model: add curr to action lists early
[model-checker.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3
4 #include "model.h"
5 #include "action.h"
6 #include "nodestack.h"
7 #include "schedule.h"
8 #include "snapshot-interface.h"
9 #include "common.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
12 #include "promise.h"
13 #include "datarace.h"
14
15 #define INITIAL_THREAD_ID       0
16
17 ModelChecker *model;
18
19 /** @brief Constructor */
20 ModelChecker::ModelChecker(struct model_params params) :
21         /* Initialize default scheduler */
22         scheduler(new Scheduler()),
23         num_executions(0),
24         num_feasible_executions(0),
25         params(params),
26         diverge(NULL),
27         action_trace(new action_list_t()),
28         thread_map(new HashTable<int, Thread *, int>()),
29         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
30         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
31         promises(new std::vector<Promise *>()),
32         futurevalues(new std::vector<struct PendingFutureValue>()),
33         lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
34         thrd_last_action(new std::vector<ModelAction *>(1)),
35         node_stack(new NodeStack()),
36         mo_graph(new CycleGraph()),
37         failed_promise(false),
38         too_many_reads(false),
39         asserted(false)
40 {
41         /* Allocate this "size" on the snapshotting heap */
42         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
43         /* First thread created will have id INITIAL_THREAD_ID */
44         priv->next_thread_id = INITIAL_THREAD_ID;
45
46         lazy_sync_size = &priv->lazy_sync_size;
47 }
48
49 /** @brief Destructor */
50 ModelChecker::~ModelChecker()
51 {
52         for (int i = 0; i < get_num_threads(); i++)
53                 delete thread_map->get(i);
54         delete thread_map;
55
56         delete obj_thrd_map;
57         delete obj_map;
58         delete action_trace;
59
60         for (unsigned int i = 0; i < promises->size(); i++)
61                 delete (*promises)[i];
62         delete promises;
63
64         delete lazy_sync_with_release;
65
66         delete thrd_last_action;
67         delete node_stack;
68         delete scheduler;
69         delete mo_graph;
70 }
71
72 /**
73  * Restores user program to initial state and resets all model-checker data
74  * structures.
75  */
76 void ModelChecker::reset_to_initial_state()
77 {
78         DEBUG("+++ Resetting to initial state +++\n");
79         node_stack->reset_execution();
80         failed_promise = false;
81         too_many_reads = false;
82         reset_asserted();
83         snapshotObject->backTrackBeforeStep(0);
84 }
85
86 /** @returns a thread ID for a new Thread */
87 thread_id_t ModelChecker::get_next_id()
88 {
89         return priv->next_thread_id++;
90 }
91
92 /** @returns the number of user threads created during this execution */
93 int ModelChecker::get_num_threads()
94 {
95         return priv->next_thread_id;
96 }
97
98 /** @returns a sequence number for a new ModelAction */
99 modelclock_t ModelChecker::get_next_seq_num()
100 {
101         return ++priv->used_sequence_numbers;
102 }
103
104 /**
105  * @brief Choose the next thread to execute.
106  *
107  * This function chooses the next thread that should execute. It can force the
108  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
109  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
110  * The model-checker may have no preference regarding the next thread (i.e.,
111  * when exploring a new execution ordering), in which case this will return
112  * NULL.
113  * @param curr The current ModelAction. This action might guide the choice of
114  * next thread.
115  * @return The next thread to run. If the model-checker has no preference, NULL.
116  */
117 Thread * ModelChecker::get_next_thread(ModelAction *curr)
118 {
119         thread_id_t tid;
120
121         /* Do not split atomic actions. */
122         if (curr->is_rmwr())
123                 return thread_current();
124         /* The THREAD_CREATE action points to the created Thread */
125         else if (curr->get_type() == THREAD_CREATE)
126                 return (Thread *)curr->get_location();
127
128         /* Have we completed exploring the preselected path? */
129         if (diverge == NULL)
130                 return NULL;
131
132         /* Else, we are trying to replay an execution */
133         ModelAction *next = node_stack->get_next()->get_action();
134
135         if (next == diverge) {
136                 Node *nextnode = next->get_node();
137                 /* Reached divergence point */
138                 if (nextnode->increment_promise()) {
139                         /* The next node will try to satisfy a different set of promises. */
140                         tid = next->get_tid();
141                         node_stack->pop_restofstack(2);
142                 } else if (nextnode->increment_read_from()) {
143                         /* The next node will read from a different value. */
144                         tid = next->get_tid();
145                         node_stack->pop_restofstack(2);
146                 } else if (nextnode->increment_future_value()) {
147                         /* The next node will try to read from a different future value. */
148                         tid = next->get_tid();
149                         node_stack->pop_restofstack(2);
150                 } else {
151                         /* Make a different thread execute for next step */
152                         Node *node = nextnode->get_parent();
153                         tid = node->get_next_backtrack();
154                         node_stack->pop_restofstack(1);
155                 }
156                 DEBUG("*** Divergence point ***\n");
157                 diverge = NULL;
158         } else {
159                 tid = next->get_tid();
160         }
161         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
162         ASSERT(tid != THREAD_ID_T_NONE);
163         return thread_map->get(id_to_int(tid));
164 }
165
166 /**
167  * Queries the model-checker for more executions to explore and, if one
168  * exists, resets the model-checker state to execute a new execution.
169  *
170  * @return If there are more executions to explore, return true. Otherwise,
171  * return false.
172  */
173 bool ModelChecker::next_execution()
174 {
175         DBG();
176
177         num_executions++;
178         if (isfinalfeasible())
179                 num_feasible_executions++;
180
181         if (isfinalfeasible() || DBG_ENABLED())
182                 print_summary();
183
184         if ((diverge = get_next_backtrack()) == NULL)
185                 return false;
186
187         if (DBG_ENABLED()) {
188                 printf("Next execution will diverge at:\n");
189                 diverge->print();
190         }
191
192         reset_to_initial_state();
193         return true;
194 }
195
196 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
197 {
198         action_type type = act->get_type();
199
200         switch (type) {
201                 case ATOMIC_READ:
202                 case ATOMIC_WRITE:
203                 case ATOMIC_RMW:
204                         break;
205                 default:
206                         return NULL;
207         }
208         /* linear search: from most recent to oldest */
209         action_list_t *list = obj_map->get_safe_ptr(act->get_location());
210         action_list_t::reverse_iterator rit;
211         for (rit = list->rbegin(); rit != list->rend(); rit++) {
212                 ModelAction *prev = *rit;
213                 if (act->is_synchronizing(prev))
214                         return prev;
215         }
216         return NULL;
217 }
218
219 void ModelChecker::set_backtracking(ModelAction *act)
220 {
221         ModelAction *prev;
222         Node *node;
223         Thread *t = get_thread(act);
224
225         prev = get_last_conflict(act);
226         if (prev == NULL)
227                 return;
228
229         node = prev->get_node()->get_parent();
230
231         while (!node->is_enabled(t))
232                 t = t->get_parent();
233
234         /* Check if this has been explored already */
235         if (node->has_been_explored(t->get_id()))
236                 return;
237
238         /* Cache the latest backtracking point */
239         if (!priv->next_backtrack || *prev > *priv->next_backtrack)
240                 priv->next_backtrack = prev;
241
242         /* If this is a new backtracking point, mark the tree */
243         if (!node->set_backtrack(t->get_id()))
244                 return;
245         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
246                         prev->get_tid(), t->get_id());
247         if (DBG_ENABLED()) {
248                 prev->print();
249                 act->print();
250         }
251 }
252
253 /**
254  * Returns last backtracking point. The model checker will explore a different
255  * path for this point in the next execution.
256  * @return The ModelAction at which the next execution should diverge.
257  */
258 ModelAction * ModelChecker::get_next_backtrack()
259 {
260         ModelAction *next = priv->next_backtrack;
261         priv->next_backtrack = NULL;
262         return next;
263 }
264
265 /**
266  * Processes a read or rmw model action.
267  * @param curr is the read model action to process.
268  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
269  * @return True if processing this read updates the mo_graph.
270  */
271 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
272 {
273         uint64_t value;
274         bool updated = false;
275         while (true) {
276                 const ModelAction *reads_from = curr->get_node()->get_read_from();
277                 if (reads_from != NULL) {
278                         mo_graph->startChanges();
279
280                         value = reads_from->get_value();
281                         bool r_status = false;
282
283                         if (!second_part_of_rmw) {
284                                 check_recency(curr);
285                                 r_status = r_modification_order(curr, reads_from);
286                         }
287
288
289                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
290                                 mo_graph->rollbackChanges();
291                                 too_many_reads = false;
292                                 continue;
293                         }
294
295                         curr->read_from(reads_from);
296                         mo_graph->commitChanges();
297                         updated |= r_status;
298                 } else if (!second_part_of_rmw) {
299                         /* Read from future value */
300                         value = curr->get_node()->get_future_value();
301                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
302                         curr->read_from(NULL);
303                         Promise *valuepromise = new Promise(curr, value, expiration);
304                         promises->push_back(valuepromise);
305                 }
306                 get_thread(curr)->set_return_value(value);
307                 return updated;
308         }
309 }
310
311 /**
312  * Process a write ModelAction
313  * @param curr The ModelAction to process
314  * @return True if the mo_graph was updated or promises were resolved
315  */
316 bool ModelChecker::process_write(ModelAction *curr)
317 {
318         bool updated_mod_order = w_modification_order(curr);
319         bool updated_promises = resolve_promises(curr);
320
321         if (promises->size() == 0) {
322                 for (unsigned int i = 0; i<futurevalues->size(); i++) {
323                         struct PendingFutureValue pfv = (*futurevalues)[i];
324                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
325                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
326                                 priv->next_backtrack = pfv.act;
327                 }
328                 futurevalues->resize(0);
329         }
330
331         mo_graph->commitChanges();
332         get_thread(curr)->set_return_value(VALUE_NONE);
333         return updated_mod_order || updated_promises;
334 }
335
336 /**
337  * Initialize the current action by performing one or more of the following
338  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
339  * in the NodeStack, manipulating backtracking sets, allocating and
340  * initializing clock vectors, and computing the promises to fulfill.
341  *
342  * @param curr The current action, as passed from the user context; may be
343  * freed/invalidated after the execution of this function
344  * @return The current action, as processed by the ModelChecker. Is only the
345  * same as the parameter @a curr if this is a newly-explored action.
346  */
347 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
348 {
349         ModelAction *newcurr;
350
351         if (curr->is_rmwc() || curr->is_rmw()) {
352                 newcurr = process_rmw(curr);
353                 delete curr;
354                 compute_promises(newcurr);
355                 return newcurr;
356         }
357
358         newcurr = node_stack->explore_action(curr);
359         if (newcurr) {
360                 /* First restore type and order in case of RMW operation */
361                 if (curr->is_rmwr())
362                         newcurr->copy_typeandorder(curr);
363
364                 /* Discard duplicate ModelAction; use action from NodeStack */
365                 delete curr;
366
367                 /* If we have diverged, we need to reset the clock vector. */
368                 if (diverge == NULL)
369                         newcurr->create_cv(get_parent_action(newcurr->get_tid()));
370         } else {
371                 newcurr = curr;
372                 /*
373                  * Perform one-time actions when pushing new ModelAction onto
374                  * NodeStack
375                  */
376                 curr->create_cv(get_parent_action(curr->get_tid()));
377                 if (curr->is_write())
378                         compute_promises(curr);
379         }
380         return newcurr;
381 }
382
383 /**
384  * This is the heart of the model checker routine. It performs model-checking
385  * actions corresponding to a given "current action." Among other processes, it
386  * calculates reads-from relationships, updates synchronization clock vectors,
387  * forms a memory_order constraints graph, and handles replay/backtrack
388  * execution when running permutations of previously-observed executions.
389  *
390  * @param curr The current action to process
391  * @return The next Thread that must be executed. May be NULL if ModelChecker
392  * makes no choice (e.g., according to replay execution, combining RMW actions,
393  * etc.)
394  */
395 Thread * ModelChecker::check_current_action(ModelAction *curr)
396 {
397         ASSERT(curr);
398
399         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
400
401         ModelAction *newcurr = initialize_curr_action(curr);
402
403         /* Add the action to lists before any other model-checking tasks */
404         if (!second_part_of_rmw)
405                 add_action_to_lists(newcurr);
406
407         /* Build may_read_from set for newly-created actions */
408         if (curr == newcurr && curr->is_read())
409                 build_reads_from_past(curr);
410         curr = newcurr;
411
412         /* Thread specific actions */
413         switch (curr->get_type()) {
414         case THREAD_CREATE: {
415                 Thread *th = (Thread *)curr->get_location();
416                 th->set_creation(curr);
417                 break;
418         }
419         case THREAD_JOIN: {
420                 Thread *waiting, *blocking;
421                 waiting = get_thread(curr);
422                 blocking = (Thread *)curr->get_location();
423                 if (!blocking->is_complete()) {
424                         blocking->push_wait_list(curr);
425                         scheduler->sleep(waiting);
426                 }
427                 break;
428         }
429         case THREAD_FINISH: {
430                 Thread *th = get_thread(curr);
431                 while (!th->wait_list_empty()) {
432                         ModelAction *act = th->pop_wait_list();
433                         Thread *wake = get_thread(act);
434                         scheduler->wake(wake);
435                 }
436                 th->complete();
437                 break;
438         }
439         case THREAD_START: {
440                 check_promises(NULL, curr->get_cv());
441                 break;
442         }
443         default:
444                 break;
445         }
446
447         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
448
449         while (!work_queue.empty()) {
450                 WorkQueueEntry work = work_queue.front();
451                 work_queue.pop_front();
452
453                 switch (work.type) {
454                 case WORK_CHECK_CURR_ACTION: {
455                         ModelAction *act = work.action;
456                         bool updated = false;
457                         if (act->is_read() && process_read(act, second_part_of_rmw))
458                                 updated = true;
459
460                         if (act->is_write() && process_write(act))
461                                 updated = true;
462
463                         if (updated)
464                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
465                         break;
466                 }
467                 case WORK_CHECK_RELEASE_SEQ:
468                         resolve_release_sequences(work.location, &work_queue);
469                         break;
470                 case WORK_CHECK_MO_EDGES: {
471                         /** @todo Complete verification of work_queue */
472                         ModelAction *act = work.action;
473                         bool updated = false;
474
475                         if (act->is_read()) {
476                                 if (r_modification_order(act, act->get_reads_from()))
477                                         updated = true;
478                         }
479                         if (act->is_write()) {
480                                 if (w_modification_order(act))
481                                         updated = true;
482                         }
483
484                         if (updated)
485                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
486                         break;
487                 }
488                 default:
489                         ASSERT(false);
490                         break;
491                 }
492         }
493
494         check_curr_backtracking(curr);
495
496         set_backtracking(curr);
497
498         return get_next_thread(curr);
499 }
500
501 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
502         Node *currnode = curr->get_node();
503         Node *parnode = currnode->get_parent();
504
505         if ((!parnode->backtrack_empty() ||
506                          !currnode->read_from_empty() ||
507                          !currnode->future_value_empty() ||
508                          !currnode->promise_empty())
509                         && (!priv->next_backtrack ||
510                                         *curr > *priv->next_backtrack)) {
511                 priv->next_backtrack = curr;
512         }
513 }
514
515 bool ModelChecker::promises_expired() {
516         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
517                 Promise *promise = (*promises)[promise_index];
518                 if (promise->get_expiration()<priv->used_sequence_numbers) {
519                         return true;
520                 }
521         }
522         return false;
523 }
524
525 /** @returns whether the current partial trace must be a prefix of a
526  * feasible trace. */
527 bool ModelChecker::isfeasibleprefix() {
528         return promises->size() == 0 && *lazy_sync_size == 0;
529 }
530
531 /** @returns whether the current partial trace is feasible. */
532 bool ModelChecker::isfeasible() {
533         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
534 }
535
536 /** @returns whether the current partial trace is feasible other than
537  * multiple RMW reading from the same store. */
538 bool ModelChecker::isfeasibleotherthanRMW() {
539         if (DBG_ENABLED()) {
540                 if (mo_graph->checkForCycles())
541                         DEBUG("Infeasible: modification order cycles\n");
542                 if (failed_promise)
543                         DEBUG("Infeasible: failed promise\n");
544                 if (too_many_reads)
545                         DEBUG("Infeasible: too many reads\n");
546                 if (promises_expired())
547                         DEBUG("Infeasible: promises expired\n");
548         }
549         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
550 }
551
552 /** Returns whether the current completed trace is feasible. */
553 bool ModelChecker::isfinalfeasible() {
554         if (DBG_ENABLED() && promises->size() != 0)
555                 DEBUG("Infeasible: unrevolved promises\n");
556
557         return isfeasible() && promises->size() == 0;
558 }
559
560 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
561 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
562         int tid = id_to_int(act->get_tid());
563         ModelAction *lastread = get_last_action(tid);
564         lastread->process_rmw(act);
565         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
566                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
567                 mo_graph->commitChanges();
568         }
569         return lastread;
570 }
571
572 /**
573  * Checks whether a thread has read from the same write for too many times
574  * without seeing the effects of a later write.
575  *
576  * Basic idea:
577  * 1) there must a different write that we could read from that would satisfy the modification order,
578  * 2) we must have read from the same value in excess of maxreads times, and
579  * 3) that other write must have been in the reads_from set for maxreads times.
580  *
581  * If so, we decide that the execution is no longer feasible.
582  */
583 void ModelChecker::check_recency(ModelAction *curr) {
584         if (params.maxreads != 0) {
585                 if (curr->get_node()->get_read_from_size() <= 1)
586                         return;
587
588                 //Must make sure that execution is currently feasible...  We could
589                 //accidentally clear by rolling back
590                 if (!isfeasible())
591                         return;
592
593                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
594                 int tid = id_to_int(curr->get_tid());
595
596                 /* Skip checks */
597                 if ((int)thrd_lists->size() <= tid)
598                         return;
599
600                 action_list_t *list = &(*thrd_lists)[tid];
601
602                 action_list_t::reverse_iterator rit = list->rbegin();
603                 /* Skip past curr */
604                 for (; (*rit) != curr; rit++)
605                         ;
606                 /* go past curr now */
607                 rit++;
608
609                 action_list_t::reverse_iterator ritcopy = rit;
610                 //See if we have enough reads from the same value
611                 int count = 0;
612                 for (; count < params.maxreads; rit++,count++) {
613                         if (rit==list->rend())
614                                 return;
615                         ModelAction *act = *rit;
616                         if (!act->is_read())
617                                 return;
618                         if (act->get_reads_from() != curr->get_reads_from())
619                                 return;
620                         if (act->get_node()->get_read_from_size() <= 1)
621                                 return;
622                 }
623
624                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
625                         //Get write
626                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
627                         //Need a different write
628                         if (write==curr->get_reads_from())
629                                 continue;
630
631                         /* Test to see whether this is a feasible write to read from*/
632                         mo_graph->startChanges();
633                         r_modification_order(curr, write);
634                         bool feasiblereadfrom = isfeasible();
635                         mo_graph->rollbackChanges();
636
637                         if (!feasiblereadfrom)
638                                 continue;
639                         rit = ritcopy;
640
641                         bool feasiblewrite = true;
642                         //new we need to see if this write works for everyone
643
644                         for (int loop = count; loop>0; loop--,rit++) {
645                                 ModelAction *act=*rit;
646                                 bool foundvalue = false;
647                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
648                                         if (act->get_node()->get_read_from_at(i)==write) {
649                                                 foundvalue = true;
650                                                 break;
651                                         }
652                                 }
653                                 if (!foundvalue) {
654                                         feasiblewrite = false;
655                                         break;
656                                 }
657                         }
658                         if (feasiblewrite) {
659                                 too_many_reads = true;
660                                 return;
661                         }
662                 }
663         }
664 }
665
666 /**
667  * Updates the mo_graph with the constraints imposed from the current
668  * read.  
669  *
670  * Basic idea is the following: Go through each other thread and find
671  * the lastest action that happened before our read.  Two cases:
672  *
673  * (1) The action is a write => that write must either occur before
674  * the write we read from or be the write we read from.
675  *
676  * (2) The action is a read => the write that that action read from
677  * must occur before the write we read from or be the same write.
678  *
679  * @param curr The current action. Must be a read.
680  * @param rf The action that curr reads from. Must be a write.
681  * @return True if modification order edges were added; false otherwise
682  */
683 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
684 {
685         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
686         unsigned int i;
687         bool added = false;
688         ASSERT(curr->is_read());
689
690         /* Iterate over all threads */
691         for (i = 0; i < thrd_lists->size(); i++) {
692                 /* Iterate over actions in thread, starting from most recent */
693                 action_list_t *list = &(*thrd_lists)[i];
694                 action_list_t::reverse_iterator rit;
695                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
696                         ModelAction *act = *rit;
697
698                         /*
699                          * Include at most one act per-thread that "happens
700                          * before" curr. Don't consider reflexively.
701                          */
702                         if (act->happens_before(curr) && act != curr) {
703                                 if (act->is_write()) {
704                                         if (rf != act) {
705                                                 mo_graph->addEdge(act, rf);
706                                                 added = true;
707                                         }
708                                 } else {
709                                         const ModelAction *prevreadfrom = act->get_reads_from();
710                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
711                                                 mo_graph->addEdge(prevreadfrom, rf);
712                                                 added = true;
713                                         }
714                                 }
715                                 break;
716                         }
717                 }
718         }
719
720         return added;
721 }
722
723 /** This method fixes up the modification order when we resolve a
724  *  promises.  The basic problem is that actions that occur after the
725  *  read curr could not property add items to the modification order
726  *  for our read.
727  *  
728  *  So for each thread, we find the earliest item that happens after
729  *  the read curr.  This is the item we have to fix up with additional
730  *  constraints.  If that action is write, we add a MO edge between
731  *  the Action rf and that action.  If the action is a read, we add a
732  *  MO edge between the Action rf, and whatever the read accessed.
733  *
734  * @param curr is the read ModelAction that we are fixing up MO edges for.
735  * @param rf is the write ModelAction that curr reads from.
736  *
737  */
738
739 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
740 {
741         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
742         unsigned int i;
743         ASSERT(curr->is_read());
744
745         /* Iterate over all threads */
746         for (i = 0; i < thrd_lists->size(); i++) {
747                 /* Iterate over actions in thread, starting from most recent */
748                 action_list_t *list = &(*thrd_lists)[i];
749                 action_list_t::reverse_iterator rit;
750                 ModelAction *lastact = NULL;
751
752                 /* Find last action that happens after curr */
753                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
754                         ModelAction *act = *rit;
755                         if (curr->happens_before(act)) {
756                                 lastact = act;
757                         } else
758                                 break;
759                 }
760
761                         /* Include at most one act per-thread that "happens before" curr */
762                 if (lastact != NULL) {
763                         if (lastact->is_read()) {
764                                 const ModelAction *postreadfrom = lastact->get_reads_from();
765                                 if (postreadfrom != NULL&&rf != postreadfrom)
766                                         mo_graph->addEdge(rf, postreadfrom);
767                         } else if (rf != lastact) {
768                                 mo_graph->addEdge(rf, lastact);
769                         }
770                         break;
771                 }
772         }
773 }
774
775 /**
776  * Updates the mo_graph with the constraints imposed from the current write.
777  *
778  * Basic idea is the following: Go through each other thread and find
779  * the lastest action that happened before our write.  Two cases:
780  *
781  * (1) The action is a write => that write must occur before
782  * the current write
783  *
784  * (2) The action is a read => the write that that action read from
785  * must occur before the current write.
786  *
787  * This method also handles two other issues:
788  *
789  * (I) Sequential Consistency: Making sure that if the current write is
790  * seq_cst, that it occurs after the previous seq_cst write.
791  *
792  * (II) Sending the write back to non-synchronizing reads.
793  *
794  * @param curr The current action. Must be a write.
795  * @return True if modification order edges were added; false otherwise
796  */
797 bool ModelChecker::w_modification_order(ModelAction *curr)
798 {
799         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
800         unsigned int i;
801         bool added = false;
802         ASSERT(curr->is_write());
803
804         if (curr->is_seqcst()) {
805                 /* We have to at least see the last sequentially consistent write,
806                          so we are initialized. */
807                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
808                 if (last_seq_cst != NULL) {
809                         mo_graph->addEdge(last_seq_cst, curr);
810                         added = true;
811                 }
812         }
813
814         /* Iterate over all threads */
815         for (i = 0; i < thrd_lists->size(); i++) {
816                 /* Iterate over actions in thread, starting from most recent */
817                 action_list_t *list = &(*thrd_lists)[i];
818                 action_list_t::reverse_iterator rit;
819                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
820                         ModelAction *act = *rit;
821                         if (act == curr) {
822                                 /*
823                                  * If RMW, we already have all relevant edges,
824                                  * so just skip to next thread.
825                                  * If normal write, we need to look at earlier
826                                  * actions, so continue processing list.
827                                  */
828                                 if (curr->is_rmw())
829                                         break;
830                                 else
831                                         continue;
832                         }
833
834                         /*
835                          * Include at most one act per-thread that "happens
836                          * before" curr
837                          */
838                         if (act->happens_before(curr)) {
839                                 /*
840                                  * Note: if act is RMW, just add edge:
841                                  *   act --mo--> curr
842                                  * The following edge should be handled elsewhere:
843                                  *   readfrom(act) --mo--> act
844                                  */
845                                 if (act->is_write())
846                                         mo_graph->addEdge(act, curr);
847                                 else if (act->is_read() && act->get_reads_from() != NULL)
848                                         mo_graph->addEdge(act->get_reads_from(), curr);
849                                 added = true;
850                                 break;
851                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
852                                                      !act->same_thread(curr)) {
853                                 /* We have an action that:
854                                    (1) did not happen before us
855                                    (2) is a read and we are a write
856                                    (3) cannot synchronize with us
857                                    (4) is in a different thread
858                                    =>
859                                    that read could potentially read from our write.
860                                  */
861                                 if (thin_air_constraint_may_allow(curr, act)) {
862                                         if (isfeasible() ||
863                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
864                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
865                                                 futurevalues->push_back(pfv);
866                                         }
867                                 }
868                         }
869                 }
870         }
871
872         return added;
873 }
874
875 /** Arbitrary reads from the future are not allowed.  Section 29.3
876  * part 9 places some constraints.  This method checks one result of constraint
877  * constraint.  Others require compiler support. */
878
879 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
880         if (!writer->is_rmw())
881                 return true;
882
883         if (!reader->is_rmw())
884                 return true;
885
886         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
887                 if (search==reader)
888                         return false;
889                 if (search->get_tid() == reader->get_tid() &&
890                                 search->happens_before(reader))
891                         break;
892         }
893
894         return true;
895 }
896
897 /**
898  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
899  * The ModelAction under consideration is expected to be taking part in
900  * release/acquire synchronization as an object of the "reads from" relation.
901  * Note that this can only provide release sequence support for RMW chains
902  * which do not read from the future, as those actions cannot be traced until
903  * their "promise" is fulfilled. Similarly, we may not even establish the
904  * presence of a release sequence with certainty, as some modification order
905  * constraints may be decided further in the future. Thus, this function
906  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
907  * and a boolean representing certainty.
908  *
909  * @todo Finish lazy updating, when promises are fulfilled in the future
910  * @param rf The action that might be part of a release sequence. Must be a
911  * write.
912  * @param release_heads A pass-by-reference style return parameter.  After
913  * execution of this function, release_heads will contain the heads of all the
914  * relevant release sequences, if any exists
915  * @return true, if the ModelChecker is certain that release_heads is complete;
916  * false otherwise
917  */
918 bool ModelChecker::release_seq_head(const ModelAction *rf,
919                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
920 {
921         if (!rf) {
922                 /* read from future: need to settle this later */
923                 return false; /* incomplete */
924         }
925
926         ASSERT(rf->is_write());
927
928         if (rf->is_release())
929                 release_heads->push_back(rf);
930         if (rf->is_rmw()) {
931                 /* We need a RMW action that is both an acquire and release to stop */
932                 /** @todo Need to be smarter here...  In the linux lock
933                  * example, this will run to the beginning of the program for
934                  * every acquire. */
935                 if (rf->is_acquire() && rf->is_release())
936                         return true; /* complete */
937                 return release_seq_head(rf->get_reads_from(), release_heads);
938         }
939         if (rf->is_release())
940                 return true; /* complete */
941
942         /* else relaxed write; check modification order for contiguous subsequence
943          * -> rf must be same thread as release */
944         int tid = id_to_int(rf->get_tid());
945         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
946         action_list_t *list = &(*thrd_lists)[tid];
947         action_list_t::const_reverse_iterator rit;
948
949         /* Find rf in the thread list */
950         rit = std::find(list->rbegin(), list->rend(), rf);
951         ASSERT(rit != list->rend());
952
953         /* Find the last write/release */
954         for (; rit != list->rend(); rit++)
955                 if ((*rit)->is_release())
956                         break;
957         if (rit == list->rend()) {
958                 /* No write-release in this thread */
959                 return true; /* complete */
960         }
961         ModelAction *release = *rit;
962
963         ASSERT(rf->same_thread(release));
964
965         bool certain = true;
966         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
967                 if (id_to_int(rf->get_tid()) == (int)i)
968                         continue;
969                 list = &(*thrd_lists)[i];
970
971                 /* Can we ensure no future writes from this thread may break
972                  * the release seq? */
973                 bool future_ordered = false;
974
975                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
976                         const ModelAction *act = *rit;
977                         if (!act->is_write())
978                                 continue;
979                         /* Reach synchronization -> this thread is complete */
980                         if (act->happens_before(release))
981                                 break;
982                         if (rf->happens_before(act)) {
983                                 future_ordered = true;
984                                 continue;
985                         }
986
987                         /* Check modification order */
988                         if (mo_graph->checkReachable(rf, act)) {
989                                 /* rf --mo--> act */
990                                 future_ordered = true;
991                                 continue;
992                         }
993                         if (mo_graph->checkReachable(act, release))
994                                 /* act --mo--> release */
995                                 break;
996                         if (mo_graph->checkReachable(release, act) &&
997                                       mo_graph->checkReachable(act, rf)) {
998                                 /* release --mo-> act --mo--> rf */
999                                 return true; /* complete */
1000                         }
1001                         certain = false;
1002                 }
1003                 if (!future_ordered)
1004                         return false; /* This thread is uncertain */
1005         }
1006
1007         if (certain)
1008                 release_heads->push_back(release);
1009         return certain;
1010 }
1011
1012 /**
1013  * A public interface for getting the release sequence head(s) with which a
1014  * given ModelAction must synchronize. This function only returns a non-empty
1015  * result when it can locate a release sequence head with certainty. Otherwise,
1016  * it may mark the internal state of the ModelChecker so that it will handle
1017  * the release sequence at a later time, causing @a act to update its
1018  * synchronization at some later point in execution.
1019  * @param act The 'acquire' action that may read from a release sequence
1020  * @param release_heads A pass-by-reference return parameter. Will be filled
1021  * with the head(s) of the release sequence(s), if they exists with certainty.
1022  * @see ModelChecker::release_seq_head
1023  */
1024 void ModelChecker::get_release_seq_heads(ModelAction *act,
1025                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
1026 {
1027         const ModelAction *rf = act->get_reads_from();
1028         bool complete;
1029         complete = release_seq_head(rf, release_heads);
1030         if (!complete) {
1031                 /* add act to 'lazy checking' list */
1032                 std::list<ModelAction *> *list;
1033                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1034                 list->push_back(act);
1035                 (*lazy_sync_size)++;
1036         }
1037 }
1038
1039 /**
1040  * Attempt to resolve all stashed operations that might synchronize with a
1041  * release sequence for a given location. This implements the "lazy" portion of
1042  * determining whether or not a release sequence was contiguous, since not all
1043  * modification order information is present at the time an action occurs.
1044  *
1045  * @param location The location/object that should be checked for release
1046  * sequence resolutions
1047  * @param work_queue The work queue to which to add work items as they are
1048  * generated
1049  * @return True if any updates occurred (new synchronization, new mo_graph
1050  * edges)
1051  */
1052 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1053 {
1054         std::list<ModelAction *> *list;
1055         list = lazy_sync_with_release->getptr(location);
1056         if (!list)
1057                 return false;
1058
1059         bool updated = false;
1060         std::list<ModelAction *>::iterator it = list->begin();
1061         while (it != list->end()) {
1062                 ModelAction *act = *it;
1063                 const ModelAction *rf = act->get_reads_from();
1064                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
1065                 bool complete;
1066                 complete = release_seq_head(rf, &release_heads);
1067                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1068                         if (!act->has_synchronized_with(release_heads[i])) {
1069                                 updated = true;
1070                                 act->synchronize_with(release_heads[i]);
1071                         }
1072                 }
1073
1074                 if (updated) {
1075                         /* Re-check act for mo_graph edges */
1076                         work_queue->push_back(MOEdgeWorkEntry(act));
1077
1078                         /* propagate synchronization to later actions */
1079                         action_list_t::reverse_iterator it = action_trace->rbegin();
1080                         while ((*it) != act) {
1081                                 ModelAction *propagate = *it;
1082                                 if (act->happens_before(propagate)) {
1083                                         propagate->synchronize_with(act);
1084                                         /* Re-check 'propagate' for mo_graph edges */
1085                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1086                                 }
1087                         }
1088                 }
1089                 if (complete) {
1090                         it = list->erase(it);
1091                         (*lazy_sync_size)--;
1092                 } else
1093                         it++;
1094         }
1095
1096         // If we resolved promises or data races, see if we have realized a data race.
1097         if (checkDataRaces()) {
1098                 set_assert();
1099         }
1100
1101         return updated;
1102 }
1103
1104 /**
1105  * Performs various bookkeeping operations for the current ModelAction. For
1106  * instance, adds action to the per-object, per-thread action vector and to the
1107  * action trace list of all thread actions.
1108  *
1109  * @param act is the ModelAction to add.
1110  */
1111 void ModelChecker::add_action_to_lists(ModelAction *act)
1112 {
1113         int tid = id_to_int(act->get_tid());
1114         action_trace->push_back(act);
1115
1116         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1117
1118         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1119         if (tid >= (int)vec->size())
1120                 vec->resize(priv->next_thread_id);
1121         (*vec)[tid].push_back(act);
1122
1123         if ((int)thrd_last_action->size() <= tid)
1124                 thrd_last_action->resize(get_num_threads());
1125         (*thrd_last_action)[tid] = act;
1126 }
1127
1128 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1129 {
1130         int nthreads = get_num_threads();
1131         if ((int)thrd_last_action->size() < nthreads)
1132                 thrd_last_action->resize(nthreads);
1133         return (*thrd_last_action)[id_to_int(tid)];
1134 }
1135
1136 /**
1137  * Gets the last memory_order_seq_cst write (in the total global sequence)
1138  * performed on a particular object (i.e., memory location), not including the
1139  * current action.
1140  * @param curr The current ModelAction; also denotes the object location to
1141  * check
1142  * @return The last seq_cst write
1143  */
1144 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1145 {
1146         void *location = curr->get_location();
1147         action_list_t *list = obj_map->get_safe_ptr(location);
1148         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1149         action_list_t::reverse_iterator rit;
1150         for (rit = list->rbegin(); rit != list->rend(); rit++)
1151                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1152                         return *rit;
1153         return NULL;
1154 }
1155
1156 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1157 {
1158         ModelAction *parent = get_last_action(tid);
1159         if (!parent)
1160                 parent = get_thread(tid)->get_creation();
1161         return parent;
1162 }
1163
1164 /**
1165  * Returns the clock vector for a given thread.
1166  * @param tid The thread whose clock vector we want
1167  * @return Desired clock vector
1168  */
1169 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1170 {
1171         return get_parent_action(tid)->get_cv();
1172 }
1173
1174 /**
1175  * Resolve a set of Promises with a current write. The set is provided in the
1176  * Node corresponding to @a write.
1177  * @param write The ModelAction that is fulfilling Promises
1178  * @return True if promises were resolved; false otherwise
1179  */
1180 bool ModelChecker::resolve_promises(ModelAction *write)
1181 {
1182         bool resolved = false;
1183
1184         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1185                 Promise *promise = (*promises)[promise_index];
1186                 if (write->get_node()->get_promise(i)) {
1187                         ModelAction *read = promise->get_action();
1188                         read->read_from(write);
1189                         if (read->is_rmw()) {
1190                                 mo_graph->addRMWEdge(write, read);
1191                         }
1192                         //First fix up the modification order for actions that happened
1193                         //before the read
1194                         r_modification_order(read, write);
1195                         //Next fix up the modification order for actions that happened
1196                         //after the read.
1197                         post_r_modification_order(read, write);
1198                         promises->erase(promises->begin() + promise_index);
1199                         resolved = true;
1200                 } else
1201                         promise_index++;
1202         }
1203         return resolved;
1204 }
1205
1206 /**
1207  * Compute the set of promises that could potentially be satisfied by this
1208  * action. Note that the set computation actually appears in the Node, not in
1209  * ModelChecker.
1210  * @param curr The ModelAction that may satisfy promises
1211  */
1212 void ModelChecker::compute_promises(ModelAction *curr)
1213 {
1214         for (unsigned int i = 0; i < promises->size(); i++) {
1215                 Promise *promise = (*promises)[i];
1216                 const ModelAction *act = promise->get_action();
1217                 if (!act->happens_before(curr) &&
1218                                 act->is_read() &&
1219                                 !act->is_synchronizing(curr) &&
1220                                 !act->same_thread(curr) &&
1221                                 promise->get_value() == curr->get_value()) {
1222                         curr->get_node()->set_promise(i);
1223                 }
1224         }
1225 }
1226
1227 /** Checks promises in response to change in ClockVector Threads. */
1228 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1229 {
1230         for (unsigned int i = 0; i < promises->size(); i++) {
1231                 Promise *promise = (*promises)[i];
1232                 const ModelAction *act = promise->get_action();
1233                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1234                                 merge_cv->synchronized_since(act)) {
1235                         //This thread is no longer able to send values back to satisfy the promise
1236                         int num_synchronized_threads = promise->increment_threads();
1237                         if (num_synchronized_threads == get_num_threads()) {
1238                                 //Promise has failed
1239                                 failed_promise = true;
1240                                 return;
1241                         }
1242                 }
1243         }
1244 }
1245
1246 /**
1247  * Build up an initial set of all past writes that this 'read' action may read
1248  * from. This set is determined by the clock vector's "happens before"
1249  * relationship.
1250  * @param curr is the current ModelAction that we are exploring; it must be a
1251  * 'read' operation.
1252  */
1253 void ModelChecker::build_reads_from_past(ModelAction *curr)
1254 {
1255         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1256         unsigned int i;
1257         ASSERT(curr->is_read());
1258
1259         ModelAction *last_seq_cst = NULL;
1260
1261         /* Track whether this object has been initialized */
1262         bool initialized = false;
1263
1264         if (curr->is_seqcst()) {
1265                 last_seq_cst = get_last_seq_cst(curr);
1266                 /* We have to at least see the last sequentially consistent write,
1267                          so we are initialized. */
1268                 if (last_seq_cst != NULL)
1269                         initialized = true;
1270         }
1271
1272         /* Iterate over all threads */
1273         for (i = 0; i < thrd_lists->size(); i++) {
1274                 /* Iterate over actions in thread, starting from most recent */
1275                 action_list_t *list = &(*thrd_lists)[i];
1276                 action_list_t::reverse_iterator rit;
1277                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1278                         ModelAction *act = *rit;
1279
1280                         /* Only consider 'write' actions */
1281                         if (!act->is_write() || act == curr)
1282                                 continue;
1283
1284                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1285                         if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1286                                 DEBUG("Adding action to may_read_from:\n");
1287                                 if (DBG_ENABLED()) {
1288                                         act->print();
1289                                         curr->print();
1290                                 }
1291                                 curr->get_node()->add_read_from(act);
1292                         }
1293
1294                         /* Include at most one act per-thread that "happens before" curr */
1295                         if (act->happens_before(curr)) {
1296                                 initialized = true;
1297                                 break;
1298                         }
1299                 }
1300         }
1301
1302         if (!initialized) {
1303                 /** @todo Need a more informative way of reporting errors. */
1304                 printf("ERROR: may read from uninitialized atomic\n");
1305         }
1306
1307         if (DBG_ENABLED() || !initialized) {
1308                 printf("Reached read action:\n");
1309                 curr->print();
1310                 printf("Printing may_read_from\n");
1311                 curr->get_node()->print_may_read_from();
1312                 printf("End printing may_read_from\n");
1313         }
1314
1315         ASSERT(initialized);
1316 }
1317
1318 static void print_list(action_list_t *list)
1319 {
1320         action_list_t::iterator it;
1321
1322         printf("---------------------------------------------------------------------\n");
1323         printf("Trace:\n");
1324
1325         for (it = list->begin(); it != list->end(); it++) {
1326                 (*it)->print();
1327         }
1328         printf("---------------------------------------------------------------------\n");
1329 }
1330
1331 void ModelChecker::print_summary()
1332 {
1333         printf("\n");
1334         printf("Number of executions: %d\n", num_executions);
1335         printf("Number of feasible executions: %d\n", num_feasible_executions);
1336         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1337
1338 #if SUPPORT_MOD_ORDER_DUMP
1339         scheduler->print();
1340         char buffername[100];
1341         sprintf(buffername, "exec%u",num_executions);
1342         mo_graph->dumpGraphToFile(buffername);
1343 #endif
1344
1345         if (!isfinalfeasible())
1346                 printf("INFEASIBLE EXECUTION!\n");
1347         print_list(action_trace);
1348         printf("\n");
1349 }
1350
1351 /**
1352  * Add a Thread to the system for the first time. Should only be called once
1353  * per thread.
1354  * @param t The Thread to add
1355  */
1356 void ModelChecker::add_thread(Thread *t)
1357 {
1358         thread_map->put(id_to_int(t->get_id()), t);
1359         scheduler->add_thread(t);
1360 }
1361
1362 void ModelChecker::remove_thread(Thread *t)
1363 {
1364         scheduler->remove_thread(t);
1365 }
1366
1367 /**
1368  * Switch from a user-context to the "master thread" context (a.k.a. system
1369  * context). This switch is made with the intention of exploring a particular
1370  * model-checking action (described by a ModelAction object). Must be called
1371  * from a user-thread context.
1372  * @param act The current action that will be explored. Must not be NULL.
1373  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1374  */
1375 int ModelChecker::switch_to_master(ModelAction *act)
1376 {
1377         DBG();
1378         Thread *old = thread_current();
1379         set_current_action(act);
1380         old->set_state(THREAD_READY);
1381         return Thread::swap(old, &system_context);
1382 }
1383
1384 /**
1385  * Takes the next step in the execution, if possible.
1386  * @return Returns true (success) if a step was taken and false otherwise.
1387  */
1388 bool ModelChecker::take_step() {
1389         Thread *curr, *next;
1390
1391         if (has_asserted())
1392                 return false;
1393
1394         curr = thread_current();
1395         if (curr) {
1396                 if (curr->get_state() == THREAD_READY) {
1397                         ASSERT(priv->current_action);
1398
1399                         priv->nextThread = check_current_action(priv->current_action);
1400                         priv->current_action = NULL;
1401                         if (!curr->is_blocked() && !curr->is_complete())
1402                                 scheduler->add_thread(curr);
1403                 } else {
1404                         ASSERT(false);
1405                 }
1406         }
1407         next = scheduler->next_thread(priv->nextThread);
1408
1409         /* Infeasible -> don't take any more steps */
1410         if (!isfeasible())
1411                 return false;
1412
1413         if (next)
1414                 next->set_state(THREAD_RUNNING);
1415         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1416
1417         /* next == NULL -> don't take any more steps */
1418         if (!next)
1419                 return false;
1420         /* Return false only if swap fails with an error */
1421         return (Thread::swap(&system_context, next) == 0);
1422 }
1423
1424 /** Runs the current execution until threre are no more steps to take. */
1425 void ModelChecker::finish_execution() {
1426         DBG();
1427
1428         while (take_step());
1429 }