pthread_create is working now
[c11tester.git] / action.cc
1 #include <stdio.h>
2 #define __STDC_FORMAT_MACROS
3 #include <inttypes.h>
4 #include <stdlib.h>
5
6 #include "model.h"
7 #include "action.h"
8 #include "clockvector.h"
9 #include "common.h"
10 #include "threads-model.h"
11 #include "nodestack.h"
12 #include "wildcard.h"
13
14 #define ACTION_INITIAL_CLOCK 0
15
16 /** @brief A special value to represent a successful trylock */
17 #define VALUE_TRYSUCCESS 1
18
19 /** @brief A special value to represent a failed trylock */
20 #define VALUE_TRYFAILED 0
21
22 /**
23  * @brief Construct a new ModelAction
24  *
25  * @param type The type of action
26  * @param order The memory order of this action. A "don't care" for non-ATOMIC
27  * actions (e.g., THREAD_* or MODEL_* actions).
28  * @param loc The location that this action acts upon
29  * @param value (optional) A value associated with the action (e.g., the value
30  * read or written). Defaults to a given macro constant, for debugging purposes.
31  * @param thread (optional) The Thread in which this action occurred. If NULL
32  * (default), then a Thread is assigned according to the scheduler.
33  */
34 ModelAction::ModelAction(action_type_t type, memory_order order, void *loc,
35                 uint64_t value, Thread *thread) :
36         type(type),
37         order(order),
38         original_order(order),
39         location(loc),
40         value(value),
41         reads_from(NULL),
42         reads_from_promise(NULL),
43         last_fence_release(NULL),
44         node(NULL),
45         seq_number(ACTION_INITIAL_CLOCK),
46         cv(NULL),
47         sleep_flag(false)
48 {
49         /* References to NULL atomic variables can end up here */
50         ASSERT(loc || type == ATOMIC_FENCE || type == MODEL_FIXUP_RELSEQ);
51
52         Thread *t = thread ? thread : thread_current();
53         this->tid = t->get_id();
54 }
55
56 /** @brief ModelAction destructor */
57 ModelAction::~ModelAction()
58 {
59         /**
60          * We can't free the clock vector:
61          * Clock vectors are snapshotting state. When we delete model actions,
62          * they are at the end of the node list and have invalid old clock
63          * vectors which have already been rolled back to an unallocated state.
64          */
65
66         /*
67          if (cv)
68                 delete cv; */
69 }
70
71 void ModelAction::copy_from_new(ModelAction *newaction)
72 {
73         seq_number = newaction->seq_number;
74 }
75
76 void ModelAction::set_seq_number(modelclock_t num)
77 {
78         /* ATOMIC_UNINIT actions should never have non-zero clock */
79         ASSERT(!is_uninitialized());
80         ASSERT(seq_number == ACTION_INITIAL_CLOCK);
81         seq_number = num;
82 }
83
84 bool ModelAction::is_thread_start() const
85 {
86         return type == THREAD_START;
87 }
88
89 bool ModelAction::is_thread_join() const
90 {
91         return type == THREAD_JOIN;
92 }
93
94 bool ModelAction::is_relseq_fixup() const
95 {
96         return type == MODEL_FIXUP_RELSEQ;
97 }
98
99 bool ModelAction::is_mutex_op() const
100 {
101         return type == ATOMIC_LOCK || type == ATOMIC_TRYLOCK || type == ATOMIC_UNLOCK || type == ATOMIC_WAIT || type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
102 }
103
104 bool ModelAction::is_lock() const
105 {
106         return type == ATOMIC_LOCK;
107 }
108
109 bool ModelAction::is_wait() const {
110         return type == ATOMIC_WAIT;
111 }
112
113 bool ModelAction::is_notify() const {
114         return type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
115 }
116
117 bool ModelAction::is_notify_one() const {
118         return type == ATOMIC_NOTIFY_ONE;
119 }
120
121 bool ModelAction::is_unlock() const
122 {
123         return type == ATOMIC_UNLOCK;
124 }
125
126 bool ModelAction::is_trylock() const
127 {
128         return type == ATOMIC_TRYLOCK;
129 }
130
131 bool ModelAction::is_success_lock() const
132 {
133         return type == ATOMIC_LOCK || (type == ATOMIC_TRYLOCK && value == VALUE_TRYSUCCESS);
134 }
135
136 bool ModelAction::is_failed_trylock() const
137 {
138         return (type == ATOMIC_TRYLOCK && value == VALUE_TRYFAILED);
139 }
140
141 /** @return True if this operation is performed on a C/C++ atomic variable */
142 bool ModelAction::is_atomic_var() const
143 {
144         return is_read() || could_be_write();
145 }
146
147 bool ModelAction::is_uninitialized() const
148 {
149         return type == ATOMIC_UNINIT;
150 }
151
152 bool ModelAction::is_read() const
153 {
154         return type == ATOMIC_READ || type == ATOMIC_RMWR || type == ATOMIC_RMW;
155 }
156
157 bool ModelAction::is_write() const
158 {
159         return type == ATOMIC_WRITE || type == ATOMIC_RMW || type == ATOMIC_INIT || type == ATOMIC_UNINIT;
160 }
161
162 bool ModelAction::could_be_write() const
163 {
164         return is_write() || is_rmwr();
165 }
166
167 bool ModelAction::is_yield() const
168 {
169         return type == THREAD_YIELD;
170 }
171
172 bool ModelAction::is_rmwr() const
173 {
174         return type == ATOMIC_RMWR;
175 }
176
177 bool ModelAction::is_rmw() const
178 {
179         return type == ATOMIC_RMW;
180 }
181
182 bool ModelAction::is_rmwc() const
183 {
184         return type == ATOMIC_RMWC;
185 }
186
187 bool ModelAction::is_fence() const
188 {
189         return type == ATOMIC_FENCE;
190 }
191
192 bool ModelAction::is_initialization() const
193 {
194         return type == ATOMIC_INIT;
195 }
196
197 bool ModelAction::is_annotation() const
198 {
199         return type == ATOMIC_ANNOTATION;
200 }
201
202 bool ModelAction::is_relaxed() const
203 {
204         return order == std::memory_order_relaxed;
205 }
206
207 bool ModelAction::is_acquire() const
208 {
209         switch (order) {
210         case std::memory_order_acquire:
211         case std::memory_order_acq_rel:
212         case std::memory_order_seq_cst:
213                 return true;
214         default:
215                 return false;
216         }
217 }
218
219 bool ModelAction::is_release() const
220 {
221         switch (order) {
222         case std::memory_order_release:
223         case std::memory_order_acq_rel:
224         case std::memory_order_seq_cst:
225                 return true;
226         default:
227                 return false;
228         }
229 }
230
231 bool ModelAction::is_seqcst() const
232 {
233         return order == std::memory_order_seq_cst;
234 }
235
236 bool ModelAction::same_var(const ModelAction *act) const
237 {
238         if (act->is_wait() || is_wait()) {
239                 if (act->is_wait() && is_wait()) {
240                         if (((void *)value) == ((void *)act->value))
241                                 return true;
242                 } else if (is_wait()) {
243                         if (((void *)value) == act->location)
244                                 return true;
245                 } else if (act->is_wait()) {
246                         if (location == ((void *)act->value))
247                                 return true;
248                 }
249         }
250
251         return location == act->location;
252 }
253
254 bool ModelAction::same_thread(const ModelAction *act) const
255 {
256         return tid == act->tid;
257 }
258
259 void ModelAction::copy_typeandorder(ModelAction * act)
260 {
261         this->type = act->type;
262         this->order = act->order;
263 }
264
265 /**
266  * Get the Thread which is the operand of this action. This is only valid for
267  * THREAD_* operations (currently only for THREAD_CREATE and THREAD_JOIN). Note
268  * that this provides a central place for determining the conventions of Thread
269  * storage in ModelAction, where we generally aren't very type-safe (e.g., we
270  * store object references in a (void *) address.
271  *
272  * For THREAD_CREATE, this yields the Thread which is created.
273  * For THREAD_JOIN, this yields the Thread we are joining with.
274  *
275  * @return The Thread which this action acts on, if exists; otherwise NULL
276  */
277 Thread * ModelAction::get_thread_operand() const
278 {
279         if (type == THREAD_CREATE) {
280                 /* THREAD_CREATE stores its (Thread *) in a thrd_t::priv */
281                 thrd_t *thrd = (thrd_t *)get_location();
282                 return thrd->priv;
283         } else if (type == PTHREAD_CREATE) {
284                 // not implemented
285                 return NULL;
286         } else if (type == THREAD_JOIN) {
287                 /* THREAD_JOIN uses (Thread *) for location */
288                 return (Thread *)get_location();
289         } else if (type == PTHREAD_JOIN) {
290                 // WL: to be added (modified)
291                 return (Thread *)get_location();
292         } else
293                 return NULL;
294 }
295
296 /**
297  * @brief Convert the read portion of an RMW
298  *
299  * Changes an existing read part of an RMW action into either:
300  *  -# a full RMW action in case of the completed write or
301  *  -# a READ action in case a failed action.
302  *
303  * @todo  If the memory_order changes, we may potentially need to update our
304  * clock vector.
305  *
306  * @param act The second half of the RMW (either RMWC or RMW)
307  */
308 void ModelAction::process_rmw(ModelAction *act)
309 {
310         this->order = act->order;
311         if (act->is_rmwc())
312                 this->type = ATOMIC_READ;
313         else if (act->is_rmw()) {
314                 this->type = ATOMIC_RMW;
315                 this->value = act->value;
316         }
317 }
318
319 /**
320  * @brief Check if this action should be backtracked with another, due to
321  * potential synchronization
322  *
323  * The is_synchronizing method should only explore interleavings if:
324  *  -# the operations are seq_cst and don't commute or
325  *  -# the reordering may establish or break a synchronization relation.
326  *
327  * Other memory operations will be dealt with by using the reads_from relation.
328  *
329  * @param act The action to consider exploring a reordering
330  * @return True, if we have to explore a reordering; otherwise false
331  */
332 bool ModelAction::could_synchronize_with(const ModelAction *act) const
333 {
334         // Same thread can't be reordered
335         if (same_thread(act))
336                 return false;
337
338         // Different locations commute
339         if (!same_var(act) && !is_fence() && !act->is_fence())
340                 return false;
341
342         // Explore interleavings of seqcst writes/fences to guarantee total
343         // order of seq_cst operations that don't commute
344         if ((could_be_write() || act->could_be_write() || is_fence() || act->is_fence()) && is_seqcst() && act->is_seqcst())
345                 return true;
346
347         // Explore synchronizing read/write pairs
348         if (is_acquire() && act->is_release() && is_read() && act->could_be_write())
349                 return true;
350
351         // lock just released...we can grab lock
352         if ((is_lock() || is_trylock()) && (act->is_unlock() || act->is_wait()))
353                 return true;
354
355         // lock just acquired...we can fail to grab lock
356         if (is_trylock() && act->is_success_lock())
357                 return true;
358
359         // other thread stalling on lock...we can release lock
360         if (is_unlock() && (act->is_trylock() || act->is_lock()))
361                 return true;
362
363         if (is_trylock() && (act->is_unlock() || act->is_wait()))
364                 return true;
365
366         if (is_notify() && act->is_wait())
367                 return true;
368
369         if (is_wait() && act->is_notify())
370                 return true;
371
372         // Otherwise handle by reads_from relation
373         return false;
374 }
375
376 bool ModelAction::is_conflicting_lock(const ModelAction *act) const
377 {
378         // Must be different threads to reorder
379         if (same_thread(act))
380                 return false;
381
382         // Try to reorder a lock past a successful lock
383         if (act->is_success_lock())
384                 return true;
385
386         // Try to push a successful trylock past an unlock
387         if (act->is_unlock() && is_trylock() && value == VALUE_TRYSUCCESS)
388                 return true;
389
390         // Try to push a successful trylock past a wait
391         if (act->is_wait() && is_trylock() && value == VALUE_TRYSUCCESS)
392                 return true;
393
394         return false;
395 }
396
397 /**
398  * Create a new clock vector for this action. Note that this function allows a
399  * user to clobber (and leak) a ModelAction's existing clock vector. A user
400  * should ensure that the vector has already either been rolled back
401  * (effectively "freed") or freed.
402  *
403  * @param parent A ModelAction from which to inherit a ClockVector
404  */
405 void ModelAction::create_cv(const ModelAction *parent)
406 {
407         if (parent)
408                 cv = new ClockVector(parent->cv, this);
409         else
410                 cv = new ClockVector(NULL, this);
411 }
412
413 void ModelAction::set_try_lock(bool obtainedlock)
414 {
415         value = obtainedlock ? VALUE_TRYSUCCESS : VALUE_TRYFAILED;
416 }
417
418 /**
419  * @brief Get the value read by this load
420  *
421  * We differentiate this function from ModelAction::get_write_value and
422  * ModelAction::get_value for the purpose of RMW's, which may have both a
423  * 'read' and a 'write' value.
424  *
425  * Note: 'this' must be a load.
426  *
427  * @return The value read by this load
428  */
429 uint64_t ModelAction::get_reads_from_value() const
430 {
431         ASSERT(is_read());
432         if (reads_from)
433                 return reads_from->get_write_value();
434         else if (reads_from_promise)
435                 return reads_from_promise->get_value();
436         return VALUE_NONE; /* Only for new actions with no reads-from */
437 }
438
439 /**
440  * @brief Get the value written by this store
441  *
442  * We differentiate this function from ModelAction::get_reads_from_value and
443  * ModelAction::get_value for the purpose of RMW's, which may have both a
444  * 'read' and a 'write' value.
445  *
446  * Note: 'this' must be a store.
447  *
448  * @return The value written by this store
449  */
450 uint64_t ModelAction::get_write_value() const
451 {
452         ASSERT(is_write());
453         return value;
454 }
455
456 /**
457  * @brief Get the value returned by this action
458  *
459  * For atomic reads (including RMW), an operation returns the value it read.
460  * For atomic writes, an operation returns the value it wrote. For other
461  * operations, the return value varies (sometimes is a "don't care"), but the
462  * value is simply stored in the "value" field.
463  *
464  * @return This action's return value
465  */
466 uint64_t ModelAction::get_return_value() const
467 {
468         if (is_read())
469                 return get_reads_from_value();
470         else if (is_write())
471                 return get_write_value();
472         else
473                 return value;
474 }
475
476 /** @return The Node associated with this ModelAction */
477 Node * ModelAction::get_node() const
478 {
479         /* UNINIT actions do not have a Node */
480         ASSERT(!is_uninitialized());
481         return node;
482 }
483
484 /**
485  * Update the model action's read_from action
486  * @param act The action to read from; should be a write
487  */
488 void ModelAction::set_read_from(const ModelAction *act)
489 {
490         ASSERT(act);
491
492         reads_from = act;
493         reads_from_promise = NULL;
494
495         if (act->is_uninitialized()) { // WL
496                 uint64_t val = *((uint64_t *) location);
497                 ModelAction * act_initialized = (ModelAction *)act;
498                 act_initialized->set_value(val);
499                 reads_from = (const ModelAction *)act_initialized;
500
501 // disabled by WL, because LLVM IR is unable to detect atomic init
502 /*              model->assert_bug("May read from uninitialized atomic:\n"
503                                 "    action %d, thread %d, location %p (%s, %s)",
504                                 seq_number, id_to_int(tid), location,
505                                 get_type_str(), get_mo_str());
506 */
507         }
508 }
509
510 /**
511  * Set this action's read-from promise
512  * @param promise The promise to read from
513  */
514 void ModelAction::set_read_from_promise(Promise *promise)
515 {
516         ASSERT(is_read());
517         reads_from_promise = promise;
518         reads_from = NULL;
519 }
520
521 /**
522  * Synchronize the current thread with the thread corresponding to the
523  * ModelAction parameter.
524  * @param act The ModelAction to synchronize with
525  * @return True if this is a valid synchronization; false otherwise
526  */
527 bool ModelAction::synchronize_with(const ModelAction *act)
528 {
529         if (*this < *act)
530                 return false;
531         cv->merge(act->cv);
532         return true;
533 }
534
535 bool ModelAction::has_synchronized_with(const ModelAction *act) const
536 {
537         return cv->synchronized_since(act);
538 }
539
540 /**
541  * Check whether 'this' happens before act, according to the memory-model's
542  * happens before relation. This is checked via the ClockVector constructs.
543  * @return true if this action's thread has synchronized with act's thread
544  * since the execution of act, false otherwise.
545  */
546 bool ModelAction::happens_before(const ModelAction *act) const
547 {
548         return act->cv->synchronized_since(this);
549 }
550
551 const char * ModelAction::get_type_str() const
552 {
553         switch (this->type) {
554                 case MODEL_FIXUP_RELSEQ: return "relseq fixup";
555                 case THREAD_CREATE: return "thread create";
556                 case THREAD_START: return "thread start";
557                 case THREAD_YIELD: return "thread yield";
558                 case THREAD_JOIN: return "thread join";
559                 case THREAD_FINISH: return "thread finish";
560
561                 case PTHREAD_CREATE: return "pthread create";
562                 case PTHREAD_JOIN: return "pthread join";
563
564                 case ATOMIC_UNINIT: return "uninitialized";
565                 case ATOMIC_READ: return "atomic read";
566                 case ATOMIC_WRITE: return "atomic write";
567                 case ATOMIC_RMW: return "atomic rmw";
568                 case ATOMIC_FENCE: return "fence";
569                 case ATOMIC_RMWR: return "atomic rmwr";
570                 case ATOMIC_RMWC: return "atomic rmwc";
571                 case ATOMIC_INIT: return "init atomic";
572                 case ATOMIC_LOCK: return "lock";
573                 case ATOMIC_UNLOCK: return "unlock";
574                 case ATOMIC_TRYLOCK: return "trylock";
575                 case ATOMIC_WAIT: return "wait";
576                 case ATOMIC_NOTIFY_ONE: return "notify one";
577           case ATOMIC_NOTIFY_ALL: return "notify all";
578           case ATOMIC_ANNOTATION: return "annotation";
579                 default: return "unknown type";
580         };
581 }
582
583 const char * ModelAction::get_mo_str() const
584 {
585         switch (this->order) {
586                 case std::memory_order_relaxed: return "relaxed";
587                 case std::memory_order_acquire: return "acquire";
588                 case std::memory_order_release: return "release";
589                 case std::memory_order_acq_rel: return "acq_rel";
590                 case std::memory_order_seq_cst: return "seq_cst";
591                 default: return "unknown";
592         }
593 }
594
595 /** @brief Print nicely-formatted info about this ModelAction */
596 void ModelAction::print() const
597 {
598         const char *type_str = get_type_str(), *mo_str = get_mo_str();
599
600         model_print("%-4d %-2d   %-13s   %7s  %14p   %-#18" PRIx64,
601                         seq_number, id_to_int(tid), type_str, mo_str, location, get_return_value());
602         if (is_read()) {
603                 if (reads_from)
604                         model_print("  %-3d", reads_from->get_seq_number());
605                 else if (reads_from_promise) {
606                         int idx = reads_from_promise->get_index();
607                         if (idx >= 0)
608                                 model_print("  P%-2d", idx);
609                         else
610                                 model_print("  P? ");
611                 } else
612                         model_print("  ?  ");
613         }
614         if (cv) {
615                 if (is_read())
616                         model_print(" ");
617                 else
618                         model_print("      ");
619                 cv->print();
620         } else
621                 model_print("\n");
622 }
623
624 /** @brief Get a (likely) unique hash for this ModelAction */
625 unsigned int ModelAction::hash() const
626 {
627         unsigned int hash = (unsigned int)this->type;
628         hash ^= ((unsigned int)this->order) << 3;
629         hash ^= seq_number << 5;
630         hash ^= id_to_int(tid) << 6;
631
632         if (is_read()) {
633                if (reads_from)
634                        hash ^= reads_from->get_seq_number();
635                else if (reads_from_promise)
636                        hash ^= reads_from_promise->get_index();
637                hash ^= get_reads_from_value();
638         }
639         return hash;
640 }
641
642 /**
643  * @brief Checks the NodeStack to see if a ModelAction is in our may-read-from set
644  * @param write The ModelAction to check for
645  * @return True if the ModelAction is found; false otherwise
646  */
647 bool ModelAction::may_read_from(const ModelAction *write) const
648 {
649         for (int i = 0; i < node->get_read_from_past_size(); i++)
650                 if (node->get_read_from_past(i) == write)
651                         return true;
652         return false;
653 }
654
655 /**
656  * @brief Checks the NodeStack to see if a Promise is in our may-read-from set
657  * @param promise The Promise to check for
658  * @return True if the Promise is found; false otherwise
659  */
660 bool ModelAction::may_read_from(const Promise *promise) const
661 {
662         for (int i = 0; i < node->get_read_from_promise_size(); i++)
663                 if (node->get_read_from_promise(i) == promise)
664                         return true;
665         return false;
666 }
667
668 /**
669  * Only valid for LOCK, TRY_LOCK, UNLOCK, and WAIT operations.
670  * @return The mutex operated on by this action, if any; otherwise NULL
671  */
672 std::mutex * ModelAction::get_mutex() const
673 {
674         if (is_trylock() || is_lock() || is_unlock())
675                 return (std::mutex *)get_location();
676         else if (is_wait())
677                 return (std::mutex *)get_value();
678         else
679                 return NULL;
680 }