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