Add yield block support. The idea is to not generate executions with yield actions.
[model-checker.git] / execution.cc
1 #include <stdio.h>
2 #include <algorithm>
3 #include <mutex>
4 #include <new>
5 #include <stdarg.h>
6
7 #include "model.h"
8 #include "execution.h"
9 #include "action.h"
10 #include "nodestack.h"
11 #include "schedule.h"
12 #include "common.h"
13 #include "clockvector.h"
14 #include "cyclegraph.h"
15 #include "promise.h"
16 #include "datarace.h"
17 #include "threads-model.h"
18 #include "bugmessage.h"
19
20 #define INITIAL_THREAD_ID       0
21
22 /**
23  * Structure for holding small ModelChecker members that should be snapshotted
24  */
25 struct model_snapshot_members {
26         model_snapshot_members() :
27                 /* First thread created will have id INITIAL_THREAD_ID */
28                 next_thread_id(INITIAL_THREAD_ID),
29                 used_sequence_numbers(0),
30                 next_backtrack(NULL),
31                 bugs(),
32                 failed_promise(false),
33                 too_many_reads(false),
34                 no_valid_reads(false),
35                 bad_synchronization(false),
36                 asserted(false)
37         { }
38
39         ~model_snapshot_members() {
40                 for (unsigned int i = 0; i < bugs.size(); i++)
41                         delete bugs[i];
42                 bugs.clear();
43         }
44
45         unsigned int next_thread_id;
46         modelclock_t used_sequence_numbers;
47         ModelAction *next_backtrack;
48         SnapVector<bug_message *> bugs;
49         bool failed_promise;
50         bool too_many_reads;
51         bool no_valid_reads;
52         /** @brief Incorrectly-ordered synchronization was made */
53         bool bad_synchronization;
54         bool asserted;
55
56         SNAPSHOTALLOC
57 };
58
59 /** @brief Constructor */
60 ModelExecution::ModelExecution(ModelChecker *m,
61                 const struct model_params *params,
62                 Scheduler *scheduler,
63                 NodeStack *node_stack) :
64         model(m),
65         params(params),
66         scheduler(scheduler),
67         action_trace(),
68         thread_map(2), /* We'll always need at least 2 threads */
69         obj_map(),
70         condvar_waiters_map(),
71         obj_thrd_map(),
72         promises(),
73         futurevalues(),
74         pending_rel_seqs(),
75         thrd_last_action(1),
76         thrd_last_fence_release(),
77         node_stack(node_stack),
78         priv(new struct model_snapshot_members()),
79         mo_graph(new CycleGraph())
80 {
81         /* Initialize a model-checker thread, for special ModelActions */
82         model_thread = new Thread(get_next_id());
83         add_thread(model_thread);
84         scheduler->register_engine(this);
85         node_stack->register_engine(this);
86 }
87
88 /** @brief Destructor */
89 ModelExecution::~ModelExecution()
90 {
91         for (unsigned int i = 0; i < get_num_threads(); i++)
92                 delete get_thread(int_to_id(i));
93
94         for (unsigned int i = 0; i < promises.size(); i++)
95                 delete promises[i];
96
97         delete mo_graph;
98         delete priv;
99 }
100
101 int ModelExecution::get_execution_number() const
102 {
103         return model->get_execution_number();
104 }
105
106 static action_list_t * get_safe_ptr_action(HashTable<const void *, action_list_t *, uintptr_t, 4> * hash, void * ptr)
107 {
108         action_list_t *tmp = hash->get(ptr);
109         if (tmp == NULL) {
110                 tmp = new action_list_t();
111                 hash->put(ptr, tmp);
112         }
113         return tmp;
114 }
115
116 static SnapVector<action_list_t> * get_safe_ptr_vect_action(HashTable<void *, SnapVector<action_list_t> *, uintptr_t, 4> * hash, void * ptr)
117 {
118         SnapVector<action_list_t> *tmp = hash->get(ptr);
119         if (tmp == NULL) {
120                 tmp = new SnapVector<action_list_t>();
121                 hash->put(ptr, tmp);
122         }
123         return tmp;
124 }
125
126 action_list_t * ModelExecution::get_actions_on_obj(void * obj, thread_id_t tid) const
127 {
128         SnapVector<action_list_t> *wrv = obj_thrd_map.get(obj);
129         if (wrv==NULL)
130                 return NULL;
131         unsigned int thread=id_to_int(tid);
132         if (thread < wrv->size())
133                 return &(*wrv)[thread];
134         else
135                 return NULL;
136 }
137
138 /** @return a thread ID for a new Thread */
139 thread_id_t ModelExecution::get_next_id()
140 {
141         return priv->next_thread_id++;
142 }
143
144 /** @return the number of user threads created during this execution */
145 unsigned int ModelExecution::get_num_threads() const
146 {
147         return priv->next_thread_id;
148 }
149
150 /** @return a sequence number for a new ModelAction */
151 modelclock_t ModelExecution::get_next_seq_num()
152 {
153         return ++priv->used_sequence_numbers;
154 }
155
156 /**
157  * @brief Should the current action wake up a given thread?
158  *
159  * @param curr The current action
160  * @param thread The thread that we might wake up
161  * @return True, if we should wake up the sleeping thread; false otherwise
162  */
163 bool ModelExecution::should_wake_up(const ModelAction *curr, const Thread *thread) const
164 {
165         const ModelAction *asleep = thread->get_pending();
166         /* Don't allow partial RMW to wake anyone up */
167         if (curr->is_rmwr())
168                 return false;
169         /* Synchronizing actions may have been backtracked */
170         if (asleep->could_synchronize_with(curr))
171                 return true;
172         /* All acquire/release fences and fence-acquire/store-release */
173         if (asleep->is_fence() && asleep->is_acquire() && curr->is_release())
174                 return true;
175         /* Fence-release + store can awake load-acquire on the same location */
176         if (asleep->is_read() && asleep->is_acquire() && curr->same_var(asleep) && curr->is_write()) {
177                 ModelAction *fence_release = get_last_fence_release(curr->get_tid());
178                 if (fence_release && *(get_last_action(thread->get_id())) < *fence_release)
179                         return true;
180         }
181         return false;
182 }
183
184 void ModelExecution::wake_up_sleeping_actions(ModelAction *curr)
185 {
186         for (unsigned int i = 0; i < get_num_threads(); i++) {
187                 Thread *thr = get_thread(int_to_id(i));
188                 if (scheduler->is_sleep_set(thr)) {
189                         if (should_wake_up(curr, thr))
190                                 /* Remove this thread from sleep set */
191                                 scheduler->remove_sleep(thr);
192                 }
193         }
194 }
195
196 /** @brief Alert the model-checker that an incorrectly-ordered
197  * synchronization was made */
198 void ModelExecution::set_bad_synchronization()
199 {
200         priv->bad_synchronization = true;
201 }
202
203 bool ModelExecution::assert_bug(const char *msg)
204 {
205         priv->bugs.push_back(new bug_message(msg));
206
207         if (isfeasibleprefix()) {
208                 set_assert();
209                 return true;
210         }
211         return false;
212 }
213
214 /** @return True, if any bugs have been reported for this execution */
215 bool ModelExecution::have_bug_reports() const
216 {
217         return priv->bugs.size() != 0;
218 }
219
220 SnapVector<bug_message *> * ModelExecution::get_bugs() const
221 {
222         return &priv->bugs;
223 }
224
225 /**
226  * Check whether the current trace has triggered an assertion which should halt
227  * its execution.
228  *
229  * @return True, if the execution should be aborted; false otherwise
230  */
231 bool ModelExecution::has_asserted() const
232 {
233         return priv->asserted;
234 }
235
236 /**
237  * Trigger a trace assertion which should cause this execution to be halted.
238  * This can be due to a detected bug or due to an infeasibility that should
239  * halt ASAP.
240  */
241 void ModelExecution::set_assert()
242 {
243         priv->asserted = true;
244 }
245
246 /**
247  * Check if we are in a deadlock. Should only be called at the end of an
248  * execution, although it should not give false positives in the middle of an
249  * execution (there should be some ENABLED thread).
250  *
251  * @return True if program is in a deadlock; false otherwise
252  */
253 bool ModelExecution::is_deadlocked() const
254 {
255         bool blocking_threads = false;
256         for (unsigned int i = 0; i < get_num_threads(); i++) {
257                 thread_id_t tid = int_to_id(i);
258                 if (is_enabled(tid))
259                         return false;
260                 Thread *t = get_thread(tid);
261                 if (!t->is_model_thread() && t->get_pending())
262                         blocking_threads = true;
263         }
264         return blocking_threads;
265 }
266
267 bool ModelExecution::is_yieldblocked() const
268 {
269         for (unsigned int i = 0; i < get_num_threads(); i++) {
270                 thread_id_t tid = int_to_id(i);
271                 Thread *t = get_thread(tid);
272                 if (t->get_pending() && t->get_pending()->is_yield())
273                         return true;
274         }
275         return false;
276 }
277
278 /**
279  * Check if this is a complete execution. That is, have all thread completed
280  * execution (rather than exiting because sleep sets have forced a redundant
281  * execution).
282  *
283  * @return True if the execution is complete.
284  */
285 bool ModelExecution::is_complete_execution() const
286 {
287         if (params->yieldblock && is_yieldblocked())
288                 return false;
289         for (unsigned int i = 0; i < get_num_threads(); i++)
290                 if (is_enabled(int_to_id(i)))
291                         return false;
292         return true;
293 }
294
295 /**
296  * @brief Find the last fence-related backtracking conflict for a ModelAction
297  *
298  * This function performs the search for the most recent conflicting action
299  * against which we should perform backtracking, as affected by fence
300  * operations. This includes pairs of potentially-synchronizing actions which
301  * occur due to fence-acquire or fence-release, and hence should be explored in
302  * the opposite execution order.
303  *
304  * @param act The current action
305  * @return The most recent action which conflicts with act due to fences
306  */
307 ModelAction * ModelExecution::get_last_fence_conflict(ModelAction *act) const
308 {
309         /* Only perform release/acquire fence backtracking for stores */
310         if (!act->is_write())
311                 return NULL;
312
313         /* Find a fence-release (or, act is a release) */
314         ModelAction *last_release;
315         if (act->is_release())
316                 last_release = act;
317         else
318                 last_release = get_last_fence_release(act->get_tid());
319         if (!last_release)
320                 return NULL;
321
322         /* Skip past the release */
323         const action_list_t *list = &action_trace;
324         action_list_t::const_reverse_iterator rit;
325         for (rit = list->rbegin(); rit != list->rend(); rit++)
326                 if (*rit == last_release)
327                         break;
328         ASSERT(rit != list->rend());
329
330         /* Find a prior:
331          *   load-acquire
332          * or
333          *   load --sb-> fence-acquire */
334         ModelVector<ModelAction *> acquire_fences(get_num_threads(), NULL);
335         ModelVector<ModelAction *> prior_loads(get_num_threads(), NULL);
336         bool found_acquire_fences = false;
337         for ( ; rit != list->rend(); rit++) {
338                 ModelAction *prev = *rit;
339                 if (act->same_thread(prev))
340                         continue;
341
342                 int tid = id_to_int(prev->get_tid());
343
344                 if (prev->is_read() && act->same_var(prev)) {
345                         if (prev->is_acquire()) {
346                                 /* Found most recent load-acquire, don't need
347                                  * to search for more fences */
348                                 if (!found_acquire_fences)
349                                         return NULL;
350                         } else {
351                                 prior_loads[tid] = prev;
352                         }
353                 }
354                 if (prev->is_acquire() && prev->is_fence() && !acquire_fences[tid]) {
355                         found_acquire_fences = true;
356                         acquire_fences[tid] = prev;
357                 }
358         }
359
360         ModelAction *latest_backtrack = NULL;
361         for (unsigned int i = 0; i < acquire_fences.size(); i++)
362                 if (acquire_fences[i] && prior_loads[i])
363                         if (!latest_backtrack || *latest_backtrack < *acquire_fences[i])
364                                 latest_backtrack = acquire_fences[i];
365         return latest_backtrack;
366 }
367
368 /**
369  * @brief Find the last backtracking conflict for a ModelAction
370  *
371  * This function performs the search for the most recent conflicting action
372  * against which we should perform backtracking. This primary includes pairs of
373  * synchronizing actions which should be explored in the opposite execution
374  * order.
375  *
376  * @param act The current action
377  * @return The most recent action which conflicts with act
378  */
379 ModelAction * ModelExecution::get_last_conflict(ModelAction *act) const
380 {
381         switch (act->get_type()) {
382         case ATOMIC_FENCE:
383                 /* Only seq-cst fences can (directly) cause backtracking */
384                 if (!act->is_seqcst())
385                         break;
386         case ATOMIC_READ:
387         case ATOMIC_WRITE:
388         case ATOMIC_RMW: {
389                 ModelAction *ret = NULL;
390
391                 /* linear search: from most recent to oldest */
392                 action_list_t *list = obj_map.get(act->get_location());
393                 action_list_t::reverse_iterator rit;
394                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
395                         ModelAction *prev = *rit;
396                         if (prev == act)
397                                 continue;
398                         if (prev->could_synchronize_with(act)) {
399                                 ret = prev;
400                                 break;
401                         }
402                 }
403
404                 ModelAction *ret2 = get_last_fence_conflict(act);
405                 if (!ret2)
406                         return ret;
407                 if (!ret)
408                         return ret2;
409                 if (*ret < *ret2)
410                         return ret2;
411                 return ret;
412         }
413         case ATOMIC_LOCK:
414         case ATOMIC_TRYLOCK: {
415                 /* linear search: from most recent to oldest */
416                 action_list_t *list = obj_map.get(act->get_location());
417                 action_list_t::reverse_iterator rit;
418                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
419                         ModelAction *prev = *rit;
420                         if (act->is_conflicting_lock(prev))
421                                 return prev;
422                 }
423                 break;
424         }
425         case ATOMIC_UNLOCK: {
426                 /* linear search: from most recent to oldest */
427                 action_list_t *list = obj_map.get(act->get_location());
428                 action_list_t::reverse_iterator rit;
429                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
430                         ModelAction *prev = *rit;
431                         if (!act->same_thread(prev) && prev->is_failed_trylock())
432                                 return prev;
433                 }
434                 break;
435         }
436         case ATOMIC_WAIT: {
437                 /* linear search: from most recent to oldest */
438                 action_list_t *list = obj_map.get(act->get_location());
439                 action_list_t::reverse_iterator rit;
440                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
441                         ModelAction *prev = *rit;
442                         if (!act->same_thread(prev) && prev->is_failed_trylock())
443                                 return prev;
444                         if (!act->same_thread(prev) && prev->is_notify())
445                                 return prev;
446                 }
447                 break;
448         }
449
450         case ATOMIC_NOTIFY_ALL:
451         case ATOMIC_NOTIFY_ONE: {
452                 /* linear search: from most recent to oldest */
453                 action_list_t *list = obj_map.get(act->get_location());
454                 action_list_t::reverse_iterator rit;
455                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
456                         ModelAction *prev = *rit;
457                         if (!act->same_thread(prev) && prev->is_wait())
458                                 return prev;
459                 }
460                 break;
461         }
462         default:
463                 break;
464         }
465         return NULL;
466 }
467
468 /** This method finds backtracking points where we should try to
469  * reorder the parameter ModelAction against.
470  *
471  * @param the ModelAction to find backtracking points for.
472  */
473 void ModelExecution::set_backtracking(ModelAction *act)
474 {
475         Thread *t = get_thread(act);
476         ModelAction *prev = get_last_conflict(act);
477         if (prev == NULL)
478                 return;
479
480         Node *node = prev->get_node()->get_parent();
481
482         /* See Dynamic Partial Order Reduction (addendum), POPL '05 */
483         int low_tid, high_tid;
484         if (node->enabled_status(t->get_id()) == THREAD_ENABLED) {
485                 low_tid = id_to_int(act->get_tid());
486                 high_tid = low_tid + 1;
487         } else {
488                 low_tid = 0;
489                 high_tid = get_num_threads();
490         }
491
492         for (int i = low_tid; i < high_tid; i++) {
493                 thread_id_t tid = int_to_id(i);
494
495                 /* Make sure this thread can be enabled here. */
496                 if (i >= node->get_num_threads())
497                         break;
498
499                 /* See Dynamic Partial Order Reduction (addendum), POPL '05 */
500                 /* Don't backtrack into a point where the thread is disabled or sleeping. */
501                 if (node->enabled_status(tid) != THREAD_ENABLED)
502                         continue;
503
504                 /* Check if this has been explored already */
505                 if (node->has_been_explored(tid))
506                         continue;
507
508                 /* See if fairness allows */
509                 if (params->fairwindow != 0 && !node->has_priority(tid)) {
510                         bool unfair = false;
511                         for (int t = 0; t < node->get_num_threads(); t++) {
512                                 thread_id_t tother = int_to_id(t);
513                                 if (node->is_enabled(tother) && node->has_priority(tother)) {
514                                         unfair = true;
515                                         break;
516                                 }
517                         }
518                         if (unfair)
519                                 continue;
520                 }
521
522                 /* See if CHESS-like yield fairness allows */
523                 if (params->yieldon) {
524                         bool unfair = false;
525                         for (int t = 0; t < node->get_num_threads(); t++) {
526                                 thread_id_t tother = int_to_id(t);
527                                 if (node->is_enabled(tother) && node->has_priority_over(tid, tother)) {
528                                         unfair = true;
529                                         break;
530                                 }
531                         }
532                         if (unfair)
533                                 continue;
534                 }
535
536                 /* Cache the latest backtracking point */
537                 set_latest_backtrack(prev);
538
539                 /* If this is a new backtracking point, mark the tree */
540                 if (!node->set_backtrack(tid))
541                         continue;
542                 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
543                                         id_to_int(prev->get_tid()),
544                                         id_to_int(t->get_id()));
545                 if (DBG_ENABLED()) {
546                         prev->print();
547                         act->print();
548                 }
549         }
550 }
551
552 /**
553  * @brief Cache the a backtracking point as the "most recent", if eligible
554  *
555  * Note that this does not prepare the NodeStack for this backtracking
556  * operation, it only caches the action on a per-execution basis
557  *
558  * @param act The operation at which we should explore a different next action
559  * (i.e., backtracking point)
560  * @return True, if this action is now the most recent backtracking point;
561  * false otherwise
562  */
563 bool ModelExecution::set_latest_backtrack(ModelAction *act)
564 {
565         if (!priv->next_backtrack || *act > *priv->next_backtrack) {
566                 priv->next_backtrack = act;
567                 return true;
568         }
569         return false;
570 }
571
572 /**
573  * Returns last backtracking point. The model checker will explore a different
574  * path for this point in the next execution.
575  * @return The ModelAction at which the next execution should diverge.
576  */
577 ModelAction * ModelExecution::get_next_backtrack()
578 {
579         ModelAction *next = priv->next_backtrack;
580         priv->next_backtrack = NULL;
581         return next;
582 }
583
584 /**
585  * Processes a read model action.
586  * @param curr is the read model action to process.
587  * @return True if processing this read updates the mo_graph.
588  */
589 bool ModelExecution::process_read(ModelAction *curr)
590 {
591         Node *node = curr->get_node();
592         while (true) {
593                 bool updated = false;
594                 switch (node->get_read_from_status()) {
595                 case READ_FROM_PAST: {
596                         const ModelAction *rf = node->get_read_from_past();
597                         ASSERT(rf);
598
599                         mo_graph->startChanges();
600
601                         ASSERT(!is_infeasible());
602                         if (!check_recency(curr, rf)) {
603                                 if (node->increment_read_from()) {
604                                         mo_graph->rollbackChanges();
605                                         continue;
606                                 } else {
607                                         priv->too_many_reads = true;
608                                 }
609                         }
610
611                         updated = r_modification_order(curr, rf);
612                         read_from(curr, rf);
613                         mo_graph->commitChanges();
614                         mo_check_promises(curr, true);
615                         break;
616                 }
617                 case READ_FROM_PROMISE: {
618                         Promise *promise = curr->get_node()->get_read_from_promise();
619                         if (promise->add_reader(curr))
620                                 priv->failed_promise = true;
621                         curr->set_read_from_promise(promise);
622                         mo_graph->startChanges();
623                         if (!check_recency(curr, promise))
624                                 priv->too_many_reads = true;
625                         updated = r_modification_order(curr, promise);
626                         mo_graph->commitChanges();
627                         break;
628                 }
629                 case READ_FROM_FUTURE: {
630                         /* Read from future value */
631                         struct future_value fv = node->get_future_value();
632                         Promise *promise = new Promise(this, curr, fv);
633                         curr->set_read_from_promise(promise);
634                         promises.push_back(promise);
635                         mo_graph->startChanges();
636                         updated = r_modification_order(curr, promise);
637                         mo_graph->commitChanges();
638                         break;
639                 }
640                 default:
641                         ASSERT(false);
642                 }
643                 get_thread(curr)->set_return_value(curr->get_return_value());
644                 return updated;
645         }
646 }
647
648 /**
649  * Processes a lock, trylock, or unlock model action.  @param curr is
650  * the read model action to process.
651  *
652  * The try lock operation checks whether the lock is taken.  If not,
653  * it falls to the normal lock operation case.  If so, it returns
654  * fail.
655  *
656  * The lock operation has already been checked that it is enabled, so
657  * it just grabs the lock and synchronizes with the previous unlock.
658  *
659  * The unlock operation has to re-enable all of the threads that are
660  * waiting on the lock.
661  *
662  * @return True if synchronization was updated; false otherwise
663  */
664 bool ModelExecution::process_mutex(ModelAction *curr)
665 {
666         std::mutex *mutex = curr->get_mutex();
667         struct std::mutex_state *state = NULL;
668
669         if (mutex)
670                 state = mutex->get_state();
671
672         switch (curr->get_type()) {
673         case ATOMIC_TRYLOCK: {
674                 bool success = !state->locked;
675                 curr->set_try_lock(success);
676                 if (!success) {
677                         get_thread(curr)->set_return_value(0);
678                         break;
679                 }
680                 get_thread(curr)->set_return_value(1);
681         }
682                 //otherwise fall into the lock case
683         case ATOMIC_LOCK: {
684                 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock)
685                         assert_bug("Lock access before initialization");
686                 state->locked = get_thread(curr);
687                 ModelAction *unlock = get_last_unlock(curr);
688                 //synchronize with the previous unlock statement
689                 if (unlock != NULL) {
690                         synchronize(unlock, curr);
691                         return true;
692                 }
693                 break;
694         }
695         case ATOMIC_WAIT:
696         case ATOMIC_UNLOCK: {
697                 /* wake up the other threads */
698                 for (unsigned int i = 0; i < get_num_threads(); i++) {
699                         Thread *t = get_thread(int_to_id(i));
700                         Thread *curr_thrd = get_thread(curr);
701                         if (t->waiting_on() == curr_thrd && t->get_pending()->is_lock())
702                                 scheduler->wake(t);
703                 }
704
705                 /* unlock the lock - after checking who was waiting on it */
706                 state->locked = NULL;
707
708                 if (!curr->is_wait())
709                         break; /* The rest is only for ATOMIC_WAIT */
710
711                 /* Should we go to sleep? (simulate spurious failures) */
712                 if (curr->get_node()->get_misc() == 0) {
713                         get_safe_ptr_action(&condvar_waiters_map, curr->get_location())->push_back(curr);
714                         /* disable us */
715                         scheduler->sleep(get_thread(curr));
716                 }
717                 break;
718         }
719         case ATOMIC_NOTIFY_ALL: {
720                 action_list_t *waiters = get_safe_ptr_action(&condvar_waiters_map, curr->get_location());
721                 //activate all the waiting threads
722                 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
723                         scheduler->wake(get_thread(*rit));
724                 }
725                 waiters->clear();
726                 break;
727         }
728         case ATOMIC_NOTIFY_ONE: {
729                 action_list_t *waiters = get_safe_ptr_action(&condvar_waiters_map, curr->get_location());
730                 int wakeupthread = curr->get_node()->get_misc();
731                 action_list_t::iterator it = waiters->begin();
732                 advance(it, wakeupthread);
733                 scheduler->wake(get_thread(*it));
734                 waiters->erase(it);
735                 break;
736         }
737
738         default:
739                 ASSERT(0);
740         }
741         return false;
742 }
743
744 /**
745  * @brief Check if the current pending promises allow a future value to be sent
746  *
747  * If one of the following is true:
748  *  (a) there are no pending promises
749  *  (b) the reader and writer do not cross any promises
750  * Then, it is safe to pass a future value back now.
751  *
752  * Otherwise, we must save the pending future value until (a) or (b) is true
753  *
754  * @param writer The operation which sends the future value. Must be a write.
755  * @param reader The operation which will observe the value. Must be a read.
756  * @return True if the future value can be sent now; false if it must wait.
757  */
758 bool ModelExecution::promises_may_allow(const ModelAction *writer,
759                 const ModelAction *reader) const
760 {
761         if (promises.empty())
762                 return true;
763         for (int i = promises.size() - 1; i >= 0; i--) {
764                 ModelAction *pr = promises[i]->get_reader(0);
765                 //reader is after promise...doesn't cross any promise
766                 if (*reader > *pr)
767                         return true;
768                 //writer is after promise, reader before...bad...
769                 if (*writer > *pr)
770                         return false;
771         }
772         return true;
773 }
774
775 /**
776  * @brief Add a future value to a reader
777  *
778  * This function performs a few additional checks to ensure that the future
779  * value can be feasibly observed by the reader
780  *
781  * @param writer The operation whose value is sent. Must be a write.
782  * @param reader The read operation which may read the future value. Must be a read.
783  */
784 void ModelExecution::add_future_value(const ModelAction *writer, ModelAction *reader)
785 {
786         /* Do more ambitious checks now that mo is more complete */
787         if (!mo_may_allow(writer, reader))
788                 return;
789
790         Node *node = reader->get_node();
791
792         /* Find an ancestor thread which exists at the time of the reader */
793         Thread *write_thread = get_thread(writer);
794         while (id_to_int(write_thread->get_id()) >= node->get_num_threads())
795                 write_thread = write_thread->get_parent();
796
797         struct future_value fv = {
798                 writer->get_write_value(),
799                 writer->get_seq_number() + params->maxfuturedelay,
800                 write_thread->get_id(),
801         };
802         if (node->add_future_value(fv))
803                 set_latest_backtrack(reader);
804 }
805
806 /**
807  * Process a write ModelAction
808  * @param curr The ModelAction to process
809  * @return True if the mo_graph was updated or promises were resolved
810  */
811 bool ModelExecution::process_write(ModelAction *curr)
812 {
813         /* Readers to which we may send our future value */
814         ModelVector<ModelAction *> send_fv;
815
816         const ModelAction *earliest_promise_reader;
817         bool updated_promises = false;
818
819         bool updated_mod_order = w_modification_order(curr, &send_fv);
820         Promise *promise = pop_promise_to_resolve(curr);
821
822         if (promise) {
823                 earliest_promise_reader = promise->get_reader(0);
824                 updated_promises = resolve_promise(curr, promise);
825         } else
826                 earliest_promise_reader = NULL;
827
828         for (unsigned int i = 0; i < send_fv.size(); i++) {
829                 ModelAction *read = send_fv[i];
830
831                 /* Don't send future values to reads after the Promise we resolve */
832                 if (!earliest_promise_reader || *read < *earliest_promise_reader) {
833                         /* Check if future value can be sent immediately */
834                         if (promises_may_allow(curr, read)) {
835                                 add_future_value(curr, read);
836                         } else {
837                                 futurevalues.push_back(PendingFutureValue(curr, read));
838                         }
839                 }
840         }
841
842         /* Check the pending future values */
843         for (int i = (int)futurevalues.size() - 1; i >= 0; i--) {
844                 struct PendingFutureValue pfv = futurevalues[i];
845                 if (promises_may_allow(pfv.writer, pfv.reader)) {
846                         add_future_value(pfv.writer, pfv.reader);
847                         futurevalues.erase(futurevalues.begin() + i);
848                 }
849         }
850
851         mo_graph->commitChanges();
852         mo_check_promises(curr, false);
853
854         get_thread(curr)->set_return_value(VALUE_NONE);
855         return updated_mod_order || updated_promises;
856 }
857
858 /**
859  * Process a fence ModelAction
860  * @param curr The ModelAction to process
861  * @return True if synchronization was updated
862  */
863 bool ModelExecution::process_fence(ModelAction *curr)
864 {
865         /*
866          * fence-relaxed: no-op
867          * fence-release: only log the occurence (not in this function), for
868          *   use in later synchronization
869          * fence-acquire (this function): search for hypothetical release
870          *   sequences
871          * fence-seq-cst: MO constraints formed in {r,w}_modification_order
872          */
873         bool updated = false;
874         if (curr->is_acquire()) {
875                 action_list_t *list = &action_trace;
876                 action_list_t::reverse_iterator rit;
877                 /* Find X : is_read(X) && X --sb-> curr */
878                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
879                         ModelAction *act = *rit;
880                         if (act == curr)
881                                 continue;
882                         if (act->get_tid() != curr->get_tid())
883                                 continue;
884                         /* Stop at the beginning of the thread */
885                         if (act->is_thread_start())
886                                 break;
887                         /* Stop once we reach a prior fence-acquire */
888                         if (act->is_fence() && act->is_acquire())
889                                 break;
890                         if (!act->is_read())
891                                 continue;
892                         /* read-acquire will find its own release sequences */
893                         if (act->is_acquire())
894                                 continue;
895
896                         /* Establish hypothetical release sequences */
897                         rel_heads_list_t release_heads;
898                         get_release_seq_heads(curr, act, &release_heads);
899                         for (unsigned int i = 0; i < release_heads.size(); i++)
900                                 synchronize(release_heads[i], curr);
901                         if (release_heads.size() != 0)
902                                 updated = true;
903                 }
904         }
905         return updated;
906 }
907
908 /**
909  * @brief Process the current action for thread-related activity
910  *
911  * Performs current-action processing for a THREAD_* ModelAction. Proccesses
912  * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
913  * synchronization, etc.  This function is a no-op for non-THREAD actions
914  * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
915  *
916  * @param curr The current action
917  * @return True if synchronization was updated or a thread completed
918  */
919 bool ModelExecution::process_thread_action(ModelAction *curr)
920 {
921         bool updated = false;
922
923         switch (curr->get_type()) {
924         case THREAD_CREATE: {
925                 thrd_t *thrd = (thrd_t *)curr->get_location();
926                 struct thread_params *params = (struct thread_params *)curr->get_value();
927                 Thread *th = new Thread(get_next_id(), thrd, params->func, params->arg, get_thread(curr));
928                 add_thread(th);
929                 th->set_creation(curr);
930                 /* Promises can be satisfied by children */
931                 for (unsigned int i = 0; i < promises.size(); i++) {
932                         Promise *promise = promises[i];
933                         if (promise->thread_is_available(curr->get_tid()))
934                                 promise->add_thread(th->get_id());
935                 }
936                 break;
937         }
938         case THREAD_JOIN: {
939                 Thread *blocking = curr->get_thread_operand();
940                 ModelAction *act = get_last_action(blocking->get_id());
941                 synchronize(act, curr);
942                 updated = true; /* trigger rel-seq checks */
943                 break;
944         }
945         case THREAD_FINISH: {
946                 Thread *th = get_thread(curr);
947                 /* Wake up any joining threads */
948                 for (unsigned int i = 0; i < get_num_threads(); i++) {
949                         Thread *waiting = get_thread(int_to_id(i));
950                         if (waiting->waiting_on() == th &&
951                                         waiting->get_pending()->is_thread_join())
952                                 scheduler->wake(waiting);
953                 }
954                 th->complete();
955                 /* Completed thread can't satisfy promises */
956                 for (unsigned int i = 0; i < promises.size(); i++) {
957                         Promise *promise = promises[i];
958                         if (promise->thread_is_available(th->get_id()))
959                                 if (promise->eliminate_thread(th->get_id()))
960                                         priv->failed_promise = true;
961                 }
962                 updated = true; /* trigger rel-seq checks */
963                 break;
964         }
965         case THREAD_START: {
966                 check_promises(curr->get_tid(), NULL, curr->get_cv());
967                 break;
968         }
969         default:
970                 break;
971         }
972
973         return updated;
974 }
975
976 /**
977  * @brief Process the current action for release sequence fixup activity
978  *
979  * Performs model-checker release sequence fixups for the current action,
980  * forcing a single pending release sequence to break (with a given, potential
981  * "loose" write) or to complete (i.e., synchronize). If a pending release
982  * sequence forms a complete release sequence, then we must perform the fixup
983  * synchronization, mo_graph additions, etc.
984  *
985  * @param curr The current action; must be a release sequence fixup action
986  * @param work_queue The work queue to which to add work items as they are
987  * generated
988  */
989 void ModelExecution::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
990 {
991         const ModelAction *write = curr->get_node()->get_relseq_break();
992         struct release_seq *sequence = pending_rel_seqs.back();
993         pending_rel_seqs.pop_back();
994         ASSERT(sequence);
995         ModelAction *acquire = sequence->acquire;
996         const ModelAction *rf = sequence->rf;
997         const ModelAction *release = sequence->release;
998         ASSERT(acquire);
999         ASSERT(release);
1000         ASSERT(rf);
1001         ASSERT(release->same_thread(rf));
1002
1003         if (write == NULL) {
1004                 /**
1005                  * @todo Forcing a synchronization requires that we set
1006                  * modification order constraints. For instance, we can't allow
1007                  * a fixup sequence in which two separate read-acquire
1008                  * operations read from the same sequence, where the first one
1009                  * synchronizes and the other doesn't. Essentially, we can't
1010                  * allow any writes to insert themselves between 'release' and
1011                  * 'rf'
1012                  */
1013
1014                 /* Must synchronize */
1015                 if (!synchronize(release, acquire))
1016                         return;
1017                 /* Re-check all pending release sequences */
1018                 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1019                 /* Re-check act for mo_graph edges */
1020                 work_queue->push_back(MOEdgeWorkEntry(acquire));
1021
1022                 /* propagate synchronization to later actions */
1023                 action_list_t::reverse_iterator rit = action_trace.rbegin();
1024                 for (; (*rit) != acquire; rit++) {
1025                         ModelAction *propagate = *rit;
1026                         if (acquire->happens_before(propagate)) {
1027                                 synchronize(acquire, propagate);
1028                                 /* Re-check 'propagate' for mo_graph edges */
1029                                 work_queue->push_back(MOEdgeWorkEntry(propagate));
1030                         }
1031                 }
1032         } else {
1033                 /* Break release sequence with new edges:
1034                  *   release --mo--> write --mo--> rf */
1035                 mo_graph->addEdge(release, write);
1036                 mo_graph->addEdge(write, rf);
1037         }
1038
1039         /* See if we have realized a data race */
1040         checkDataRaces();
1041 }
1042
1043 /**
1044  * Initialize the current action by performing one or more of the following
1045  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
1046  * in the NodeStack, manipulating backtracking sets, allocating and
1047  * initializing clock vectors, and computing the promises to fulfill.
1048  *
1049  * @param curr The current action, as passed from the user context; may be
1050  * freed/invalidated after the execution of this function, with a different
1051  * action "returned" its place (pass-by-reference)
1052  * @return True if curr is a newly-explored action; false otherwise
1053  */
1054 bool ModelExecution::initialize_curr_action(ModelAction **curr)
1055 {
1056         ModelAction *newcurr;
1057
1058         if ((*curr)->is_rmwc() || (*curr)->is_rmw()) {
1059                 newcurr = process_rmw(*curr);
1060                 delete *curr;
1061
1062                 if (newcurr->is_rmw())
1063                         compute_promises(newcurr);
1064
1065                 *curr = newcurr;
1066                 return false;
1067         }
1068
1069         (*curr)->set_seq_number(get_next_seq_num());
1070
1071         newcurr = node_stack->explore_action(*curr, scheduler->get_enabled_array());
1072         if (newcurr) {
1073                 /* First restore type and order in case of RMW operation */
1074                 if ((*curr)->is_rmwr())
1075                         newcurr->copy_typeandorder(*curr);
1076
1077                 ASSERT((*curr)->get_location() == newcurr->get_location());
1078                 newcurr->copy_from_new(*curr);
1079
1080                 /* Discard duplicate ModelAction; use action from NodeStack */
1081                 delete *curr;
1082
1083                 /* Always compute new clock vector */
1084                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
1085
1086                 *curr = newcurr;
1087                 return false; /* Action was explored previously */
1088         } else {
1089                 newcurr = *curr;
1090
1091                 /* Always compute new clock vector */
1092                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
1093
1094                 /* Assign most recent release fence */
1095                 newcurr->set_last_fence_release(get_last_fence_release(newcurr->get_tid()));
1096
1097                 /*
1098                  * Perform one-time actions when pushing new ModelAction onto
1099                  * NodeStack
1100                  */
1101                 if (newcurr->is_write())
1102                         compute_promises(newcurr);
1103                 else if (newcurr->is_relseq_fixup())
1104                         compute_relseq_breakwrites(newcurr);
1105                 else if (newcurr->is_wait())
1106                         newcurr->get_node()->set_misc_max(2);
1107                 else if (newcurr->is_notify_one()) {
1108                         newcurr->get_node()->set_misc_max(get_safe_ptr_action(&condvar_waiters_map, newcurr->get_location())->size());
1109                 }
1110                 return true; /* This was a new ModelAction */
1111         }
1112 }
1113
1114 /**
1115  * @brief Establish reads-from relation between two actions
1116  *
1117  * Perform basic operations involved with establishing a concrete rf relation,
1118  * including setting the ModelAction data and checking for release sequences.
1119  *
1120  * @param act The action that is reading (must be a read)
1121  * @param rf The action from which we are reading (must be a write)
1122  *
1123  * @return True if this read established synchronization
1124  */
1125 bool ModelExecution::read_from(ModelAction *act, const ModelAction *rf)
1126 {
1127         ASSERT(rf);
1128         ASSERT(rf->is_write());
1129
1130         act->set_read_from(rf);
1131         if (act->is_acquire()) {
1132                 rel_heads_list_t release_heads;
1133                 get_release_seq_heads(act, act, &release_heads);
1134                 int num_heads = release_heads.size();
1135                 for (unsigned int i = 0; i < release_heads.size(); i++)
1136                         if (!synchronize(release_heads[i], act))
1137                                 num_heads--;
1138                 return num_heads > 0;
1139         }
1140         return false;
1141 }
1142
1143 /**
1144  * @brief Synchronizes two actions
1145  *
1146  * When A synchronizes with B (or A --sw-> B), B inherits A's clock vector.
1147  * This function performs the synchronization as well as providing other hooks
1148  * for other checks along with synchronization.
1149  *
1150  * @param first The left-hand side of the synchronizes-with relation
1151  * @param second The right-hand side of the synchronizes-with relation
1152  * @return True if the synchronization was successful (i.e., was consistent
1153  * with the execution order); false otherwise
1154  */
1155 bool ModelExecution::synchronize(const ModelAction *first, ModelAction *second)
1156 {
1157         if (*second < *first) {
1158                 set_bad_synchronization();
1159                 return false;
1160         }
1161         check_promises(first->get_tid(), second->get_cv(), first->get_cv());
1162         return second->synchronize_with(first);
1163 }
1164
1165 /**
1166  * Check promises and eliminate potentially-satisfying threads when a thread is
1167  * blocked (e.g., join, lock). A thread which is waiting on another thread can
1168  * no longer satisfy a promise generated from that thread.
1169  *
1170  * @param blocker The thread on which a thread is waiting
1171  * @param waiting The waiting thread
1172  */
1173 void ModelExecution::thread_blocking_check_promises(Thread *blocker, Thread *waiting)
1174 {
1175         for (unsigned int i = 0; i < promises.size(); i++) {
1176                 Promise *promise = promises[i];
1177                 if (!promise->thread_is_available(waiting->get_id()))
1178                         continue;
1179                 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
1180                         ModelAction *reader = promise->get_reader(j);
1181                         if (reader->get_tid() != blocker->get_id())
1182                                 continue;
1183                         if (promise->eliminate_thread(waiting->get_id())) {
1184                                 /* Promise has failed */
1185                                 priv->failed_promise = true;
1186                         } else {
1187                                 /* Only eliminate the 'waiting' thread once */
1188                                 return;
1189                         }
1190                 }
1191         }
1192 }
1193
1194 /**
1195  * @brief Check whether a model action is enabled.
1196  *
1197  * Checks whether a lock or join operation would be successful (i.e., is the
1198  * lock already locked, or is the joined thread already complete). If not, put
1199  * the action in a waiter list.
1200  *
1201  * @param curr is the ModelAction to check whether it is enabled.
1202  * @return a bool that indicates whether the action is enabled.
1203  */
1204 bool ModelExecution::check_action_enabled(ModelAction *curr) {
1205         if (curr->is_lock()) {
1206                 std::mutex *lock = curr->get_mutex();
1207                 struct std::mutex_state *state = lock->get_state();
1208                 if (state->locked)
1209                         return false;
1210         } else if (curr->is_thread_join()) {
1211                 Thread *blocking = curr->get_thread_operand();
1212                 if (!blocking->is_complete()) {
1213                         thread_blocking_check_promises(blocking, get_thread(curr));
1214                         return false;
1215                 }
1216         } else if (params->yieldblock && curr->is_yield()) {
1217                 return false;
1218         }
1219
1220         return true;
1221 }
1222
1223 /**
1224  * This is the heart of the model checker routine. It performs model-checking
1225  * actions corresponding to a given "current action." Among other processes, it
1226  * calculates reads-from relationships, updates synchronization clock vectors,
1227  * forms a memory_order constraints graph, and handles replay/backtrack
1228  * execution when running permutations of previously-observed executions.
1229  *
1230  * @param curr The current action to process
1231  * @return The ModelAction that is actually executed; may be different than
1232  * curr
1233  */
1234 ModelAction * ModelExecution::check_current_action(ModelAction *curr)
1235 {
1236         ASSERT(curr);
1237         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
1238         bool newly_explored = initialize_curr_action(&curr);
1239
1240         DBG();
1241
1242         wake_up_sleeping_actions(curr);
1243
1244         /* Compute fairness information for CHESS yield algorithm */
1245         if (params->yieldon) {
1246                 curr->get_node()->update_yield(scheduler);
1247         }
1248
1249         /* Add the action to lists before any other model-checking tasks */
1250         if (!second_part_of_rmw)
1251                 add_action_to_lists(curr);
1252
1253         /* Build may_read_from set for newly-created actions */
1254         if (newly_explored && curr->is_read())
1255                 build_may_read_from(curr);
1256
1257         /* Initialize work_queue with the "current action" work */
1258         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
1259         while (!work_queue.empty() && !has_asserted()) {
1260                 WorkQueueEntry work = work_queue.front();
1261                 work_queue.pop_front();
1262
1263                 switch (work.type) {
1264                 case WORK_CHECK_CURR_ACTION: {
1265                         ModelAction *act = work.action;
1266                         bool update = false; /* update this location's release seq's */
1267                         bool update_all = false; /* update all release seq's */
1268
1269                         if (process_thread_action(curr))
1270                                 update_all = true;
1271
1272                         if (act->is_read() && !second_part_of_rmw && process_read(act))
1273                                 update = true;
1274
1275                         if (act->is_write() && process_write(act))
1276                                 update = true;
1277
1278                         if (act->is_fence() && process_fence(act))
1279                                 update_all = true;
1280
1281                         if (act->is_mutex_op() && process_mutex(act))
1282                                 update_all = true;
1283
1284                         if (act->is_relseq_fixup())
1285                                 process_relseq_fixup(curr, &work_queue);
1286
1287                         if (update_all)
1288                                 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
1289                         else if (update)
1290                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
1291                         break;
1292                 }
1293                 case WORK_CHECK_RELEASE_SEQ:
1294                         resolve_release_sequences(work.location, &work_queue);
1295                         break;
1296                 case WORK_CHECK_MO_EDGES: {
1297                         /** @todo Complete verification of work_queue */
1298                         ModelAction *act = work.action;
1299                         bool updated = false;
1300
1301                         if (act->is_read()) {
1302                                 const ModelAction *rf = act->get_reads_from();
1303                                 const Promise *promise = act->get_reads_from_promise();
1304                                 if (rf) {
1305                                         if (r_modification_order(act, rf))
1306                                                 updated = true;
1307                                 } else if (promise) {
1308                                         if (r_modification_order(act, promise))
1309                                                 updated = true;
1310                                 }
1311                         }
1312                         if (act->is_write()) {
1313                                 if (w_modification_order(act, NULL))
1314                                         updated = true;
1315                         }
1316                         mo_graph->commitChanges();
1317
1318                         if (updated)
1319                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
1320                         break;
1321                 }
1322                 default:
1323                         ASSERT(false);
1324                         break;
1325                 }
1326         }
1327
1328         check_curr_backtracking(curr);
1329         set_backtracking(curr);
1330         return curr;
1331 }
1332
1333 void ModelExecution::check_curr_backtracking(ModelAction *curr)
1334 {
1335         Node *currnode = curr->get_node();
1336         Node *parnode = currnode->get_parent();
1337
1338         if ((parnode && !parnode->backtrack_empty()) ||
1339                          !currnode->misc_empty() ||
1340                          !currnode->read_from_empty() ||
1341                          !currnode->promise_empty() ||
1342                          !currnode->relseq_break_empty()) {
1343                 set_latest_backtrack(curr);
1344         }
1345 }
1346
1347 bool ModelExecution::promises_expired() const
1348 {
1349         for (unsigned int i = 0; i < promises.size(); i++) {
1350                 Promise *promise = promises[i];
1351                 if (promise->get_expiration() < priv->used_sequence_numbers)
1352                         return true;
1353         }
1354         return false;
1355 }
1356
1357 /**
1358  * This is the strongest feasibility check available.
1359  * @return whether the current trace (partial or complete) must be a prefix of
1360  * a feasible trace.
1361  */
1362 bool ModelExecution::isfeasibleprefix() const
1363 {
1364         return pending_rel_seqs.size() == 0 && is_feasible_prefix_ignore_relseq();
1365 }
1366
1367 /**
1368  * Print disagnostic information about an infeasible execution
1369  * @param prefix A string to prefix the output with; if NULL, then a default
1370  * message prefix will be provided
1371  */
1372 void ModelExecution::print_infeasibility(const char *prefix) const
1373 {
1374         char buf[100];
1375         char *ptr = buf;
1376         if (mo_graph->checkForCycles())
1377                 ptr += sprintf(ptr, "[mo cycle]");
1378         if (priv->failed_promise)
1379                 ptr += sprintf(ptr, "[failed promise]");
1380         if (priv->too_many_reads)
1381                 ptr += sprintf(ptr, "[too many reads]");
1382         if (priv->no_valid_reads)
1383                 ptr += sprintf(ptr, "[no valid reads-from]");
1384         if (priv->bad_synchronization)
1385                 ptr += sprintf(ptr, "[bad sw ordering]");
1386         if (promises_expired())
1387                 ptr += sprintf(ptr, "[promise expired]");
1388         if (promises.size() != 0)
1389                 ptr += sprintf(ptr, "[unresolved promise]");
1390         if (ptr != buf)
1391                 model_print("%s: %s\n", prefix ? prefix : "Infeasible", buf);
1392 }
1393
1394 /**
1395  * Returns whether the current completed trace is feasible, except for pending
1396  * release sequences.
1397  */
1398 bool ModelExecution::is_feasible_prefix_ignore_relseq() const
1399 {
1400         return !is_infeasible() && promises.size() == 0;
1401 }
1402
1403 /**
1404  * Check if the current partial trace is infeasible. Does not check any
1405  * end-of-execution flags, which might rule out the execution. Thus, this is
1406  * useful only for ruling an execution as infeasible.
1407  * @return whether the current partial trace is infeasible.
1408  */
1409 bool ModelExecution::is_infeasible() const
1410 {
1411         return mo_graph->checkForCycles() ||
1412                 priv->no_valid_reads ||
1413                 priv->failed_promise ||
1414                 priv->too_many_reads ||
1415                 priv->bad_synchronization ||
1416                 promises_expired();
1417 }
1418
1419 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
1420 ModelAction * ModelExecution::process_rmw(ModelAction *act) {
1421         ModelAction *lastread = get_last_action(act->get_tid());
1422         lastread->process_rmw(act);
1423         if (act->is_rmw()) {
1424                 if (lastread->get_reads_from())
1425                         mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
1426                 else
1427                         mo_graph->addRMWEdge(lastread->get_reads_from_promise(), lastread);
1428                 mo_graph->commitChanges();
1429         }
1430         return lastread;
1431 }
1432
1433 /**
1434  * A helper function for ModelExecution::check_recency, to check if the current
1435  * thread is able to read from a different write/promise for 'params.maxreads'
1436  * number of steps and if that write/promise should become visible (i.e., is
1437  * ordered later in the modification order). This helps model memory liveness.
1438  *
1439  * @param curr The current action. Must be a read.
1440  * @param rf The write/promise from which we plan to read
1441  * @param other_rf The write/promise from which we may read
1442  * @return True if we were able to read from other_rf for params.maxreads steps
1443  */
1444 template <typename T, typename U>
1445 bool ModelExecution::should_read_instead(const ModelAction *curr, const T *rf, const U *other_rf) const
1446 {
1447         /* Need a different write/promise */
1448         if (other_rf->equals(rf))
1449                 return false;
1450
1451         /* Only look for "newer" writes/promises */
1452         if (!mo_graph->checkReachable(rf, other_rf))
1453                 return false;
1454
1455         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1456         action_list_t *list = &(*thrd_lists)[id_to_int(curr->get_tid())];
1457         action_list_t::reverse_iterator rit = list->rbegin();
1458         ASSERT((*rit) == curr);
1459         /* Skip past curr */
1460         rit++;
1461
1462         /* Does this write/promise work for everyone? */
1463         for (int i = 0; i < params->maxreads; i++, rit++) {
1464                 ModelAction *act = *rit;
1465                 if (!act->may_read_from(other_rf))
1466                         return false;
1467         }
1468         return true;
1469 }
1470
1471 /**
1472  * Checks whether a thread has read from the same write or Promise for too many
1473  * times without seeing the effects of a later write/Promise.
1474  *
1475  * Basic idea:
1476  * 1) there must a different write/promise that we could read from,
1477  * 2) we must have read from the same write/promise in excess of maxreads times,
1478  * 3) that other write/promise must have been in the reads_from set for maxreads times, and
1479  * 4) that other write/promise must be mod-ordered after the write/promise we are reading.
1480  *
1481  * If so, we decide that the execution is no longer feasible.
1482  *
1483  * @param curr The current action. Must be a read.
1484  * @param rf The ModelAction/Promise from which we might read.
1485  * @return True if the read should succeed; false otherwise
1486  */
1487 template <typename T>
1488 bool ModelExecution::check_recency(ModelAction *curr, const T *rf) const
1489 {
1490         if (!params->maxreads)
1491                 return true;
1492
1493         //NOTE: Next check is just optimization, not really necessary....
1494         if (curr->get_node()->get_read_from_past_size() +
1495                         curr->get_node()->get_read_from_promise_size() <= 1)
1496                 return true;
1497
1498         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1499         int tid = id_to_int(curr->get_tid());
1500         ASSERT(tid < (int)thrd_lists->size());
1501         action_list_t *list = &(*thrd_lists)[tid];
1502         action_list_t::reverse_iterator rit = list->rbegin();
1503         ASSERT((*rit) == curr);
1504         /* Skip past curr */
1505         rit++;
1506
1507         action_list_t::reverse_iterator ritcopy = rit;
1508         /* See if we have enough reads from the same value */
1509         for (int count = 0; count < params->maxreads; ritcopy++, count++) {
1510                 if (ritcopy == list->rend())
1511                         return true;
1512                 ModelAction *act = *ritcopy;
1513                 if (!act->is_read())
1514                         return true;
1515                 if (act->get_reads_from_promise() && !act->get_reads_from_promise()->equals(rf))
1516                         return true;
1517                 if (act->get_reads_from() && !act->get_reads_from()->equals(rf))
1518                         return true;
1519                 if (act->get_node()->get_read_from_past_size() +
1520                                 act->get_node()->get_read_from_promise_size() <= 1)
1521                         return true;
1522         }
1523         for (int i = 0; i < curr->get_node()->get_read_from_past_size(); i++) {
1524                 const ModelAction *write = curr->get_node()->get_read_from_past(i);
1525                 if (should_read_instead(curr, rf, write))
1526                         return false; /* liveness failure */
1527         }
1528         for (int i = 0; i < curr->get_node()->get_read_from_promise_size(); i++) {
1529                 const Promise *promise = curr->get_node()->get_read_from_promise(i);
1530                 if (should_read_instead(curr, rf, promise))
1531                         return false; /* liveness failure */
1532         }
1533         return true;
1534 }
1535
1536 /**
1537  * @brief Updates the mo_graph with the constraints imposed from the current
1538  * read.
1539  *
1540  * Basic idea is the following: Go through each other thread and find
1541  * the last action that happened before our read.  Two cases:
1542  *
1543  * -# The action is a write: that write must either occur before
1544  * the write we read from or be the write we read from.
1545  * -# The action is a read: the write that that action read from
1546  * must occur before the write we read from or be the same write.
1547  *
1548  * @param curr The current action. Must be a read.
1549  * @param rf The ModelAction or Promise that curr reads from. Must be a write.
1550  * @return True if modification order edges were added; false otherwise
1551  */
1552 template <typename rf_type>
1553 bool ModelExecution::r_modification_order(ModelAction *curr, const rf_type *rf)
1554 {
1555         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1556         unsigned int i;
1557         bool added = false;
1558         ASSERT(curr->is_read());
1559
1560         /* Last SC fence in the current thread */
1561         ModelAction *last_sc_fence_local = get_last_seq_cst_fence(curr->get_tid(), NULL);
1562         ModelAction *last_sc_write = NULL;
1563         if (curr->is_seqcst())
1564                 last_sc_write = get_last_seq_cst_write(curr);
1565
1566         /* Iterate over all threads */
1567         for (i = 0; i < thrd_lists->size(); i++) {
1568                 /* Last SC fence in thread i */
1569                 ModelAction *last_sc_fence_thread_local = NULL;
1570                 if (int_to_id((int)i) != curr->get_tid())
1571                         last_sc_fence_thread_local = get_last_seq_cst_fence(int_to_id(i), NULL);
1572
1573                 /* Last SC fence in thread i, before last SC fence in current thread */
1574                 ModelAction *last_sc_fence_thread_before = NULL;
1575                 if (last_sc_fence_local)
1576                         last_sc_fence_thread_before = get_last_seq_cst_fence(int_to_id(i), last_sc_fence_local);
1577
1578                 /* Iterate over actions in thread, starting from most recent */
1579                 action_list_t *list = &(*thrd_lists)[i];
1580                 action_list_t::reverse_iterator rit;
1581                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1582                         ModelAction *act = *rit;
1583
1584                         /* Skip curr */
1585                         if (act == curr)
1586                                 continue;
1587                         /* Don't want to add reflexive edges on 'rf' */
1588                         if (act->equals(rf)) {
1589                                 if (act->happens_before(curr))
1590                                         break;
1591                                 else
1592                                         continue;
1593                         }
1594
1595                         if (act->is_write()) {
1596                                 /* C++, Section 29.3 statement 5 */
1597                                 if (curr->is_seqcst() && last_sc_fence_thread_local &&
1598                                                 *act < *last_sc_fence_thread_local) {
1599                                         added = mo_graph->addEdge(act, rf) || added;
1600                                         break;
1601                                 }
1602                                 /* C++, Section 29.3 statement 4 */
1603                                 else if (act->is_seqcst() && last_sc_fence_local &&
1604                                                 *act < *last_sc_fence_local) {
1605                                         added = mo_graph->addEdge(act, rf) || added;
1606                                         break;
1607                                 }
1608                                 /* C++, Section 29.3 statement 6 */
1609                                 else if (last_sc_fence_thread_before &&
1610                                                 *act < *last_sc_fence_thread_before) {
1611                                         added = mo_graph->addEdge(act, rf) || added;
1612                                         break;
1613                                 }
1614                         }
1615
1616                         /* C++, Section 29.3 statement 3 (second subpoint) */
1617                         if (curr->is_seqcst() && last_sc_write && act == last_sc_write) {
1618                                 added = mo_graph->addEdge(act, rf) || added;
1619                                 break;
1620                         }
1621
1622                         /*
1623                          * Include at most one act per-thread that "happens
1624                          * before" curr
1625                          */
1626                         if (act->happens_before(curr)) {
1627                                 if (act->is_write()) {
1628                                         added = mo_graph->addEdge(act, rf) || added;
1629                                 } else {
1630                                         const ModelAction *prevrf = act->get_reads_from();
1631                                         const Promise *prevrf_promise = act->get_reads_from_promise();
1632                                         if (prevrf) {
1633                                                 if (!prevrf->equals(rf))
1634                                                         added = mo_graph->addEdge(prevrf, rf) || added;
1635                                         } else if (!prevrf_promise->equals(rf)) {
1636                                                 added = mo_graph->addEdge(prevrf_promise, rf) || added;
1637                                         }
1638                                 }
1639                                 break;
1640                         }
1641                 }
1642         }
1643
1644         /*
1645          * All compatible, thread-exclusive promises must be ordered after any
1646          * concrete loads from the same thread
1647          */
1648         for (unsigned int i = 0; i < promises.size(); i++)
1649                 if (promises[i]->is_compatible_exclusive(curr))
1650                         added = mo_graph->addEdge(rf, promises[i]) || added;
1651
1652         return added;
1653 }
1654
1655 /**
1656  * Updates the mo_graph with the constraints imposed from the current write.
1657  *
1658  * Basic idea is the following: Go through each other thread and find
1659  * the lastest action that happened before our write.  Two cases:
1660  *
1661  * (1) The action is a write => that write must occur before
1662  * the current write
1663  *
1664  * (2) The action is a read => the write that that action read from
1665  * must occur before the current write.
1666  *
1667  * This method also handles two other issues:
1668  *
1669  * (I) Sequential Consistency: Making sure that if the current write is
1670  * seq_cst, that it occurs after the previous seq_cst write.
1671  *
1672  * (II) Sending the write back to non-synchronizing reads.
1673  *
1674  * @param curr The current action. Must be a write.
1675  * @param send_fv A vector for stashing reads to which we may pass our future
1676  * value. If NULL, then don't record any future values.
1677  * @return True if modification order edges were added; false otherwise
1678  */
1679 bool ModelExecution::w_modification_order(ModelAction *curr, ModelVector<ModelAction *> *send_fv)
1680 {
1681         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1682         unsigned int i;
1683         bool added = false;
1684         ASSERT(curr->is_write());
1685
1686         if (curr->is_seqcst()) {
1687                 /* We have to at least see the last sequentially consistent write,
1688                          so we are initialized. */
1689                 ModelAction *last_seq_cst = get_last_seq_cst_write(curr);
1690                 if (last_seq_cst != NULL) {
1691                         added = mo_graph->addEdge(last_seq_cst, curr) || added;
1692                 }
1693         }
1694
1695         /* Last SC fence in the current thread */
1696         ModelAction *last_sc_fence_local = get_last_seq_cst_fence(curr->get_tid(), NULL);
1697
1698         /* Iterate over all threads */
1699         for (i = 0; i < thrd_lists->size(); i++) {
1700                 /* Last SC fence in thread i, before last SC fence in current thread */
1701                 ModelAction *last_sc_fence_thread_before = NULL;
1702                 if (last_sc_fence_local && int_to_id((int)i) != curr->get_tid())
1703                         last_sc_fence_thread_before = get_last_seq_cst_fence(int_to_id(i), last_sc_fence_local);
1704
1705                 /* Iterate over actions in thread, starting from most recent */
1706                 action_list_t *list = &(*thrd_lists)[i];
1707                 action_list_t::reverse_iterator rit;
1708                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1709                         ModelAction *act = *rit;
1710                         if (act == curr) {
1711                                 /*
1712                                  * 1) If RMW and it actually read from something, then we
1713                                  * already have all relevant edges, so just skip to next
1714                                  * thread.
1715                                  *
1716                                  * 2) If RMW and it didn't read from anything, we should
1717                                  * whatever edge we can get to speed up convergence.
1718                                  *
1719                                  * 3) If normal write, we need to look at earlier actions, so
1720                                  * continue processing list.
1721                                  */
1722                                 if (curr->is_rmw()) {
1723                                         if (curr->get_reads_from() != NULL)
1724                                                 break;
1725                                         else
1726                                                 continue;
1727                                 } else
1728                                         continue;
1729                         }
1730
1731                         /* C++, Section 29.3 statement 7 */
1732                         if (last_sc_fence_thread_before && act->is_write() &&
1733                                         *act < *last_sc_fence_thread_before) {
1734                                 added = mo_graph->addEdge(act, curr) || added;
1735                                 break;
1736                         }
1737
1738                         /*
1739                          * Include at most one act per-thread that "happens
1740                          * before" curr
1741                          */
1742                         if (act->happens_before(curr)) {
1743                                 /*
1744                                  * Note: if act is RMW, just add edge:
1745                                  *   act --mo--> curr
1746                                  * The following edge should be handled elsewhere:
1747                                  *   readfrom(act) --mo--> act
1748                                  */
1749                                 if (act->is_write())
1750                                         added = mo_graph->addEdge(act, curr) || added;
1751                                 else if (act->is_read()) {
1752                                         //if previous read accessed a null, just keep going
1753                                         if (act->get_reads_from() == NULL)
1754                                                 continue;
1755                                         added = mo_graph->addEdge(act->get_reads_from(), curr) || added;
1756                                 }
1757                                 break;
1758                         } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1759                                                      !act->same_thread(curr)) {
1760                                 /* We have an action that:
1761                                    (1) did not happen before us
1762                                    (2) is a read and we are a write
1763                                    (3) cannot synchronize with us
1764                                    (4) is in a different thread
1765                                    =>
1766                                    that read could potentially read from our write.  Note that
1767                                    these checks are overly conservative at this point, we'll
1768                                    do more checks before actually removing the
1769                                    pendingfuturevalue.
1770
1771                                  */
1772                                 if (send_fv && thin_air_constraint_may_allow(curr, act)) {
1773                                         if (!is_infeasible())
1774                                                 send_fv->push_back(act);
1775                                         else if (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() && curr->get_reads_from() == act->get_reads_from())
1776                                                 add_future_value(curr, act);
1777                                 }
1778                         }
1779                 }
1780         }
1781
1782         /*
1783          * All compatible, thread-exclusive promises must be ordered after any
1784          * concrete stores to the same thread, or else they can be merged with
1785          * this store later
1786          */
1787         for (unsigned int i = 0; i < promises.size(); i++)
1788                 if (promises[i]->is_compatible_exclusive(curr))
1789                         added = mo_graph->addEdge(curr, promises[i]) || added;
1790
1791         return added;
1792 }
1793
1794 /** Arbitrary reads from the future are not allowed.  Section 29.3
1795  * part 9 places some constraints.  This method checks one result of constraint
1796  * constraint.  Others require compiler support. */
1797 bool ModelExecution::thin_air_constraint_may_allow(const ModelAction *writer, const ModelAction *reader) const
1798 {
1799         if (!writer->is_rmw())
1800                 return true;
1801
1802         if (!reader->is_rmw())
1803                 return true;
1804
1805         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1806                 if (search == reader)
1807                         return false;
1808                 if (search->get_tid() == reader->get_tid() &&
1809                                 search->happens_before(reader))
1810                         break;
1811         }
1812
1813         return true;
1814 }
1815
1816 /**
1817  * Arbitrary reads from the future are not allowed. Section 29.3 part 9 places
1818  * some constraints. This method checks one the following constraint (others
1819  * require compiler support):
1820  *
1821  *   If X --hb-> Y --mo-> Z, then X should not read from Z.
1822  */
1823 bool ModelExecution::mo_may_allow(const ModelAction *writer, const ModelAction *reader)
1824 {
1825         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(reader->get_location());
1826         unsigned int i;
1827         /* Iterate over all threads */
1828         for (i = 0; i < thrd_lists->size(); i++) {
1829                 const ModelAction *write_after_read = NULL;
1830
1831                 /* Iterate over actions in thread, starting from most recent */
1832                 action_list_t *list = &(*thrd_lists)[i];
1833                 action_list_t::reverse_iterator rit;
1834                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1835                         ModelAction *act = *rit;
1836
1837                         /* Don't disallow due to act == reader */
1838                         if (!reader->happens_before(act) || reader == act)
1839                                 break;
1840                         else if (act->is_write())
1841                                 write_after_read = act;
1842                         else if (act->is_read() && act->get_reads_from() != NULL)
1843                                 write_after_read = act->get_reads_from();
1844                 }
1845
1846                 if (write_after_read && write_after_read != writer && mo_graph->checkReachable(write_after_read, writer))
1847                         return false;
1848         }
1849         return true;
1850 }
1851
1852 /**
1853  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1854  * The ModelAction under consideration is expected to be taking part in
1855  * release/acquire synchronization as an object of the "reads from" relation.
1856  * Note that this can only provide release sequence support for RMW chains
1857  * which do not read from the future, as those actions cannot be traced until
1858  * their "promise" is fulfilled. Similarly, we may not even establish the
1859  * presence of a release sequence with certainty, as some modification order
1860  * constraints may be decided further in the future. Thus, this function
1861  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1862  * and a boolean representing certainty.
1863  *
1864  * @param rf The action that might be part of a release sequence. Must be a
1865  * write.
1866  * @param release_heads A pass-by-reference style return parameter. After
1867  * execution of this function, release_heads will contain the heads of all the
1868  * relevant release sequences, if any exists with certainty
1869  * @param pending A pass-by-reference style return parameter which is only used
1870  * when returning false (i.e., uncertain). Returns most information regarding
1871  * an uncertain release sequence, including any write operations that might
1872  * break the sequence.
1873  * @return true, if the ModelExecution is certain that release_heads is complete;
1874  * false otherwise
1875  */
1876 bool ModelExecution::release_seq_heads(const ModelAction *rf,
1877                 rel_heads_list_t *release_heads,
1878                 struct release_seq *pending) const
1879 {
1880         /* Only check for release sequences if there are no cycles */
1881         if (mo_graph->checkForCycles())
1882                 return false;
1883
1884         for ( ; rf != NULL; rf = rf->get_reads_from()) {
1885                 ASSERT(rf->is_write());
1886
1887                 if (rf->is_release())
1888                         release_heads->push_back(rf);
1889                 else if (rf->get_last_fence_release())
1890                         release_heads->push_back(rf->get_last_fence_release());
1891                 if (!rf->is_rmw())
1892                         break; /* End of RMW chain */
1893
1894                 /** @todo Need to be smarter here...  In the linux lock
1895                  * example, this will run to the beginning of the program for
1896                  * every acquire. */
1897                 /** @todo The way to be smarter here is to keep going until 1
1898                  * thread has a release preceded by an acquire and you've seen
1899                  *       both. */
1900
1901                 /* acq_rel RMW is a sufficient stopping condition */
1902                 if (rf->is_acquire() && rf->is_release())
1903                         return true; /* complete */
1904         };
1905         if (!rf) {
1906                 /* read from future: need to settle this later */
1907                 pending->rf = NULL;
1908                 return false; /* incomplete */
1909         }
1910
1911         if (rf->is_release())
1912                 return true; /* complete */
1913
1914         /* else relaxed write
1915          * - check for fence-release in the same thread (29.8, stmt. 3)
1916          * - check modification order for contiguous subsequence
1917          *   -> rf must be same thread as release */
1918
1919         const ModelAction *fence_release = rf->get_last_fence_release();
1920         /* Synchronize with a fence-release unconditionally; we don't need to
1921          * find any more "contiguous subsequence..." for it */
1922         if (fence_release)
1923                 release_heads->push_back(fence_release);
1924
1925         int tid = id_to_int(rf->get_tid());
1926         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(rf->get_location());
1927         action_list_t *list = &(*thrd_lists)[tid];
1928         action_list_t::const_reverse_iterator rit;
1929
1930         /* Find rf in the thread list */
1931         rit = std::find(list->rbegin(), list->rend(), rf);
1932         ASSERT(rit != list->rend());
1933
1934         /* Find the last {write,fence}-release */
1935         for (; rit != list->rend(); rit++) {
1936                 if (fence_release && *(*rit) < *fence_release)
1937                         break;
1938                 if ((*rit)->is_release())
1939                         break;
1940         }
1941         if (rit == list->rend()) {
1942                 /* No write-release in this thread */
1943                 return true; /* complete */
1944         } else if (fence_release && *(*rit) < *fence_release) {
1945                 /* The fence-release is more recent (and so, "stronger") than
1946                  * the most recent write-release */
1947                 return true; /* complete */
1948         } /* else, need to establish contiguous release sequence */
1949         ModelAction *release = *rit;
1950
1951         ASSERT(rf->same_thread(release));
1952
1953         pending->writes.clear();
1954
1955         bool certain = true;
1956         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1957                 if (id_to_int(rf->get_tid()) == (int)i)
1958                         continue;
1959                 list = &(*thrd_lists)[i];
1960
1961                 /* Can we ensure no future writes from this thread may break
1962                  * the release seq? */
1963                 bool future_ordered = false;
1964
1965                 ModelAction *last = get_last_action(int_to_id(i));
1966                 Thread *th = get_thread(int_to_id(i));
1967                 if ((last && rf->happens_before(last)) ||
1968                                 !is_enabled(th) ||
1969                                 th->is_complete())
1970                         future_ordered = true;
1971
1972                 ASSERT(!th->is_model_thread() || future_ordered);
1973
1974                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1975                         const ModelAction *act = *rit;
1976                         /* Reach synchronization -> this thread is complete */
1977                         if (act->happens_before(release))
1978                                 break;
1979                         if (rf->happens_before(act)) {
1980                                 future_ordered = true;
1981                                 continue;
1982                         }
1983
1984                         /* Only non-RMW writes can break release sequences */
1985                         if (!act->is_write() || act->is_rmw())
1986                                 continue;
1987
1988                         /* Check modification order */
1989                         if (mo_graph->checkReachable(rf, act)) {
1990                                 /* rf --mo--> act */
1991                                 future_ordered = true;
1992                                 continue;
1993                         }
1994                         if (mo_graph->checkReachable(act, release))
1995                                 /* act --mo--> release */
1996                                 break;
1997                         if (mo_graph->checkReachable(release, act) &&
1998                                       mo_graph->checkReachable(act, rf)) {
1999                                 /* release --mo-> act --mo--> rf */
2000                                 return true; /* complete */
2001                         }
2002                         /* act may break release sequence */
2003                         pending->writes.push_back(act);
2004                         certain = false;
2005                 }
2006                 if (!future_ordered)
2007                         certain = false; /* This thread is uncertain */
2008         }
2009
2010         if (certain) {
2011                 release_heads->push_back(release);
2012                 pending->writes.clear();
2013         } else {
2014                 pending->release = release;
2015                 pending->rf = rf;
2016         }
2017         return certain;
2018 }
2019
2020 /**
2021  * An interface for getting the release sequence head(s) with which a
2022  * given ModelAction must synchronize. This function only returns a non-empty
2023  * result when it can locate a release sequence head with certainty. Otherwise,
2024  * it may mark the internal state of the ModelExecution so that it will handle
2025  * the release sequence at a later time, causing @a acquire to update its
2026  * synchronization at some later point in execution.
2027  *
2028  * @param acquire The 'acquire' action that may synchronize with a release
2029  * sequence
2030  * @param read The read action that may read from a release sequence; this may
2031  * be the same as acquire, or else an earlier action in the same thread (i.e.,
2032  * when 'acquire' is a fence-acquire)
2033  * @param release_heads A pass-by-reference return parameter. Will be filled
2034  * with the head(s) of the release sequence(s), if they exists with certainty.
2035  * @see ModelExecution::release_seq_heads
2036  */
2037 void ModelExecution::get_release_seq_heads(ModelAction *acquire,
2038                 ModelAction *read, rel_heads_list_t *release_heads)
2039 {
2040         const ModelAction *rf = read->get_reads_from();
2041         struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
2042         sequence->acquire = acquire;
2043         sequence->read = read;
2044
2045         if (!release_seq_heads(rf, release_heads, sequence)) {
2046                 /* add act to 'lazy checking' list */
2047                 pending_rel_seqs.push_back(sequence);
2048         } else {
2049                 snapshot_free(sequence);
2050         }
2051 }
2052
2053 /**
2054  * Attempt to resolve all stashed operations that might synchronize with a
2055  * release sequence for a given location. This implements the "lazy" portion of
2056  * determining whether or not a release sequence was contiguous, since not all
2057  * modification order information is present at the time an action occurs.
2058  *
2059  * @param location The location/object that should be checked for release
2060  * sequence resolutions. A NULL value means to check all locations.
2061  * @param work_queue The work queue to which to add work items as they are
2062  * generated
2063  * @return True if any updates occurred (new synchronization, new mo_graph
2064  * edges)
2065  */
2066 bool ModelExecution::resolve_release_sequences(void *location, work_queue_t *work_queue)
2067 {
2068         bool updated = false;
2069         SnapVector<struct release_seq *>::iterator it = pending_rel_seqs.begin();
2070         while (it != pending_rel_seqs.end()) {
2071                 struct release_seq *pending = *it;
2072                 ModelAction *acquire = pending->acquire;
2073                 const ModelAction *read = pending->read;
2074
2075                 /* Only resolve sequences on the given location, if provided */
2076                 if (location && read->get_location() != location) {
2077                         it++;
2078                         continue;
2079                 }
2080
2081                 const ModelAction *rf = read->get_reads_from();
2082                 rel_heads_list_t release_heads;
2083                 bool complete;
2084                 complete = release_seq_heads(rf, &release_heads, pending);
2085                 for (unsigned int i = 0; i < release_heads.size(); i++)
2086                         if (!acquire->has_synchronized_with(release_heads[i]))
2087                                 if (synchronize(release_heads[i], acquire))
2088                                         updated = true;
2089
2090                 if (updated) {
2091                         /* Re-check all pending release sequences */
2092                         work_queue->push_back(CheckRelSeqWorkEntry(NULL));
2093                         /* Re-check read-acquire for mo_graph edges */
2094                         if (acquire->is_read())
2095                                 work_queue->push_back(MOEdgeWorkEntry(acquire));
2096
2097                         /* propagate synchronization to later actions */
2098                         action_list_t::reverse_iterator rit = action_trace.rbegin();
2099                         for (; (*rit) != acquire; rit++) {
2100                                 ModelAction *propagate = *rit;
2101                                 if (acquire->happens_before(propagate)) {
2102                                         synchronize(acquire, propagate);
2103                                         /* Re-check 'propagate' for mo_graph edges */
2104                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
2105                                 }
2106                         }
2107                 }
2108                 if (complete) {
2109                         it = pending_rel_seqs.erase(it);
2110                         snapshot_free(pending);
2111                 } else {
2112                         it++;
2113                 }
2114         }
2115
2116         // If we resolved promises or data races, see if we have realized a data race.
2117         checkDataRaces();
2118
2119         return updated;
2120 }
2121
2122 /**
2123  * Performs various bookkeeping operations for the current ModelAction. For
2124  * instance, adds action to the per-object, per-thread action vector and to the
2125  * action trace list of all thread actions.
2126  *
2127  * @param act is the ModelAction to add.
2128  */
2129 void ModelExecution::add_action_to_lists(ModelAction *act)
2130 {
2131         int tid = id_to_int(act->get_tid());
2132         ModelAction *uninit = NULL;
2133         int uninit_id = -1;
2134         action_list_t *list = get_safe_ptr_action(&obj_map, act->get_location());
2135         if (list->empty() && act->is_atomic_var()) {
2136                 uninit = get_uninitialized_action(act);
2137                 uninit_id = id_to_int(uninit->get_tid());
2138                 list->push_front(uninit);
2139         }
2140         list->push_back(act);
2141
2142         action_trace.push_back(act);
2143         if (uninit)
2144                 action_trace.push_front(uninit);
2145
2146         SnapVector<action_list_t> *vec = get_safe_ptr_vect_action(&obj_thrd_map, act->get_location());
2147         if (tid >= (int)vec->size())
2148                 vec->resize(priv->next_thread_id);
2149         (*vec)[tid].push_back(act);
2150         if (uninit)
2151                 (*vec)[uninit_id].push_front(uninit);
2152
2153         if ((int)thrd_last_action.size() <= tid)
2154                 thrd_last_action.resize(get_num_threads());
2155         thrd_last_action[tid] = act;
2156         if (uninit)
2157                 thrd_last_action[uninit_id] = uninit;
2158
2159         if (act->is_fence() && act->is_release()) {
2160                 if ((int)thrd_last_fence_release.size() <= tid)
2161                         thrd_last_fence_release.resize(get_num_threads());
2162                 thrd_last_fence_release[tid] = act;
2163         }
2164
2165         if (act->is_wait()) {
2166                 void *mutex_loc = (void *) act->get_value();
2167                 get_safe_ptr_action(&obj_map, mutex_loc)->push_back(act);
2168
2169                 SnapVector<action_list_t> *vec = get_safe_ptr_vect_action(&obj_thrd_map, mutex_loc);
2170                 if (tid >= (int)vec->size())
2171                         vec->resize(priv->next_thread_id);
2172                 (*vec)[tid].push_back(act);
2173         }
2174 }
2175
2176 /**
2177  * @brief Get the last action performed by a particular Thread
2178  * @param tid The thread ID of the Thread in question
2179  * @return The last action in the thread
2180  */
2181 ModelAction * ModelExecution::get_last_action(thread_id_t tid) const
2182 {
2183         int threadid = id_to_int(tid);
2184         if (threadid < (int)thrd_last_action.size())
2185                 return thrd_last_action[id_to_int(tid)];
2186         else
2187                 return NULL;
2188 }
2189
2190 /**
2191  * @brief Get the last fence release performed by a particular Thread
2192  * @param tid The thread ID of the Thread in question
2193  * @return The last fence release in the thread, if one exists; NULL otherwise
2194  */
2195 ModelAction * ModelExecution::get_last_fence_release(thread_id_t tid) const
2196 {
2197         int threadid = id_to_int(tid);
2198         if (threadid < (int)thrd_last_fence_release.size())
2199                 return thrd_last_fence_release[id_to_int(tid)];
2200         else
2201                 return NULL;
2202 }
2203
2204 /**
2205  * Gets the last memory_order_seq_cst write (in the total global sequence)
2206  * performed on a particular object (i.e., memory location), not including the
2207  * current action.
2208  * @param curr The current ModelAction; also denotes the object location to
2209  * check
2210  * @return The last seq_cst write
2211  */
2212 ModelAction * ModelExecution::get_last_seq_cst_write(ModelAction *curr) const
2213 {
2214         void *location = curr->get_location();
2215         action_list_t *list = obj_map.get(location);
2216         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
2217         action_list_t::reverse_iterator rit;
2218         for (rit = list->rbegin(); (*rit) != curr; rit++)
2219                 ;
2220         rit++; /* Skip past curr */
2221         for ( ; rit != list->rend(); rit++)
2222                 if ((*rit)->is_write() && (*rit)->is_seqcst())
2223                         return *rit;
2224         return NULL;
2225 }
2226
2227 /**
2228  * Gets the last memory_order_seq_cst fence (in the total global sequence)
2229  * performed in a particular thread, prior to a particular fence.
2230  * @param tid The ID of the thread to check
2231  * @param before_fence The fence from which to begin the search; if NULL, then
2232  * search for the most recent fence in the thread.
2233  * @return The last prior seq_cst fence in the thread, if exists; otherwise, NULL
2234  */
2235 ModelAction * ModelExecution::get_last_seq_cst_fence(thread_id_t tid, const ModelAction *before_fence) const
2236 {
2237         /* All fences should have location FENCE_LOCATION */
2238         action_list_t *list = obj_map.get(FENCE_LOCATION);
2239
2240         if (!list)
2241                 return NULL;
2242
2243         action_list_t::reverse_iterator rit = list->rbegin();
2244
2245         if (before_fence) {
2246                 for (; rit != list->rend(); rit++)
2247                         if (*rit == before_fence)
2248                                 break;
2249
2250                 ASSERT(*rit == before_fence);
2251                 rit++;
2252         }
2253
2254         for (; rit != list->rend(); rit++)
2255                 if ((*rit)->is_fence() && (tid == (*rit)->get_tid()) && (*rit)->is_seqcst())
2256                         return *rit;
2257         return NULL;
2258 }
2259
2260 /**
2261  * Gets the last unlock operation performed on a particular mutex (i.e., memory
2262  * location). This function identifies the mutex according to the current
2263  * action, which is presumed to perform on the same mutex.
2264  * @param curr The current ModelAction; also denotes the object location to
2265  * check
2266  * @return The last unlock operation
2267  */
2268 ModelAction * ModelExecution::get_last_unlock(ModelAction *curr) const
2269 {
2270         void *location = curr->get_location();
2271         action_list_t *list = obj_map.get(location);
2272         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
2273         action_list_t::reverse_iterator rit;
2274         for (rit = list->rbegin(); rit != list->rend(); rit++)
2275                 if ((*rit)->is_unlock() || (*rit)->is_wait())
2276                         return *rit;
2277         return NULL;
2278 }
2279
2280 ModelAction * ModelExecution::get_parent_action(thread_id_t tid) const
2281 {
2282         ModelAction *parent = get_last_action(tid);
2283         if (!parent)
2284                 parent = get_thread(tid)->get_creation();
2285         return parent;
2286 }
2287
2288 /**
2289  * Returns the clock vector for a given thread.
2290  * @param tid The thread whose clock vector we want
2291  * @return Desired clock vector
2292  */
2293 ClockVector * ModelExecution::get_cv(thread_id_t tid) const
2294 {
2295         return get_parent_action(tid)->get_cv();
2296 }
2297
2298 /**
2299  * @brief Find the promise (if any) to resolve for the current action and
2300  * remove it from the pending promise vector
2301  * @param curr The current ModelAction. Should be a write.
2302  * @return The Promise to resolve, if any; otherwise NULL
2303  */
2304 Promise * ModelExecution::pop_promise_to_resolve(const ModelAction *curr)
2305 {
2306         for (unsigned int i = 0; i < promises.size(); i++)
2307                 if (curr->get_node()->get_promise(i)) {
2308                         Promise *ret = promises[i];
2309                         promises.erase(promises.begin() + i);
2310                         return ret;
2311                 }
2312         return NULL;
2313 }
2314
2315 /**
2316  * Resolve a Promise with a current write.
2317  * @param write The ModelAction that is fulfilling Promises
2318  * @param promise The Promise to resolve
2319  * @return True if the Promise was successfully resolved; false otherwise
2320  */
2321 bool ModelExecution::resolve_promise(ModelAction *write, Promise *promise)
2322 {
2323         ModelVector<ModelAction *> actions_to_check;
2324
2325         for (unsigned int i = 0; i < promise->get_num_readers(); i++) {
2326                 ModelAction *read = promise->get_reader(i);
2327                 read_from(read, write);
2328                 actions_to_check.push_back(read);
2329         }
2330         /* Make sure the promise's value matches the write's value */
2331         ASSERT(promise->is_compatible(write) && promise->same_value(write));
2332         if (!mo_graph->resolvePromise(promise, write))
2333                 priv->failed_promise = true;
2334
2335         /**
2336          * @todo  It is possible to end up in an inconsistent state, where a
2337          * "resolved" promise may still be referenced if
2338          * CycleGraph::resolvePromise() failed, so don't delete 'promise'.
2339          *
2340          * Note that the inconsistency only matters when dumping mo_graph to
2341          * file.
2342          *
2343          * delete promise;
2344          */
2345
2346         //Check whether reading these writes has made threads unable to
2347         //resolve promises
2348         for (unsigned int i = 0; i < actions_to_check.size(); i++) {
2349                 ModelAction *read = actions_to_check[i];
2350                 mo_check_promises(read, true);
2351         }
2352
2353         return true;
2354 }
2355
2356 /**
2357  * Compute the set of promises that could potentially be satisfied by this
2358  * action. Note that the set computation actually appears in the Node, not in
2359  * ModelExecution.
2360  * @param curr The ModelAction that may satisfy promises
2361  */
2362 void ModelExecution::compute_promises(ModelAction *curr)
2363 {
2364         for (unsigned int i = 0; i < promises.size(); i++) {
2365                 Promise *promise = promises[i];
2366                 if (!promise->is_compatible(curr) || !promise->same_value(curr))
2367                         continue;
2368
2369                 bool satisfy = true;
2370                 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2371                         const ModelAction *act = promise->get_reader(j);
2372                         if (act->happens_before(curr) ||
2373                                         act->could_synchronize_with(curr)) {
2374                                 satisfy = false;
2375                                 break;
2376                         }
2377                 }
2378                 if (satisfy)
2379                         curr->get_node()->set_promise(i);
2380         }
2381 }
2382
2383 /** Checks promises in response to change in ClockVector Threads. */
2384 void ModelExecution::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
2385 {
2386         for (unsigned int i = 0; i < promises.size(); i++) {
2387                 Promise *promise = promises[i];
2388                 if (!promise->thread_is_available(tid))
2389                         continue;
2390                 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2391                         const ModelAction *act = promise->get_reader(j);
2392                         if ((!old_cv || !old_cv->synchronized_since(act)) &&
2393                                         merge_cv->synchronized_since(act)) {
2394                                 if (promise->eliminate_thread(tid)) {
2395                                         /* Promise has failed */
2396                                         priv->failed_promise = true;
2397                                         return;
2398                                 }
2399                         }
2400                 }
2401         }
2402 }
2403
2404 void ModelExecution::check_promises_thread_disabled()
2405 {
2406         for (unsigned int i = 0; i < promises.size(); i++) {
2407                 Promise *promise = promises[i];
2408                 if (promise->has_failed()) {
2409                         priv->failed_promise = true;
2410                         return;
2411                 }
2412         }
2413 }
2414
2415 /**
2416  * @brief Checks promises in response to addition to modification order for
2417  * threads.
2418  *
2419  * We test whether threads are still available for satisfying promises after an
2420  * addition to our modification order constraints. Those that are unavailable
2421  * are "eliminated". Once all threads are eliminated from satisfying a promise,
2422  * that promise has failed.
2423  *
2424  * @param act The ModelAction which updated the modification order
2425  * @param is_read_check Should be true if act is a read and we must check for
2426  * updates to the store from which it read (there is a distinction here for
2427  * RMW's, which are both a load and a store)
2428  */
2429 void ModelExecution::mo_check_promises(const ModelAction *act, bool is_read_check)
2430 {
2431         const ModelAction *write = is_read_check ? act->get_reads_from() : act;
2432
2433         for (unsigned int i = 0; i < promises.size(); i++) {
2434                 Promise *promise = promises[i];
2435
2436                 // Is this promise on the same location?
2437                 if (!promise->same_location(write))
2438                         continue;
2439
2440                 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2441                         const ModelAction *pread = promise->get_reader(j);
2442                         if (!pread->happens_before(act))
2443                                continue;
2444                         if (mo_graph->checkPromise(write, promise)) {
2445                                 priv->failed_promise = true;
2446                                 return;
2447                         }
2448                         break;
2449                 }
2450
2451                 // Don't do any lookups twice for the same thread
2452                 if (!promise->thread_is_available(act->get_tid()))
2453                         continue;
2454
2455                 if (mo_graph->checkReachable(promise, write)) {
2456                         if (mo_graph->checkPromise(write, promise)) {
2457                                 priv->failed_promise = true;
2458                                 return;
2459                         }
2460                 }
2461         }
2462 }
2463
2464 /**
2465  * Compute the set of writes that may break the current pending release
2466  * sequence. This information is extracted from previou release sequence
2467  * calculations.
2468  *
2469  * @param curr The current ModelAction. Must be a release sequence fixup
2470  * action.
2471  */
2472 void ModelExecution::compute_relseq_breakwrites(ModelAction *curr)
2473 {
2474         if (pending_rel_seqs.empty())
2475                 return;
2476
2477         struct release_seq *pending = pending_rel_seqs.back();
2478         for (unsigned int i = 0; i < pending->writes.size(); i++) {
2479                 const ModelAction *write = pending->writes[i];
2480                 curr->get_node()->add_relseq_break(write);
2481         }
2482
2483         /* NULL means don't break the sequence; just synchronize */
2484         curr->get_node()->add_relseq_break(NULL);
2485 }
2486
2487 /**
2488  * Build up an initial set of all past writes that this 'read' action may read
2489  * from, as well as any previously-observed future values that must still be valid.
2490  *
2491  * @param curr is the current ModelAction that we are exploring; it must be a
2492  * 'read' operation.
2493  */
2494 void ModelExecution::build_may_read_from(ModelAction *curr)
2495 {
2496         SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
2497         unsigned int i;
2498         ASSERT(curr->is_read());
2499
2500         ModelAction *last_sc_write = NULL;
2501
2502         if (curr->is_seqcst())
2503                 last_sc_write = get_last_seq_cst_write(curr);
2504
2505         /* Iterate over all threads */
2506         for (i = 0; i < thrd_lists->size(); i++) {
2507                 /* Iterate over actions in thread, starting from most recent */
2508                 action_list_t *list = &(*thrd_lists)[i];
2509                 action_list_t::reverse_iterator rit;
2510                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
2511                         ModelAction *act = *rit;
2512
2513                         /* Only consider 'write' actions */
2514                         if (!act->is_write() || act == curr)
2515                                 continue;
2516
2517                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
2518                         bool allow_read = true;
2519
2520                         if (curr->is_seqcst() && (act->is_seqcst() || (last_sc_write != NULL && act->happens_before(last_sc_write))) && act != last_sc_write)
2521                                 allow_read = false;
2522                         else if (curr->get_sleep_flag() && !curr->is_seqcst() && !sleep_can_read_from(curr, act))
2523                                 allow_read = false;
2524
2525                         if (allow_read) {
2526                                 /* Only add feasible reads */
2527                                 mo_graph->startChanges();
2528                                 r_modification_order(curr, act);
2529                                 if (!is_infeasible())
2530                                         curr->get_node()->add_read_from_past(act);
2531                                 mo_graph->rollbackChanges();
2532                         }
2533
2534                         /* Include at most one act per-thread that "happens before" curr */
2535                         if (act->happens_before(curr))
2536                                 break;
2537                 }
2538         }
2539
2540         /* Inherit existing, promised future values */
2541         for (i = 0; i < promises.size(); i++) {
2542                 const Promise *promise = promises[i];
2543                 const ModelAction *promise_read = promise->get_reader(0);
2544                 if (promise_read->same_var(curr)) {
2545                         /* Only add feasible future-values */
2546                         mo_graph->startChanges();
2547                         r_modification_order(curr, promise);
2548                         if (!is_infeasible())
2549                                 curr->get_node()->add_read_from_promise(promise_read);
2550                         mo_graph->rollbackChanges();
2551                 }
2552         }
2553
2554         /* We may find no valid may-read-from only if the execution is doomed */
2555         if (!curr->get_node()->read_from_size()) {
2556                 priv->no_valid_reads = true;
2557                 set_assert();
2558         }
2559
2560         if (DBG_ENABLED()) {
2561                 model_print("Reached read action:\n");
2562                 curr->print();
2563                 model_print("Printing read_from_past\n");
2564                 curr->get_node()->print_read_from_past();
2565                 model_print("End printing read_from_past\n");
2566         }
2567 }
2568
2569 bool ModelExecution::sleep_can_read_from(ModelAction *curr, const ModelAction *write)
2570 {
2571         for ( ; write != NULL; write = write->get_reads_from()) {
2572                 /* UNINIT actions don't have a Node, and they never sleep */
2573                 if (write->is_uninitialized())
2574                         return true;
2575                 Node *prevnode = write->get_node()->get_parent();
2576
2577                 bool thread_sleep = prevnode->enabled_status(curr->get_tid()) == THREAD_SLEEP_SET;
2578                 if (write->is_release() && thread_sleep)
2579                         return true;
2580                 if (!write->is_rmw())
2581                         return false;
2582         }
2583         return true;
2584 }
2585
2586 /**
2587  * @brief Get an action representing an uninitialized atomic
2588  *
2589  * This function may create a new one or try to retrieve one from the NodeStack
2590  *
2591  * @param curr The current action, which prompts the creation of an UNINIT action
2592  * @return A pointer to the UNINIT ModelAction
2593  */
2594 ModelAction * ModelExecution::get_uninitialized_action(const ModelAction *curr) const
2595 {
2596         Node *node = curr->get_node();
2597         ModelAction *act = node->get_uninit_action();
2598         if (!act) {
2599                 act = new ModelAction(ATOMIC_UNINIT, std::memory_order_relaxed, curr->get_location(), params->uninitvalue, model_thread);
2600                 node->set_uninit_action(act);
2601         }
2602         act->create_cv(NULL);
2603         return act;
2604 }
2605
2606 static void print_list(const action_list_t *list)
2607 {
2608         action_list_t::const_iterator it;
2609
2610         model_print("---------------------------------------------------------------------\n");
2611
2612         unsigned int hash = 0;
2613
2614         for (it = list->begin(); it != list->end(); it++) {
2615                 const ModelAction *act = *it;
2616                 if (act->get_seq_number() > 0)
2617                         act->print();
2618                 hash = hash^(hash<<3)^((*it)->hash());
2619         }
2620         model_print("HASH %u\n", hash);
2621         model_print("---------------------------------------------------------------------\n");
2622 }
2623
2624 #if SUPPORT_MOD_ORDER_DUMP
2625 void ModelExecution::dumpGraph(char *filename) const
2626 {
2627         char buffer[200];
2628         sprintf(buffer, "%s.dot", filename);
2629         FILE *file = fopen(buffer, "w");
2630         fprintf(file, "digraph %s {\n", filename);
2631         mo_graph->dumpNodes(file);
2632         ModelAction **thread_array = (ModelAction **)model_calloc(1, sizeof(ModelAction *) * get_num_threads());
2633
2634         for (action_list_t::iterator it = action_trace.begin(); it != action_trace.end(); it++) {
2635                 ModelAction *act = *it;
2636                 if (act->is_read()) {
2637                         mo_graph->dot_print_node(file, act);
2638                         if (act->get_reads_from())
2639                                 mo_graph->dot_print_edge(file,
2640                                                 act->get_reads_from(),
2641                                                 act,
2642                                                 "label=\"rf\", color=red, weight=2");
2643                         else
2644                                 mo_graph->dot_print_edge(file,
2645                                                 act->get_reads_from_promise(),
2646                                                 act,
2647                                                 "label=\"rf\", color=red");
2648                 }
2649                 if (thread_array[act->get_tid()]) {
2650                         mo_graph->dot_print_edge(file,
2651                                         thread_array[id_to_int(act->get_tid())],
2652                                         act,
2653                                         "label=\"sb\", color=blue, weight=400");
2654                 }
2655
2656                 thread_array[act->get_tid()] = act;
2657         }
2658         fprintf(file, "}\n");
2659         model_free(thread_array);
2660         fclose(file);
2661 }
2662 #endif
2663
2664 /** @brief Prints an execution trace summary. */
2665 void ModelExecution::print_summary() const
2666 {
2667 #if SUPPORT_MOD_ORDER_DUMP
2668         char buffername[100];
2669         sprintf(buffername, "exec%04u", get_execution_number());
2670         mo_graph->dumpGraphToFile(buffername);
2671         sprintf(buffername, "graph%04u", get_execution_number());
2672         dumpGraph(buffername);
2673 #endif
2674
2675         model_print("Execution %d:", get_execution_number());
2676         if (isfeasibleprefix()) {
2677                 if (params->yieldblock && is_yieldblocked())
2678                         model_print(" YIELD BLOCKED");
2679                 if (scheduler->all_threads_sleeping())
2680                         model_print(" SLEEP-SET REDUNDANT");
2681                 model_print("\n");
2682         } else
2683                 print_infeasibility(" INFEASIBLE");
2684         print_list(&action_trace);
2685         model_print("\n");
2686         if (!promises.empty()) {
2687                 model_print("Pending promises:\n");
2688                 for (unsigned int i = 0; i < promises.size(); i++) {
2689                         model_print(" [P%u] ", i);
2690                         promises[i]->print();
2691                 }
2692                 model_print("\n");
2693         }
2694 }
2695
2696 /**
2697  * Add a Thread to the system for the first time. Should only be called once
2698  * per thread.
2699  * @param t The Thread to add
2700  */
2701 void ModelExecution::add_thread(Thread *t)
2702 {
2703         unsigned int i = id_to_int(t->get_id());
2704         if (i >= thread_map.size())
2705                 thread_map.resize(i + 1);
2706         thread_map[i] = t;
2707         if (!t->is_model_thread())
2708                 scheduler->add_thread(t);
2709 }
2710
2711 /**
2712  * @brief Get a Thread reference by its ID
2713  * @param tid The Thread's ID
2714  * @return A Thread reference
2715  */
2716 Thread * ModelExecution::get_thread(thread_id_t tid) const
2717 {
2718         unsigned int i = id_to_int(tid);
2719         if (i < thread_map.size())
2720                 return thread_map[i];
2721         return NULL;
2722 }
2723
2724 /**
2725  * @brief Get a reference to the Thread in which a ModelAction was executed
2726  * @param act The ModelAction
2727  * @return A Thread reference
2728  */
2729 Thread * ModelExecution::get_thread(const ModelAction *act) const
2730 {
2731         return get_thread(act->get_tid());
2732 }
2733
2734 /**
2735  * @brief Get a Promise's "promise number"
2736  *
2737  * A "promise number" is an index number that is unique to a promise, valid
2738  * only for a specific snapshot of an execution trace. Promises may come and go
2739  * as they are generated an resolved, so an index only retains meaning for the
2740  * current snapshot.
2741  *
2742  * @param promise The Promise to check
2743  * @return The promise index, if the promise still is valid; otherwise -1
2744  */
2745 int ModelExecution::get_promise_number(const Promise *promise) const
2746 {
2747         for (unsigned int i = 0; i < promises.size(); i++)
2748                 if (promises[i] == promise)
2749                         return i;
2750         /* Not found */
2751         return -1;
2752 }
2753
2754 /**
2755  * @brief Check if a Thread is currently enabled
2756  * @param t The Thread to check
2757  * @return True if the Thread is currently enabled
2758  */
2759 bool ModelExecution::is_enabled(Thread *t) const
2760 {
2761         return scheduler->is_enabled(t);
2762 }
2763
2764 /**
2765  * @brief Check if a Thread is currently enabled
2766  * @param tid The ID of the Thread to check
2767  * @return True if the Thread is currently enabled
2768  */
2769 bool ModelExecution::is_enabled(thread_id_t tid) const
2770 {
2771         return scheduler->is_enabled(tid);
2772 }
2773
2774 /**
2775  * @brief Select the next thread to execute based on the curren action
2776  *
2777  * RMW actions occur in two parts, and we cannot split them. And THREAD_CREATE
2778  * actions should be followed by the execution of their child thread. In either
2779  * case, the current action should determine the next thread schedule.
2780  *
2781  * @param curr The current action
2782  * @return The next thread to run, if the current action will determine this
2783  * selection; otherwise NULL
2784  */
2785 Thread * ModelExecution::action_select_next_thread(const ModelAction *curr) const
2786 {
2787         /* Do not split atomic RMW */
2788         if (curr->is_rmwr())
2789                 return get_thread(curr);
2790         /* Follow CREATE with the created thread */
2791         if (curr->get_type() == THREAD_CREATE)
2792                 return curr->get_thread_operand();
2793         return NULL;
2794 }
2795
2796 /** @return True if the execution has taken too many steps */
2797 bool ModelExecution::too_many_steps() const
2798 {
2799         return params->bound != 0 && priv->used_sequence_numbers > params->bound;
2800 }
2801
2802 /**
2803  * Takes the next step in the execution, if possible.
2804  * @param curr The current step to take
2805  * @return Returns the next Thread to run, if any; NULL if this execution
2806  * should terminate
2807  */
2808 Thread * ModelExecution::take_step(ModelAction *curr)
2809 {
2810         Thread *curr_thrd = get_thread(curr);
2811         ASSERT(curr_thrd->get_state() == THREAD_READY);
2812
2813         ASSERT(check_action_enabled(curr)); /* May have side effects? */
2814         curr = check_current_action(curr);
2815         ASSERT(curr);
2816
2817         if (curr_thrd->is_blocked() || curr_thrd->is_complete())
2818                 scheduler->remove_thread(curr_thrd);
2819
2820         return action_select_next_thread(curr);
2821 }
2822
2823 /**
2824  * Launch end-of-execution release sequence fixups only when
2825  * the execution is otherwise feasible AND there are:
2826  *
2827  * (1) pending release sequences
2828  * (2) pending assertions that could be invalidated by a change
2829  * in clock vectors (i.e., data races)
2830  * (3) no pending promises
2831  */
2832 void ModelExecution::fixup_release_sequences()
2833 {
2834         while (!pending_rel_seqs.empty() &&
2835                         is_feasible_prefix_ignore_relseq() &&
2836                         haveUnrealizedRaces()) {
2837                 model_print("*** WARNING: release sequence fixup action "
2838                                 "(%zu pending release seuqence(s)) ***\n",
2839                                 pending_rel_seqs.size());
2840                 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2841                                 std::memory_order_seq_cst, NULL, VALUE_NONE,
2842                                 model_thread);
2843                 take_step(fixup);
2844         };
2845 }