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