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