69d6660bccee0768d2f8629d8ca787e6b3912d22
[c11tester.git] / cyclegraph.cc
1 #include "cyclegraph.h"
2 #include "action.h"
3 #include "common.h"
4 #include "promise.h"
5 #include "model.h"
6
7 /** Initializes a CycleGraph object. */
8 CycleGraph::CycleGraph() :
9         discovered(new HashTable<const CycleNode *, const CycleNode *, uintptr_t, 4, model_malloc, model_calloc, model_free>(16)),
10         hasCycles(false),
11         oldCycles(false)
12 {
13 }
14
15 /** CycleGraph destructor */
16 CycleGraph::~CycleGraph()
17 {
18         delete discovered;
19 }
20
21 /**
22  * Add a CycleNode to the graph, corresponding to a store ModelAction
23  * @param act The write action that should be added
24  * @param node The CycleNode that corresponds to the store
25  */
26 void CycleGraph::putNode(const ModelAction *act, CycleNode *node)
27 {
28         actionToNode.put(act, node);
29 #if SUPPORT_MOD_ORDER_DUMP
30         nodeList.push_back(node);
31 #endif
32 }
33
34 /**
35  * Add a CycleNode to the graph, corresponding to a Promise
36  * @param promise The Promise that should be added
37  * @param node The CycleNode that corresponds to the Promise
38  */
39 void CycleGraph::putNode(const Promise *promise, CycleNode *node)
40 {
41         const ModelAction *reader = promise->get_action();
42         readerToPromiseNode.put(reader, node);
43 #if SUPPORT_MOD_ORDER_DUMP
44         nodeList.push_back(node);
45 #endif
46 }
47
48 /**
49  * @brief Remove the Promise node from the graph
50  * @param promise The promise to remove from the graph
51  */
52 void CycleGraph::erasePromiseNode(const Promise *promise)
53 {
54         const ModelAction *reader = promise->get_action();
55         readerToPromiseNode.put(reader, NULL);
56 #if SUPPORT_MOD_ORDER_DUMP
57         /* Remove the promise node from nodeList */
58         CycleNode *node = getNode_noCreate(promise);
59         for (unsigned int i = 0; i < nodeList.size(); )
60                 if (nodeList[i] == node)
61                         nodeList.erase(nodeList.begin() + i);
62                 else
63                         i++;
64 #endif
65 }
66
67 /** @return The corresponding CycleNode, if exists; otherwise NULL */
68 CycleNode * CycleGraph::getNode_noCreate(const ModelAction *act) const
69 {
70         return actionToNode.get(act);
71 }
72
73 /** @return The corresponding CycleNode, if exists; otherwise NULL */
74 CycleNode * CycleGraph::getNode_noCreate(const Promise *promise) const
75 {
76         return readerToPromiseNode.get(promise->get_action());
77 }
78
79 /**
80  * @brief Returns the CycleNode corresponding to a given ModelAction
81  *
82  * Gets (or creates, if none exist) a CycleNode corresponding to a ModelAction
83  *
84  * @param action The ModelAction to find a node for
85  * @return The CycleNode paired with this action
86  */
87 CycleNode * CycleGraph::getNode(const ModelAction *action)
88 {
89         CycleNode *node = getNode_noCreate(action);
90         if (node == NULL) {
91                 node = new CycleNode(action);
92                 putNode(action, node);
93         }
94         return node;
95 }
96
97 /**
98  * @brief Returns a CycleNode corresponding to a promise
99  *
100  * Gets (or creates, if none exist) a CycleNode corresponding to a promised
101  * value.
102  *
103  * @param promise The Promise generated by a reader
104  * @return The CycleNode corresponding to the Promise
105  */
106 CycleNode * CycleGraph::getNode(const Promise *promise)
107 {
108         CycleNode *node = getNode_noCreate(promise);
109         if (node == NULL) {
110                 node = new CycleNode(promise);
111                 putNode(promise, node);
112         }
113         return node;
114 }
115
116 /**
117  * @return false if the resolution results in a cycle; true otherwise
118  */
119 bool CycleGraph::resolvePromise(ModelAction *reader, ModelAction *writer,
120                 promise_list_t *mustResolve)
121 {
122         CycleNode *promise_node = readerToPromiseNode.get(reader);
123         CycleNode *w_node = actionToNode.get(writer);
124         ASSERT(promise_node);
125
126         if (w_node)
127                 return mergeNodes(w_node, promise_node, mustResolve);
128         /* No existing write-node; just convert the promise-node */
129         promise_node->resolvePromise(writer);
130         erasePromiseNode(promise_node->getPromise());
131         putNode(writer, promise_node);
132         return true;
133 }
134
135 /**
136  * @brief Merge two CycleNodes that represent the same write
137  *
138  * Note that this operation cannot be rolled back.
139  *
140  * @param w_node The write ModelAction node with which to merge
141  * @param p_node The Promise node to merge. Will be destroyed after this
142  * function.
143  * @param mustMerge Return (pass-by-reference) any additional Promises that
144  * must also be merged with w_node
145  *
146  * @return false if the merge results in a cycle; true otherwise
147  */
148 bool CycleGraph::mergeNodes(CycleNode *w_node, CycleNode *p_node,
149                 promise_list_t *mustMerge)
150 {
151         ASSERT(!w_node->is_promise());
152         ASSERT(p_node->is_promise());
153
154         const Promise *promise = p_node->getPromise();
155         if (!promise->is_compatible(w_node->getAction())) {
156                 hasCycles = true;
157                 return false;
158         }
159
160         /* Transfer the RMW */
161         CycleNode *promise_rmw = p_node->getRMW();
162         if (promise_rmw && promise_rmw != w_node->getRMW() && w_node->setRMW(promise_rmw)) {
163                 hasCycles = true;
164                 return false;
165         }
166
167         /* Transfer back edges to w_node */
168         while (p_node->getNumBackEdges() > 0) {
169                 CycleNode *back = p_node->removeBackEdge();
170                 if (back == w_node)
171                         continue;
172                 if (back->is_promise()) {
173                         if (checkReachable(w_node, back)) {
174                                 /* Edge would create cycle; merge instead */
175                                 mustMerge->push_back(back->getPromise());
176                                 if (!mergeNodes(w_node, back, mustMerge))
177                                         return false;
178                         } else
179                                 back->addEdge(w_node);
180                 } else
181                         addNodeEdge(back, w_node);
182         }
183
184         /* Transfer forward edges to w_node */
185         while (p_node->getNumEdges() > 0) {
186                 CycleNode *forward = p_node->removeEdge();
187                 if (forward == w_node)
188                         continue;
189                 if (forward->is_promise()) {
190                         if (checkReachable(forward, w_node)) {
191                                 mustMerge->push_back(forward->getPromise());
192                                 if (!mergeNodes(w_node, forward, mustMerge))
193                                         return false;
194                         } else
195                                 w_node->addEdge(forward);
196                 } else
197                         addNodeEdge(w_node, forward);
198         }
199
200         erasePromiseNode(promise);
201         delete p_node;
202
203         return !hasCycles;
204 }
205
206 /**
207  * Adds an edge between two CycleNodes.
208  * @param fromnode The edge comes from this CycleNode
209  * @param tonode The edge points to this CycleNode
210  * @return True, if new edge(s) are added; otherwise false
211  */
212 bool CycleGraph::addNodeEdge(CycleNode *fromnode, CycleNode *tonode)
213 {
214         bool added;
215
216         if (!hasCycles)
217                 hasCycles = checkReachable(tonode, fromnode);
218
219         if ((added = fromnode->addEdge(tonode)))
220                 rollbackvector.push_back(fromnode);
221
222         /*
223          * If the fromnode has a rmwnode that is not the tonode, we should add
224          * an edge between its rmwnode and the tonode
225          */
226         CycleNode *rmwnode = fromnode->getRMW();
227         if (rmwnode && rmwnode != tonode) {
228                 if (!hasCycles)
229                         hasCycles = checkReachable(tonode, rmwnode);
230
231                 if (rmwnode->addEdge(tonode)) {
232                         rollbackvector.push_back(rmwnode);
233                         added = true;
234                 }
235         }
236         return added;
237 }
238
239 /**
240  * @brief Add an edge between a write and the RMW which reads from it
241  *
242  * Handles special case of a RMW action, where the ModelAction rmw reads from
243  * the ModelAction/Promise from. The key differences are:
244  * (1) no write can occur in between the rmw and the from action.
245  * (2) Only one RMW action can read from a given write.
246  *
247  * @param from The edge comes from this ModelAction/Promise
248  * @param rmw The edge points to this ModelAction; this action must read from
249  * the ModelAction/Promise from
250  */
251 template <typename T>
252 void CycleGraph::addRMWEdge(const T *from, const ModelAction *rmw)
253 {
254         ASSERT(from);
255         ASSERT(rmw);
256
257         CycleNode *fromnode = getNode(from);
258         CycleNode *rmwnode = getNode(rmw);
259
260         /* Two RMW actions cannot read from the same write. */
261         if (fromnode->setRMW(rmwnode))
262                 hasCycles = true;
263         else
264                 rmwrollbackvector.push_back(fromnode);
265
266         /* Transfer all outgoing edges from the from node to the rmw node */
267         /* This process should not add a cycle because either:
268          * (1) The rmw should not have any incoming edges yet if it is the
269          * new node or
270          * (2) the fromnode is the new node and therefore it should not
271          * have any outgoing edges.
272          */
273         for (unsigned int i = 0; i < fromnode->getNumEdges(); i++) {
274                 CycleNode *tonode = fromnode->getEdge(i);
275                 if (tonode != rmwnode) {
276                         if (rmwnode->addEdge(tonode))
277                                 rollbackvector.push_back(rmwnode);
278                 }
279         }
280
281         addNodeEdge(fromnode, rmwnode);
282 }
283 /* Instantiate two forms of CycleGraph::addRMWEdge */
284 template void CycleGraph::addRMWEdge(const ModelAction *from, const ModelAction *rmw);
285 template void CycleGraph::addRMWEdge(const Promise *from, const ModelAction *rmw);
286
287 /**
288  * @brief Adds an edge between objects
289  *
290  * This function will add an edge between any two objects which can be
291  * associated with a CycleNode. That is, if they have a CycleGraph::getNode
292  * implementation.
293  *
294  * The object to is ordered after the object from.
295  *
296  * @param to The edge points to this object, of type T
297  * @param from The edge comes from this object, of type U
298  * @return True, if new edge(s) are added; otherwise false
299  */
300 template <typename T, typename U>
301 bool CycleGraph::addEdge(const T *from, const U *to)
302 {
303         ASSERT(from);
304         ASSERT(to);
305
306         CycleNode *fromnode = getNode(from);
307         CycleNode *tonode = getNode(to);
308
309         return addNodeEdge(fromnode, tonode);
310 }
311 /* Instantiate three forms of CycleGraph::addEdge */
312 template bool CycleGraph::addEdge(const ModelAction *from, const ModelAction *to);
313 template bool CycleGraph::addEdge(const ModelAction *from, const Promise *to);
314 template bool CycleGraph::addEdge(const Promise *from, const ModelAction *to);
315
316 #if SUPPORT_MOD_ORDER_DUMP
317
318 static void print_node(const CycleNode *node, FILE *file, int label)
319 {
320         modelclock_t idx;
321         if (node->is_promise()) {
322                 const Promise *promise = node->getPromise();
323                 idx = promise->get_action()->get_seq_number();
324                 fprintf(file, "P%u", idx);
325                 if (label) {
326                         int first = 1;
327                         fprintf(file, " [label=\"P%u, T", idx);
328                         for (unsigned int i = 0 ; i < model->get_num_threads(); i++)
329                                 if (promise->thread_is_available(int_to_id(i))) {
330                                         fprintf(file, "%s%u", first ? "": ",", i);
331                                         first = 0;
332                                 }
333                         fprintf(file, "\"]");
334                 }
335         } else {
336                 const ModelAction *act = node->getAction();
337                 idx = act->get_seq_number();
338                 fprintf(file, "N%u", idx);
339                 if (label)
340                         fprintf(file, " [label=\"N%u, T%u\"]", idx, act->get_tid());
341         }
342 }
343
344 void CycleGraph::dumpNodes(FILE *file) const
345 {
346         for (unsigned int i = 0; i < nodeList.size(); i++) {
347                 CycleNode *n = nodeList[i];
348                 print_node(n, file, 1);
349                 fprintf(file, ";\n");
350                 if (n->getRMW() != NULL) {
351                         print_node(n, file, 0);
352                         fprintf(file, " -> ");
353                         print_node(n->getRMW(), file, 0);
354                         fprintf(file, "[style=dotted];\n");
355                 }
356                 for (unsigned int j = 0; j < n->getNumEdges(); j++) {
357                         print_node(n, file, 0);
358                         fprintf(file, " -> ");
359                         print_node(n->getEdge(j), file, 0);
360                         fprintf(file, ";\n");
361                 }
362         }
363 }
364
365 void CycleGraph::dumpGraphToFile(const char *filename) const
366 {
367         char buffer[200];
368         sprintf(buffer, "%s.dot", filename);
369         FILE *file = fopen(buffer, "w");
370         fprintf(file, "digraph %s {\n", filename);
371         dumpNodes(file);
372         fprintf(file, "}\n");
373         fclose(file);
374 }
375 #endif
376
377 /**
378  * Checks whether one CycleNode can reach another.
379  * @param from The CycleNode from which to begin exploration
380  * @param to The CycleNode to reach
381  * @return True, @a from can reach @a to; otherwise, false
382  */
383 bool CycleGraph::checkReachable(const CycleNode *from, const CycleNode *to) const
384 {
385         std::vector< const CycleNode *, ModelAlloc<const CycleNode *> > queue;
386         discovered->reset();
387
388         queue.push_back(from);
389         discovered->put(from, from);
390         while (!queue.empty()) {
391                 const CycleNode *node = queue.back();
392                 queue.pop_back();
393                 if (node == to)
394                         return true;
395
396                 for (unsigned int i = 0; i < node->getNumEdges(); i++) {
397                         CycleNode *next = node->getEdge(i);
398                         if (!discovered->contains(next)) {
399                                 discovered->put(next, next);
400                                 queue.push_back(next);
401                         }
402                 }
403         }
404         return false;
405 }
406
407 /**
408  * Checks whether one ModelAction can reach another ModelAction/Promise
409  * @param from The ModelAction from which to begin exploration
410  * @param to The ModelAction or Promise to reach
411  * @return True, @a from can reach @a to; otherwise, false
412  */
413 template <typename T>
414 bool CycleGraph::checkReachable(const ModelAction *from, const T *to) const
415 {
416         CycleNode *fromnode = getNode_noCreate(from);
417         CycleNode *tonode = getNode_noCreate(to);
418
419         if (!fromnode || !tonode)
420                 return false;
421
422         return checkReachable(fromnode, tonode);
423 }
424 /* Instantiate two forms of CycleGraph::checkReachable */
425 template bool CycleGraph::checkReachable(const ModelAction *from,
426                 const ModelAction *to) const;
427 template bool CycleGraph::checkReachable(const ModelAction *from,
428                 const Promise *to) const;
429
430 /** @return True, if the promise has failed; false otherwise */
431 bool CycleGraph::checkPromise(const ModelAction *fromact, Promise *promise) const
432 {
433         std::vector< CycleNode *, ModelAlloc<CycleNode *> > queue;
434         discovered->reset();
435         CycleNode *from = actionToNode.get(fromact);
436
437         queue.push_back(from);
438         discovered->put(from, from);
439         while (!queue.empty()) {
440                 CycleNode *node = queue.back();
441                 queue.pop_back();
442
443                 if (!node->is_promise() &&
444                                 promise->eliminate_thread(node->getAction()->get_tid()))
445                         return true;
446
447                 for (unsigned int i = 0; i < node->getNumEdges(); i++) {
448                         CycleNode *next = node->getEdge(i);
449                         if (!discovered->contains(next)) {
450                                 discovered->put(next, next);
451                                 queue.push_back(next);
452                         }
453                 }
454         }
455         return false;
456 }
457
458 void CycleGraph::startChanges()
459 {
460         ASSERT(rollbackvector.empty());
461         ASSERT(rmwrollbackvector.empty());
462         ASSERT(oldCycles == hasCycles);
463 }
464
465 /** Commit changes to the cyclegraph. */
466 void CycleGraph::commitChanges()
467 {
468         rollbackvector.clear();
469         rmwrollbackvector.clear();
470         oldCycles = hasCycles;
471 }
472
473 /** Rollback changes to the previous commit. */
474 void CycleGraph::rollbackChanges()
475 {
476         for (unsigned int i = 0; i < rollbackvector.size(); i++)
477                 rollbackvector[i]->removeEdge();
478
479         for (unsigned int i = 0; i < rmwrollbackvector.size(); i++)
480                 rmwrollbackvector[i]->clearRMW();
481
482         hasCycles = oldCycles;
483         rollbackvector.clear();
484         rmwrollbackvector.clear();
485 }
486
487 /** @returns whether a CycleGraph contains cycles. */
488 bool CycleGraph::checkForCycles() const
489 {
490         return hasCycles;
491 }
492
493 /**
494  * @brief Constructor for a CycleNode
495  * @param act The ModelAction for this node
496  */
497 CycleNode::CycleNode(const ModelAction *act) :
498         action(act),
499         promise(NULL),
500         hasRMW(NULL)
501 {
502 }
503
504 /**
505  * @brief Constructor for a Promise CycleNode
506  * @param promise The Promise which was generated
507  */
508 CycleNode::CycleNode(const Promise *promise) :
509         action(NULL),
510         promise(promise),
511         hasRMW(NULL)
512 {
513 }
514
515 /**
516  * @param i The index of the edge to return
517  * @returns The a CycleNode edge indexed by i
518  */
519 CycleNode * CycleNode::getEdge(unsigned int i) const
520 {
521         return edges[i];
522 }
523
524 /** @returns The number of edges leaving this CycleNode */
525 unsigned int CycleNode::getNumEdges() const
526 {
527         return edges.size();
528 }
529
530 CycleNode * CycleNode::getBackEdge(unsigned int i) const
531 {
532         return back_edges[i];
533 }
534
535 unsigned int CycleNode::getNumBackEdges() const
536 {
537         return back_edges.size();
538 }
539
540 /**
541  * @brief Remove an element from a vector
542  * @param v The vector
543  * @param n The element to remove
544  * @return True if the element was found; false otherwise
545  */
546 template <typename T>
547 static bool vector_remove_node(std::vector<T, SnapshotAlloc<T> >& v, const T n)
548 {
549         for (unsigned int i = 0; i < v.size(); i++) {
550                 if (v[i] == n) {
551                         v.erase(v.begin() + i);
552                         return true;
553                 }
554         }
555         return false;
556 }
557
558 /**
559  * @brief Remove a (forward) edge from this CycleNode
560  * @return The CycleNode which was popped, if one exists; otherwise NULL
561  */
562 CycleNode * CycleNode::removeEdge()
563 {
564         if (edges.empty())
565                 return NULL;
566
567         CycleNode *ret = edges.back();
568         edges.pop_back();
569         vector_remove_node(ret->back_edges, this);
570         return ret;
571 }
572
573 /**
574  * @brief Remove a (back) edge from this CycleNode
575  * @return The CycleNode which was popped, if one exists; otherwise NULL
576  */
577 CycleNode * CycleNode::removeBackEdge()
578 {
579         if (back_edges.empty())
580                 return NULL;
581
582         CycleNode *ret = back_edges.back();
583         back_edges.pop_back();
584         vector_remove_node(ret->edges, this);
585         return ret;
586 }
587
588 /**
589  * Adds an edge from this CycleNode to another CycleNode.
590  * @param node The node to which we add a directed edge
591  * @return True if this edge is a new edge; false otherwise
592  */
593 bool CycleNode::addEdge(CycleNode *node)
594 {
595         for (unsigned int i = 0; i < edges.size(); i++)
596                 if (edges[i] == node)
597                         return false;
598         edges.push_back(node);
599         node->back_edges.push_back(this);
600         return true;
601 }
602
603 /** @returns the RMW CycleNode that reads from the current CycleNode */
604 CycleNode * CycleNode::getRMW() const
605 {
606         return hasRMW;
607 }
608
609 /**
610  * Set a RMW action node that reads from the current CycleNode.
611  * @param node The RMW that reads from the current node
612  * @return True, if this node already was read by another RMW; false otherwise
613  * @see CycleGraph::addRMWEdge
614  */
615 bool CycleNode::setRMW(CycleNode *node)
616 {
617         if (hasRMW != NULL)
618                 return true;
619         hasRMW = node;
620         return false;
621 }
622
623 /**
624  * Convert a Promise CycleNode into a concrete-valued CycleNode. Should only be
625  * used when there's no existing ModelAction CycleNode for this write.
626  *
627  * @param writer The ModelAction which wrote the future value represented by
628  * this CycleNode
629  */
630 void CycleNode::resolvePromise(const ModelAction *writer)
631 {
632         ASSERT(is_promise());
633         ASSERT(promise->is_compatible(writer));
634         action = writer;
635         promise = NULL;
636         ASSERT(!is_promise());
637 }