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