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