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