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