model: refactor "get next thread" code
[c11tester.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         params(params),
25         diverge(NULL),
26         action_trace(new action_list_t()),
27         thread_map(new HashTable<int, Thread *, int>()),
28         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
29         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
30         promises(new std::vector<Promise *>()),
31         lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
32         thrd_last_action(new std::vector<ModelAction *>(1)),
33         node_stack(new NodeStack()),
34         mo_graph(new CycleGraph()),
35         failed_promise(false),
36         asserted(false)
37 {
38         /* Allocate this "size" on the snapshotting heap */
39         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
40         /* First thread created will have id INITIAL_THREAD_ID */
41         priv->next_thread_id = INITIAL_THREAD_ID;
42
43         lazy_sync_size = &priv->lazy_sync_size;
44 }
45
46 /** @brief Destructor */
47 ModelChecker::~ModelChecker()
48 {
49         for (int i = 0; i < get_num_threads(); i++)
50                 delete thread_map->get(i);
51         delete thread_map;
52
53         delete obj_thrd_map;
54         delete obj_map;
55         delete action_trace;
56
57         for (unsigned int i = 0; i < promises->size(); i++)
58                 delete (*promises)[i];
59         delete promises;
60
61         delete lazy_sync_with_release;
62
63         delete thrd_last_action;
64         delete node_stack;
65         delete scheduler;
66         delete mo_graph;
67 }
68
69 /**
70  * Restores user program to initial state and resets all model-checker data
71  * structures.
72  */
73 void ModelChecker::reset_to_initial_state()
74 {
75         DEBUG("+++ Resetting to initial state +++\n");
76         node_stack->reset_execution();
77         failed_promise = false;
78         reset_asserted();
79         snapshotObject->backTrackBeforeStep(0);
80 }
81
82 /** @returns a thread ID for a new Thread */
83 thread_id_t ModelChecker::get_next_id()
84 {
85         return priv->next_thread_id++;
86 }
87
88 /** @returns the number of user threads created during this execution */
89 int ModelChecker::get_num_threads()
90 {
91         return priv->next_thread_id;
92 }
93
94 /** @returns a sequence number for a new ModelAction */
95 modelclock_t ModelChecker::get_next_seq_num()
96 {
97         return ++priv->used_sequence_numbers;
98 }
99
100 /**
101  * @brief Choose the next thread to execute.
102  *
103  * This function chooses the next thread that should execute. It can force the
104  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
105  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
106  * The model-checker may have no preference regarding the next thread (i.e.,
107  * when exploring a new execution ordering), in which case this will return
108  * NULL.
109  * @param curr The current ModelAction. This action might guide the choice of
110  * next thread.
111  * @return The next thread to run. If the model-checker has no preference, NULL.
112  */
113 Thread * ModelChecker::get_next_thread(ModelAction *curr)
114 {
115         thread_id_t tid;
116
117         /* Do not split atomic actions. */
118         if (curr->is_rmwr())
119                 return thread_current();
120         /* The THREAD_CREATE action points to the created Thread */
121         else if (curr->get_type() == THREAD_CREATE)
122                 return (Thread *)curr->get_location();
123
124         /* Have we completed exploring the preselected path? */
125         if (diverge == NULL)
126                 return NULL;
127
128         /* Else, we are trying to replay an execution */
129         ModelAction *next = node_stack->get_next()->get_action();
130
131         if (next == diverge) {
132                 Node *nextnode = next->get_node();
133                 /* Reached divergence point */
134                 if (nextnode->increment_promise()) {
135                         /* The next node will try to satisfy a different set of promises. */
136                         tid = next->get_tid();
137                         node_stack->pop_restofstack(2);
138                 } else if (nextnode->increment_read_from()) {
139                         /* The next node will read from a different value. */
140                         tid = next->get_tid();
141                         node_stack->pop_restofstack(2);
142                 } else if (nextnode->increment_future_value()) {
143                         /* The next node will try to read from a different future value. */
144                         tid = next->get_tid();
145                         node_stack->pop_restofstack(2);
146                 } else {
147                         /* Make a different thread execute for next step */
148                         Node *node = nextnode->get_parent();
149                         tid = node->get_next_backtrack();
150                         node_stack->pop_restofstack(1);
151                 }
152                 DEBUG("*** Divergence point ***\n");
153                 diverge = NULL;
154         } else {
155                 tid = next->get_tid();
156         }
157         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
158         ASSERT(tid != THREAD_ID_T_NONE);
159         return thread_map->get(id_to_int(tid));
160 }
161
162 /**
163  * Queries the model-checker for more executions to explore and, if one
164  * exists, resets the model-checker state to execute a new execution.
165  *
166  * @return If there are more executions to explore, return true. Otherwise,
167  * return false.
168  */
169 bool ModelChecker::next_execution()
170 {
171         DBG();
172
173         num_executions++;
174
175         if (isfinalfeasible() || DBG_ENABLED())
176                 print_summary();
177
178         if ((diverge = get_next_backtrack()) == NULL)
179                 return false;
180
181         if (DBG_ENABLED()) {
182                 printf("Next execution will diverge at:\n");
183                 diverge->print();
184         }
185
186         reset_to_initial_state();
187         return true;
188 }
189
190 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
191 {
192         action_type type = act->get_type();
193
194         switch (type) {
195                 case ATOMIC_READ:
196                 case ATOMIC_WRITE:
197                 case ATOMIC_RMW:
198                         break;
199                 default:
200                         return NULL;
201         }
202         /* linear search: from most recent to oldest */
203         action_list_t *list = obj_map->get_safe_ptr(act->get_location());
204         action_list_t::reverse_iterator rit;
205         for (rit = list->rbegin(); rit != list->rend(); rit++) {
206                 ModelAction *prev = *rit;
207                 if (act->is_synchronizing(prev))
208                         return prev;
209         }
210         return NULL;
211 }
212
213 void ModelChecker::set_backtracking(ModelAction *act)
214 {
215         ModelAction *prev;
216         Node *node;
217         Thread *t = get_thread(act->get_tid());
218
219         prev = get_last_conflict(act);
220         if (prev == NULL)
221                 return;
222
223         node = prev->get_node()->get_parent();
224
225         while (!node->is_enabled(t))
226                 t = t->get_parent();
227
228         /* Check if this has been explored already */
229         if (node->has_been_explored(t->get_id()))
230                 return;
231
232         /* Cache the latest backtracking point */
233         if (!priv->next_backtrack || *prev > *priv->next_backtrack)
234                 priv->next_backtrack = prev;
235
236         /* If this is a new backtracking point, mark the tree */
237         if (!node->set_backtrack(t->get_id()))
238                 return;
239         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
240                         prev->get_tid(), t->get_id());
241         if (DBG_ENABLED()) {
242                 prev->print();
243                 act->print();
244         }
245 }
246
247 /**
248  * Returns last backtracking point. The model checker will explore a different
249  * path for this point in the next execution.
250  * @return The ModelAction at which the next execution should diverge.
251  */
252 ModelAction * ModelChecker::get_next_backtrack()
253 {
254         ModelAction *next = priv->next_backtrack;
255         priv->next_backtrack = NULL;
256         return next;
257 }
258
259 /**
260  * This is the heart of the model checker routine. It performs model-checking
261  * actions corresponding to a given "current action." Among other processes, it
262  * calculates reads-from relationships, updates synchronization clock vectors,
263  * forms a memory_order constraints graph, and handles replay/backtrack
264  * execution when running permutations of previously-observed executions.
265  *
266  * @param curr The current action to process
267  * @return The next Thread that must be executed. May be NULL if ModelChecker
268  * makes no choice (e.g., according to replay execution, combining RMW actions,
269  * etc.)
270  */
271 Thread * ModelChecker::check_current_action(ModelAction *curr)
272 {
273         bool already_added = false;
274
275         ASSERT(curr);
276
277         if (curr->is_rmwc() || curr->is_rmw()) {
278                 ModelAction *tmp = process_rmw(curr);
279                 already_added = true;
280                 delete curr;
281                 curr = tmp;
282         } else {
283                 ModelAction *tmp = node_stack->explore_action(curr);
284                 if (tmp) {
285                         /* Discard duplicate ModelAction; use action from NodeStack */
286                         /* First restore type and order in case of RMW operation */
287                         if (curr->is_rmwr())
288                                 tmp->copy_typeandorder(curr);
289
290                         /* If we have diverged, we need to reset the clock vector. */
291                         if (diverge == NULL)
292                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
293
294                         delete curr;
295                         curr = tmp;
296                 } else {
297                         /*
298                          * Perform one-time actions when pushing new ModelAction onto
299                          * NodeStack
300                          */
301                         curr->create_cv(get_parent_action(curr->get_tid()));
302                         /* Build may_read_from set */
303                         if (curr->is_read())
304                                 build_reads_from_past(curr);
305                         if (curr->is_write())
306                                 compute_promises(curr);
307                 }
308         }
309
310         /* Assign 'creation' parent */
311         if (curr->get_type() == THREAD_CREATE) {
312                 Thread *th = (Thread *)curr->get_location();
313                 th->set_creation(curr);
314         } else if (curr->get_type() == THREAD_JOIN) {
315                 Thread *wait, *join;
316                 wait = get_thread(curr->get_tid());
317                 join = (Thread *)curr->get_location();
318                 if (!join->is_complete())
319                         scheduler->wait(wait, join);
320         } else if (curr->get_type() == THREAD_FINISH) {
321                 Thread *th = get_thread(curr->get_tid());
322                 while (!th->wait_list_empty()) {
323                         Thread *wake = th->pop_wait_list();
324                         scheduler->wake(wake);
325                 }
326                 th->complete();
327         }
328
329         /* Deal with new thread */
330         if (curr->get_type() == THREAD_START)
331                 check_promises(NULL, curr->get_cv());
332
333         /* Assign reads_from values */
334         Thread *th = get_thread(curr->get_tid());
335         uint64_t value = VALUE_NONE;
336         bool updated = false;
337         if (curr->is_read()) {
338                 const ModelAction *reads_from = curr->get_node()->get_read_from();
339                 if (reads_from != NULL) {
340                         value = reads_from->get_value();
341                         /* Assign reads_from, perform release/acquire synchronization */
342                         curr->read_from(reads_from);
343                         if (r_modification_order(curr,reads_from))
344                                 updated = true;
345                 } else {
346                         /* Read from future value */
347                         value = curr->get_node()->get_future_value();
348                         curr->read_from(NULL);
349                         Promise *valuepromise = new Promise(curr, value);
350                         promises->push_back(valuepromise);
351                 }
352         } else if (curr->is_write()) {
353                 if (w_modification_order(curr))
354                         updated = true;
355                 if (resolve_promises(curr))
356                         updated = true;
357         }
358
359         if (updated)
360                 resolve_release_sequences(curr->get_location());
361
362         th->set_return_value(value);
363
364         /* Add action to list.  */
365         if (!already_added)
366                 add_action_to_lists(curr);
367
368         Node *currnode = curr->get_node();
369         Node *parnode = currnode->get_parent();
370
371         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
372                   !currnode->future_value_empty() || !currnode->promise_empty())
373                 if (!priv->next_backtrack || *curr > *priv->next_backtrack)
374                         priv->next_backtrack = curr;
375
376         set_backtracking(curr);
377
378         return get_next_thread(curr);
379 }
380
381 /** @returns whether the current partial trace must be a prefix of a
382  * feasible trace. */
383 bool ModelChecker::isfeasibleprefix() {
384         return promises->size() == 0 && *lazy_sync_size == 0;
385 }
386
387 /** @returns whether the current partial trace is feasible. */
388 bool ModelChecker::isfeasible() {
389         return !mo_graph->checkForCycles() && !failed_promise;
390 }
391
392 /** Returns whether the current completed trace is feasible. */
393 bool ModelChecker::isfinalfeasible() {
394         return isfeasible() && promises->size() == 0;
395 }
396
397 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
398 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
399         int tid = id_to_int(act->get_tid());
400         ModelAction *lastread = get_last_action(tid);
401         lastread->process_rmw(act);
402         if (act->is_rmw())
403                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
404         return lastread;
405 }
406
407 /**
408  * Updates the mo_graph with the constraints imposed from the current read.
409  * @param curr The current action. Must be a read.
410  * @param rf The action that curr reads from. Must be a write.
411  * @return True if modification order edges were added; false otherwise
412  */
413 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
414 {
415         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
416         unsigned int i;
417         bool added = false;
418         ASSERT(curr->is_read());
419
420         /* Iterate over all threads */
421         for (i = 0; i < thrd_lists->size(); i++) {
422                 /* Iterate over actions in thread, starting from most recent */
423                 action_list_t *list = &(*thrd_lists)[i];
424                 action_list_t::reverse_iterator rit;
425                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
426                         ModelAction *act = *rit;
427
428                         /* Include at most one act per-thread that "happens before" curr */
429                         if (act->happens_before(curr)) {
430                                 if (act->is_read()) {
431                                         const ModelAction *prevreadfrom = act->get_reads_from();
432                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
433                                                 mo_graph->addEdge(prevreadfrom, rf);
434                                                 added = true;
435                                         }
436                                 } else if (rf != act) {
437                                         mo_graph->addEdge(act, rf);
438                                         added = true;
439                                 }
440                                 break;
441                         }
442                 }
443         }
444
445         return added;
446 }
447
448 /** Updates the mo_graph with the constraints imposed from the current read. */
449 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
450 {
451         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
452         unsigned int i;
453         ASSERT(curr->is_read());
454
455         /* Iterate over all threads */
456         for (i = 0; i < thrd_lists->size(); i++) {
457                 /* Iterate over actions in thread, starting from most recent */
458                 action_list_t *list = &(*thrd_lists)[i];
459                 action_list_t::reverse_iterator rit;
460                 ModelAction *lastact = NULL;
461
462                 /* Find last action that happens after curr */
463                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
464                         ModelAction *act = *rit;
465                         if (curr->happens_before(act)) {
466                                 lastact = act;
467                         } else
468                                 break;
469                 }
470
471                         /* Include at most one act per-thread that "happens before" curr */
472                 if (lastact != NULL) {
473                         if (lastact->is_read()) {
474                                 const ModelAction *postreadfrom = lastact->get_reads_from();
475                                 if (postreadfrom != NULL&&rf != postreadfrom)
476                                         mo_graph->addEdge(rf, postreadfrom);
477                         } else if (rf != lastact) {
478                                 mo_graph->addEdge(rf, lastact);
479                         }
480                         break;
481                 }
482         }
483 }
484
485 /**
486  * Updates the mo_graph with the constraints imposed from the current write.
487  * @param curr The current action. Must be a write.
488  * @return True if modification order edges were added; false otherwise
489  */
490 bool ModelChecker::w_modification_order(ModelAction *curr)
491 {
492         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
493         unsigned int i;
494         bool added = false;
495         ASSERT(curr->is_write());
496
497         if (curr->is_seqcst()) {
498                 /* We have to at least see the last sequentially consistent write,
499                          so we are initialized. */
500                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
501                 if (last_seq_cst != NULL) {
502                         mo_graph->addEdge(last_seq_cst, curr);
503                         added = true;
504                 }
505         }
506
507         /* Iterate over all threads */
508         for (i = 0; i < thrd_lists->size(); i++) {
509                 /* Iterate over actions in thread, starting from most recent */
510                 action_list_t *list = &(*thrd_lists)[i];
511                 action_list_t::reverse_iterator rit;
512                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
513                         ModelAction *act = *rit;
514
515                         /* Include at most one act per-thread that "happens before" curr */
516                         if (act->happens_before(curr)) {
517                                 if (act->is_read())
518                                         mo_graph->addEdge(act->get_reads_from(), curr);
519                                 else
520                                         mo_graph->addEdge(act, curr);
521                                 added = true;
522                                 break;
523                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
524                                                      !act->same_thread(curr)) {
525                                 /* We have an action that:
526                                    (1) did not happen before us
527                                    (2) is a read and we are a write
528                                    (3) cannot synchronize with us
529                                    (4) is in a different thread
530                                    =>
531                                    that read could potentially read from our write.
532                                  */
533                                 if (act->get_node()->add_future_value(curr->get_value()) &&
534                                                 (!priv->next_backtrack || *act > *priv->next_backtrack))
535                                         priv->next_backtrack = act;
536                         }
537                 }
538         }
539
540         return added;
541 }
542
543 /**
544  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
545  * The ModelAction under consideration is expected to be taking part in
546  * release/acquire synchronization as an object of the "reads from" relation.
547  * Note that this can only provide release sequence support for RMW chains
548  * which do not read from the future, as those actions cannot be traced until
549  * their "promise" is fulfilled. Similarly, we may not even establish the
550  * presence of a release sequence with certainty, as some modification order
551  * constraints may be decided further in the future. Thus, this function
552  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
553  * and a boolean representing certainty.
554  *
555  * @todo Finish lazy updating, when promises are fulfilled in the future
556  * @param rf The action that might be part of a release sequence. Must be a
557  * write.
558  * @param release_heads A pass-by-reference style return parameter.  After
559  * execution of this function, release_heads will contain the heads of all the
560  * relevant release sequences, if any exists
561  * @return true, if the ModelChecker is certain that release_heads is complete;
562  * false otherwise
563  */
564 bool ModelChecker::release_seq_head(const ModelAction *rf,
565                 std::vector<const ModelAction *> *release_heads) const
566 {
567         ASSERT(rf->is_write());
568         if (!rf) {
569                 /* read from future: need to settle this later */
570                 return false; /* incomplete */
571         }
572         if (rf->is_release())
573                 release_heads->push_back(rf);
574         if (rf->is_rmw()) {
575                 /* We need a RMW action that is both an acquire and release to stop */
576                 /** @todo Need to be smarter here...  In the linux lock
577                  * example, this will run to the beginning of the program for
578                  * every acquire. */
579                 if (rf->is_acquire() && rf->is_release())
580                         return true; /* complete */
581                 return release_seq_head(rf->get_reads_from(), release_heads);
582         }
583         if (rf->is_release())
584                 return true; /* complete */
585
586         /* else relaxed write; check modification order for contiguous subsequence
587          * -> rf must be same thread as release */
588         int tid = id_to_int(rf->get_tid());
589         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
590         action_list_t *list = &(*thrd_lists)[tid];
591         action_list_t::const_reverse_iterator rit;
592
593         /* Find rf in the thread list */
594         rit = std::find(list->rbegin(), list->rend(), rf);
595         ASSERT(rit != list->rend());
596
597         /* Find the last write/release */
598         for (; rit != list->rend(); rit++)
599                 if ((*rit)->is_release())
600                         break;
601         if (rit == list->rend()) {
602                 /* No write-release in this thread */
603                 return true; /* complete */
604         }
605         ModelAction *release = *rit;
606
607         ASSERT(rf->same_thread(release));
608
609         bool certain = true;
610         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
611                 if (id_to_int(rf->get_tid()) == (int)i)
612                         continue;
613                 list = &(*thrd_lists)[i];
614
615                 /* Can we ensure no future writes from this thread may break
616                  * the release seq? */
617                 bool future_ordered = false;
618
619                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
620                         const ModelAction *act = *rit;
621                         if (!act->is_write())
622                                 continue;
623                         /* Reach synchronization -> this thread is complete */
624                         if (act->happens_before(release))
625                                 break;
626                         if (rf->happens_before(act)) {
627                                 future_ordered = true;
628                                 continue;
629                         }
630
631                         /* Check modification order */
632                         if (mo_graph->checkReachable(rf, act)) {
633                                 /* rf --mo--> act */
634                                 future_ordered = true;
635                                 continue;
636                         }
637                         if (mo_graph->checkReachable(act, release))
638                                 /* act --mo--> release */
639                                 break;
640                         if (mo_graph->checkReachable(release, act) &&
641                                       mo_graph->checkReachable(act, rf)) {
642                                 /* release --mo-> act --mo--> rf */
643                                 return true; /* complete */
644                         }
645                         certain = false;
646                 }
647                 if (!future_ordered)
648                         return false; /* This thread is uncertain */
649         }
650
651         if (certain)
652                 release_heads->push_back(release);
653         return certain;
654 }
655
656 /**
657  * A public interface for getting the release sequence head(s) with which a
658  * given ModelAction must synchronize. This function only returns a non-empty
659  * result when it can locate a release sequence head with certainty. Otherwise,
660  * it may mark the internal state of the ModelChecker so that it will handle
661  * the release sequence at a later time, causing @a act to update its
662  * synchronization at some later point in execution.
663  * @param act The 'acquire' action that may read from a release sequence
664  * @param release_heads A pass-by-reference return parameter. Will be filled
665  * with the head(s) of the release sequence(s), if they exists with certainty.
666  * @see ModelChecker::release_seq_head
667  */
668 void ModelChecker::get_release_seq_heads(ModelAction *act,
669                 std::vector<const ModelAction *> *release_heads)
670 {
671         const ModelAction *rf = act->get_reads_from();
672         bool complete;
673         complete = release_seq_head(rf, release_heads);
674         if (!complete) {
675                 /* add act to 'lazy checking' list */
676                 std::list<ModelAction *> *list;
677                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
678                 list->push_back(act);
679                 (*lazy_sync_size)++;
680         }
681 }
682
683 /**
684  * Attempt to resolve all stashed operations that might synchronize with a
685  * release sequence for a given location. This implements the "lazy" portion of
686  * determining whether or not a release sequence was contiguous, since not all
687  * modification order information is present at the time an action occurs.
688  *
689  * @param location The location/object that should be checked for release
690  * sequence resolutions
691  * @return True if any updates occurred (new synchronization, new mo_graph edges)
692  */
693 bool ModelChecker::resolve_release_sequences(void *location)
694 {
695         std::list<ModelAction *> *list;
696         list = lazy_sync_with_release->getptr(location);
697         if (!list)
698                 return false;
699
700         bool updated = false;
701         std::list<ModelAction *>::iterator it = list->begin();
702         while (it != list->end()) {
703                 ModelAction *act = *it;
704                 const ModelAction *rf = act->get_reads_from();
705                 std::vector<const ModelAction *> release_heads;
706                 bool complete;
707                 complete = release_seq_head(rf, &release_heads);
708                 for (unsigned int i = 0; i < release_heads.size(); i++) {
709                         if (!act->has_synchronized_with(release_heads[i])) {
710                                 updated = true;
711                                 act->synchronize_with(release_heads[i]);
712                         }
713                 }
714
715                 if (updated) {
716                         /* propagate synchronization to later actions */
717                         action_list_t::reverse_iterator it = action_trace->rbegin();
718                         while ((*it) != act) {
719                                 ModelAction *propagate = *it;
720                                 if (act->happens_before(propagate))
721                                         /** @todo new mo_graph edges along with
722                                          * this synchronization? */
723                                         propagate->synchronize_with(act);
724                         }
725                 }
726                 if (complete) {
727                         it = list->erase(it);
728                         (*lazy_sync_size)--;
729                 } else
730                         it++;
731         }
732
733         // If we resolved promises or data races, see if we have realized a data race.
734         if (checkDataRaces()) {
735                 set_assert();
736         }
737
738         return updated;
739 }
740
741 /**
742  * Performs various bookkeeping operations for the current ModelAction. For
743  * instance, adds action to the per-object, per-thread action vector and to the
744  * action trace list of all thread actions.
745  *
746  * @param act is the ModelAction to add.
747  */
748 void ModelChecker::add_action_to_lists(ModelAction *act)
749 {
750         int tid = id_to_int(act->get_tid());
751         action_trace->push_back(act);
752
753         obj_map->get_safe_ptr(act->get_location())->push_back(act);
754
755         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
756         if (tid >= (int)vec->size())
757                 vec->resize(priv->next_thread_id);
758         (*vec)[tid].push_back(act);
759
760         if ((int)thrd_last_action->size() <= tid)
761                 thrd_last_action->resize(get_num_threads());
762         (*thrd_last_action)[tid] = act;
763 }
764
765 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
766 {
767         int nthreads = get_num_threads();
768         if ((int)thrd_last_action->size() < nthreads)
769                 thrd_last_action->resize(nthreads);
770         return (*thrd_last_action)[id_to_int(tid)];
771 }
772
773 /**
774  * Gets the last memory_order_seq_cst action (in the total global sequence)
775  * performed on a particular object (i.e., memory location).
776  * @param location The object location to check
777  * @return The last seq_cst action performed
778  */
779 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
780 {
781         action_list_t *list = obj_map->get_safe_ptr(location);
782         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
783         action_list_t::reverse_iterator rit;
784         for (rit = list->rbegin(); rit != list->rend(); rit++)
785                 if ((*rit)->is_write() && (*rit)->is_seqcst())
786                         return *rit;
787         return NULL;
788 }
789
790 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
791 {
792         ModelAction *parent = get_last_action(tid);
793         if (!parent)
794                 parent = get_thread(tid)->get_creation();
795         return parent;
796 }
797
798 /**
799  * Returns the clock vector for a given thread.
800  * @param tid The thread whose clock vector we want
801  * @return Desired clock vector
802  */
803 ClockVector * ModelChecker::get_cv(thread_id_t tid)
804 {
805         return get_parent_action(tid)->get_cv();
806 }
807
808 /**
809  * Resolve a set of Promises with a current write. The set is provided in the
810  * Node corresponding to @a write.
811  * @param write The ModelAction that is fulfilling Promises
812  * @return True if promises were resolved; false otherwise
813  */
814 bool ModelChecker::resolve_promises(ModelAction *write)
815 {
816         bool resolved = false;
817         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
818                 Promise *promise = (*promises)[promise_index];
819                 if (write->get_node()->get_promise(i)) {
820                         ModelAction *read = promise->get_action();
821                         read->read_from(write);
822                         r_modification_order(read, write);
823                         post_r_modification_order(read, write);
824                         promises->erase(promises->begin() + promise_index);
825                         resolved = true;
826                 } else
827                         promise_index++;
828         }
829
830         return resolved;
831 }
832
833 /**
834  * Compute the set of promises that could potentially be satisfied by this
835  * action. Note that the set computation actually appears in the Node, not in
836  * ModelChecker.
837  * @param curr The ModelAction that may satisfy promises
838  */
839 void ModelChecker::compute_promises(ModelAction *curr)
840 {
841         for (unsigned int i = 0; i < promises->size(); i++) {
842                 Promise *promise = (*promises)[i];
843                 const ModelAction *act = promise->get_action();
844                 if (!act->happens_before(curr) &&
845                                 act->is_read() &&
846                                 !act->is_synchronizing(curr) &&
847                                 !act->same_thread(curr) &&
848                                 promise->get_value() == curr->get_value()) {
849                         curr->get_node()->set_promise(i);
850                 }
851         }
852 }
853
854 /** Checks promises in response to change in ClockVector Threads. */
855 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
856 {
857         for (unsigned int i = 0; i < promises->size(); i++) {
858                 Promise *promise = (*promises)[i];
859                 const ModelAction *act = promise->get_action();
860                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
861                                 merge_cv->synchronized_since(act)) {
862                         //This thread is no longer able to send values back to satisfy the promise
863                         int num_synchronized_threads = promise->increment_threads();
864                         if (num_synchronized_threads == get_num_threads()) {
865                                 //Promise has failed
866                                 failed_promise = true;
867                                 return;
868                         }
869                 }
870         }
871 }
872
873 /**
874  * Build up an initial set of all past writes that this 'read' action may read
875  * from. This set is determined by the clock vector's "happens before"
876  * relationship.
877  * @param curr is the current ModelAction that we are exploring; it must be a
878  * 'read' operation.
879  */
880 void ModelChecker::build_reads_from_past(ModelAction *curr)
881 {
882         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
883         unsigned int i;
884         ASSERT(curr->is_read());
885
886         ModelAction *last_seq_cst = NULL;
887
888         /* Track whether this object has been initialized */
889         bool initialized = false;
890
891         if (curr->is_seqcst()) {
892                 last_seq_cst = get_last_seq_cst(curr->get_location());
893                 /* We have to at least see the last sequentially consistent write,
894                          so we are initialized. */
895                 if (last_seq_cst != NULL)
896                         initialized = true;
897         }
898
899         /* Iterate over all threads */
900         for (i = 0; i < thrd_lists->size(); i++) {
901                 /* Iterate over actions in thread, starting from most recent */
902                 action_list_t *list = &(*thrd_lists)[i];
903                 action_list_t::reverse_iterator rit;
904                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
905                         ModelAction *act = *rit;
906
907                         /* Only consider 'write' actions */
908                         if (!act->is_write())
909                                 continue;
910
911                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
912                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
913                                 DEBUG("Adding action to may_read_from:\n");
914                                 if (DBG_ENABLED()) {
915                                         act->print();
916                                         curr->print();
917                                 }
918                                 curr->get_node()->add_read_from(act);
919                         }
920
921                         /* Include at most one act per-thread that "happens before" curr */
922                         if (act->happens_before(curr)) {
923                                 initialized = true;
924                                 break;
925                         }
926                 }
927         }
928
929         if (!initialized) {
930                 /** @todo Need a more informative way of reporting errors. */
931                 printf("ERROR: may read from uninitialized atomic\n");
932         }
933
934         if (DBG_ENABLED() || !initialized) {
935                 printf("Reached read action:\n");
936                 curr->print();
937                 printf("Printing may_read_from\n");
938                 curr->get_node()->print_may_read_from();
939                 printf("End printing may_read_from\n");
940         }
941
942         ASSERT(initialized);
943 }
944
945 static void print_list(action_list_t *list)
946 {
947         action_list_t::iterator it;
948
949         printf("---------------------------------------------------------------------\n");
950         printf("Trace:\n");
951
952         for (it = list->begin(); it != list->end(); it++) {
953                 (*it)->print();
954         }
955         printf("---------------------------------------------------------------------\n");
956 }
957
958 void ModelChecker::print_summary()
959 {
960         printf("\n");
961         printf("Number of executions: %d\n", num_executions);
962         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
963
964         scheduler->print();
965
966         if (!isfinalfeasible())
967                 printf("INFEASIBLE EXECUTION!\n");
968         print_list(action_trace);
969         printf("\n");
970 }
971
972 /**
973  * Add a Thread to the system for the first time. Should only be called once
974  * per thread.
975  * @param t The Thread to add
976  */
977 void ModelChecker::add_thread(Thread *t)
978 {
979         thread_map->put(id_to_int(t->get_id()), t);
980         scheduler->add_thread(t);
981 }
982
983 void ModelChecker::remove_thread(Thread *t)
984 {
985         scheduler->remove_thread(t);
986 }
987
988 /**
989  * Switch from a user-context to the "master thread" context (a.k.a. system
990  * context). This switch is made with the intention of exploring a particular
991  * model-checking action (described by a ModelAction object). Must be called
992  * from a user-thread context.
993  * @param act The current action that will be explored. Must not be NULL.
994  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
995  */
996 int ModelChecker::switch_to_master(ModelAction *act)
997 {
998         DBG();
999         Thread *old = thread_current();
1000         set_current_action(act);
1001         old->set_state(THREAD_READY);
1002         return Thread::swap(old, &system_context);
1003 }
1004
1005 /**
1006  * Takes the next step in the execution, if possible.
1007  * @return Returns true (success) if a step was taken and false otherwise.
1008  */
1009 bool ModelChecker::take_step() {
1010         Thread *curr, *next;
1011
1012         if (has_asserted())
1013                 return false;
1014
1015         curr = thread_current();
1016         if (curr) {
1017                 if (curr->get_state() == THREAD_READY) {
1018                         ASSERT(priv->current_action);
1019                         priv->nextThread = check_current_action(priv->current_action);
1020                         priv->current_action = NULL;
1021                         if (!curr->is_blocked() && !curr->is_complete())
1022                                 scheduler->add_thread(curr);
1023                 } else {
1024                         ASSERT(false);
1025                 }
1026         }
1027         next = scheduler->next_thread(priv->nextThread);
1028
1029         /* Infeasible -> don't take any more steps */
1030         if (!isfeasible())
1031                 return false;
1032
1033         if (next)
1034                 next->set_state(THREAD_RUNNING);
1035         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1036
1037         /* next == NULL -> don't take any more steps */
1038         if (!next)
1039                 return false;
1040         /* Return false only if swap fails with an error */
1041         return (Thread::swap(&system_context, next) == 0);
1042 }
1043
1044 /** Runs the current execution until threre are no more steps to take. */
1045 void ModelChecker::finish_execution() {
1046         DBG();
1047
1048         while (take_step());
1049 }