1 //===--Graph.cpp--- implements Graph class ---------------- ------*- C++ -*--=//
3 // This implements Graph for helping in trace generation
4 // This graph gets used by "ProfilePaths" class
6 //===----------------------------------------------------------------------===//
9 #include "llvm/iTerminators.h"
10 #include "Support/Debug.h"
17 const graphListElement *findNodeInList(const Graph::nodeList &NL,
19 for(Graph::nodeList::const_iterator NI = NL.begin(), NE=NL.end(); NI != NE;
21 if (*NI->element== *N)
26 graphListElement *findNodeInList(Graph::nodeList &NL, Node *N) {
27 for(Graph::nodeList::iterator NI = NL.begin(), NE=NL.end(); NI != NE; ++NI)
28 if (*NI->element== *N)
33 //graph constructor with root and exit specified
34 Graph::Graph(std::vector<Node*> n, std::vector<Edge> e,
38 for(vector<Node* >::iterator x=n.begin(), en=n.end(); x!=en; ++x)
39 //nodes[*x] = list<graphListElement>();
40 nodes[*x] = vector<graphListElement>();
42 for(vector<Edge >::iterator x=e.begin(), en=e.end(); x!=en; ++x){
45 //nodes[ee.getFirst()].push_front(graphListElement(ee.getSecond(),w, ee.getRandId()));
46 nodes[ee.getFirst()].push_back(graphListElement(ee.getSecond(),w, ee.getRandId()));
51 //sorting edgelist, called by backEdgeVist ONLY!!!
52 Graph::nodeList &Graph::sortNodeList(Node *par, nodeList &nl, vector<Edge> &be){
53 assert(par && "null node pointer");
54 BasicBlock *bbPar = par->getElement();
56 if(nl.size()<=1) return nl;
57 if(getExit() == par) return nl;
59 for(nodeList::iterator NLI = nl.begin(), NLE = nl.end()-1; NLI != NLE; ++NLI){
60 nodeList::iterator min = NLI;
61 for(nodeList::iterator LI = NLI+1, LE = nl.end(); LI!=LE; ++LI){
62 //if LI < min, min = LI
63 if(min->element->getElement() == LI->element->getElement() &&
64 min->element == getExit()){
66 //same successors: so might be exit???
67 //if it is exit, then see which is backedge
68 //check if LI is a left back edge!
70 TerminatorInst *tti = par->getElement()->getTerminator();
71 BranchInst *ti = cast<BranchInst>(tti);
73 assert(ti && "not a branch");
74 assert(ti->getNumSuccessors()==2 && "less successors!");
76 BasicBlock *tB = ti->getSuccessor(0);
77 BasicBlock *fB = ti->getSuccessor(1);
78 //so one of LI or min must be back edge!
79 //Algo: if succ(0)!=LI (and so !=min) then succ(0) is backedge
80 //and then see which of min or LI is backedge
81 //THEN if LI is in be, then min=LI
82 if(LI->element->getElement() != tB){//so backedge must be made min!
83 for(vector<Edge>::iterator VBEI = be.begin(), VBEE = be.end();
84 VBEI != VBEE; ++VBEI){
85 if(VBEI->getRandId() == LI->randId){
89 else if(VBEI->getRandId() == min->randId)
93 else{// if(LI->element->getElement() != fB)
94 for(vector<Edge>::iterator VBEI = be.begin(), VBEE = be.end();
95 VBEI != VBEE; ++VBEI){
96 if(VBEI->getRandId() == min->randId){
100 else if(VBEI->getRandId() == LI->randId)
106 else if (min->element->getElement() != LI->element->getElement()){
107 TerminatorInst *tti = par->getElement()->getTerminator();
108 BranchInst *ti = cast<BranchInst>(tti);
109 assert(ti && "not a branch");
111 if(ti->getNumSuccessors()<=1) continue;
113 assert(ti->getNumSuccessors()==2 && "less successors!");
115 BasicBlock *tB = ti->getSuccessor(0);
116 BasicBlock *fB = ti->getSuccessor(1);
118 if(tB == LI->element->getElement() || fB == min->element->getElement())
123 graphListElement tmpElmnt = *min;
130 //check whether graph has an edge
131 //having an edge simply means that there is an edge in the graph
132 //which has same endpoints as the given edge
133 bool Graph::hasEdge(Edge ed){
137 nodeList &nli= nodes[ed.getFirst()]; //getNodeList(ed.getFirst());
138 Node *nd2=ed.getSecond();
140 return (findNodeInList(nli,nd2)!=NULL);
145 //check whether graph has an edge, with a given wt
146 //having an edge simply means that there is an edge in the graph
147 //which has same endpoints as the given edge
148 //This function checks, moreover, that the wt of edge matches too
149 bool Graph::hasEdgeAndWt(Edge ed){
153 Node *nd2=ed.getSecond();
154 nodeList &nli = nodes[ed.getFirst()];//getNodeList(ed.getFirst());
156 for(nodeList::iterator NI=nli.begin(), NE=nli.end(); NI!=NE; ++NI)
157 if(*NI->element == *nd2 && ed.getWeight()==NI->weight)
164 void Graph::addNode(Node *nd){
165 vector<Node *> lt=getAllNodes();
167 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE;++LI){
172 nodes[nd] =vector<graphListElement>(); //list<graphListElement>();
176 //this adds an edge ONLY when
177 //the edge to be added does not already exist
178 //we "equate" two edges here only with their
180 void Graph::addEdge(Edge ed, int w){
181 nodeList &ndList = nodes[ed.getFirst()];
182 Node *nd2=ed.getSecond();
184 if(findNodeInList(nodes[ed.getFirst()], nd2))
187 //ndList.push_front(graphListElement(nd2,w, ed.getRandId()));
188 ndList.push_back(graphListElement(nd2,w, ed.getRandId()));//chng
189 //sortNodeList(ed.getFirst(), ndList);
191 //sort(ndList.begin(), ndList.end(), NodeListSort());
194 //add an edge EVEN IF such an edge already exists
195 //this may make a multi-graph
196 //which does happen when we add dummy edges
197 //to the graph, for compensating for back-edges
198 void Graph::addEdgeForce(Edge ed){
199 //nodes[ed.getFirst()].push_front(graphListElement(ed.getSecond(),
200 //ed.getWeight(), ed.getRandId()));
201 nodes[ed.getFirst()].push_back
202 (graphListElement(ed.getSecond(), ed.getWeight(), ed.getRandId()));
204 //sortNodeList(ed.getFirst(), nodes[ed.getFirst()]);
205 //sort(nodes[ed.getFirst()].begin(), nodes[ed.getFirst()].end(), NodeListSort());
209 //Note that it removes just one edge,
210 //the first edge that is encountered
211 void Graph::removeEdge(Edge ed){
212 nodeList &ndList = nodes[ed.getFirst()];
213 Node &nd2 = *ed.getSecond();
215 for(nodeList::iterator NI=ndList.begin(), NE=ndList.end(); NI!=NE ;++NI) {
216 if(*NI->element == nd2) {
223 //remove an edge with a given wt
224 //Note that it removes just one edge,
225 //the first edge that is encountered
226 void Graph::removeEdgeWithWt(Edge ed){
227 nodeList &ndList = nodes[ed.getFirst()];
228 Node &nd2 = *ed.getSecond();
230 for(nodeList::iterator NI=ndList.begin(), NE=ndList.end(); NI!=NE ;++NI) {
231 if(*NI->element == nd2 && NI->weight==ed.getWeight()) {
238 //set the weight of an edge
239 void Graph::setWeight(Edge ed){
240 graphListElement *El = findNodeInList(nodes[ed.getFirst()], ed.getSecond());
242 El->weight=ed.getWeight();
247 //get the list of successor nodes
248 vector<Node *> Graph::getSuccNodes(Node *nd){
249 nodeMapTy::const_iterator nli = nodes.find(nd);
250 assert(nli != nodes.end() && "Node must be in nodes map");
251 const nodeList &nl = getNodeList(nd);//getSortedNodeList(nd);
254 for(nodeList::const_iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI)
255 lt.push_back(NI->element);
260 //get the number of outgoing edges
261 int Graph::getNumberOfOutgoingEdges(Node *nd) const {
262 nodeMapTy::const_iterator nli = nodes.find(nd);
263 assert(nli != nodes.end() && "Node must be in nodes map");
264 const nodeList &nl = nli->second;
267 for(nodeList::const_iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI)
273 //get the list of predecessor nodes
274 vector<Node *> Graph::getPredNodes(Node *nd){
276 for(nodeMapTy::const_iterator EI=nodes.begin(), EE=nodes.end(); EI!=EE ;++EI){
277 Node *lnode=EI->first;
278 const nodeList &nl = getNodeList(lnode);
280 const graphListElement *N = findNodeInList(nl, nd);
281 if (N) lt.push_back(lnode);
286 //get the number of predecessor nodes
287 int Graph::getNumberOfIncomingEdges(Node *nd){
289 for(nodeMapTy::const_iterator EI=nodes.begin(), EE=nodes.end(); EI!=EE ;++EI){
290 Node *lnode=EI->first;
291 const nodeList &nl = getNodeList(lnode);
292 for(Graph::nodeList::const_iterator NI = nl.begin(), NE=nl.end(); NI != NE;
294 if (*NI->element== *nd)
300 //get the list of all the vertices in graph
301 vector<Node *> Graph::getAllNodes() const{
303 for(nodeMapTy::const_iterator x=nodes.begin(), en=nodes.end(); x != en; ++x)
304 lt.push_back(x->first);
309 //get the list of all the vertices in graph
310 vector<Node *> Graph::getAllNodes(){
312 for(nodeMapTy::const_iterator x=nodes.begin(), en=nodes.end(); x != en; ++x)
313 lt.push_back(x->first);
318 //class to compare two nodes in graph
319 //based on their wt: this is used in
320 //finding the maximal spanning tree
321 struct compare_nodes {
322 bool operator()(Node *n1, Node *n2){
323 return n1->getWeight() < n2->getWeight();
328 static void printNode(Node *nd){
329 cerr<<"Node:"<<nd->getElement()->getName()<<"\n";
332 //Get the Maximal spanning tree (also a graph)
334 Graph* Graph::getMaxSpanningTree(){
335 //assume connected graph
337 Graph *st=new Graph();//max spanning tree, undirected edges
338 int inf=9999999;//largest key
339 vector<Node *> lt = getAllNodes();
341 //initially put all vertices in vector vt
343 //wt(others)=infinity
346 //pull out u: a vertex frm vt of min wt
347 //for all vertices w in vt,
348 //if wt(w) greater than
349 //the wt(u->w), then assign
350 //wt(w) to be wt(u->w).
352 //make parent(u)=w in the spanning tree
353 //keep pulling out vertices from vt till it is empty
357 map<Node*, Node* > parent;
358 map<Node*, int > ed_weight;
360 //initialize: wt(root)=0, wt(others)=infinity
361 //parent(root)=NULL, parent(others) not defined (but not null)
362 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
364 if(*thisNode == *getRoot()){
365 thisNode->setWeight(0);
366 parent[thisNode]=NULL;
367 ed_weight[thisNode]=0;
370 thisNode->setWeight(inf);
372 st->addNode(thisNode);//add all nodes to spanning tree
373 //we later need to assign edges in the tree
374 vt.push_back(thisNode); //pushed all nodes in vt
377 //keep pulling out vertex of min wt from vt
379 Node *u=*(min_element(vt.begin(), vt.end(), compare_nodes()));
380 DEBUG(cerr<<"popped wt"<<(u)->getWeight()<<"\n";
383 if(parent[u]!=NULL){ //so not root
384 Edge edge(parent[u],u, ed_weight[u]); //assign edge in spanning tree
385 st->addEdge(edge,ed_weight[u]);
387 DEBUG(cerr<<"added:\n";
394 for(vector<Node *>::iterator VI=vt.begin(), VE=vt.end(); VI!=VE; ++VI){
401 //assign wt(v) to all adjacent vertices v of u
403 Graph::nodeList &nl = getNodeList(u);
404 for(nodeList::iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI){
406 int weight=-NI->weight;
407 //check if v is in vt
409 for(vector<Node *>::iterator VI=vt.begin(), VE=vt.end(); VI!=VE; ++VI){
415 DEBUG(cerr<<"wt:v->wt"<<weight<<":"<<v->getWeight()<<"\n";
416 printNode(v);cerr<<"node wt:"<<(*v).weight<<"\n");
418 //so if v in in vt, change wt(v) to wt(u->v)
419 //only if wt(u->v)<wt(v)
420 if(contains && weight<v->getWeight()){
423 v->setWeight(weight);
425 DEBUG(cerr<<v->getWeight()<<":Set weight------\n";
427 printEdge(Edge(u,v,weight)));
434 //print the graph (for debugging)
435 void Graph::printGraph(){
436 vector<Node *> lt=getAllNodes();
437 cerr<<"Graph---------------------\n";
438 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
439 cerr<<((*LI)->getElement())->getName()<<"->";
440 Graph::nodeList &nl = getNodeList(*LI);
441 for(Graph::nodeList::iterator NI=nl.begin(), NE=nl.end(); NI!=NE; ++NI){
442 cerr<<":"<<"("<<(NI->element->getElement())
443 ->getName()<<":"<<NI->element->getWeight()<<","<<NI->weight<<")";
450 //get a list of nodes in the graph
451 //in r-topological sorted order
452 //note that we assumed graph to be connected
453 vector<Node *> Graph::reverseTopologicalSort(){
454 vector <Node *> toReturn;
455 vector<Node *> lt=getAllNodes();
456 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
457 if((*LI)->getWeight()!=GREY && (*LI)->getWeight()!=BLACK)
458 DFS_Visit(*LI, toReturn);
464 //a private method for doing DFS traversal of graph
465 //this is used in determining the reverse topological sort
467 void Graph::DFS_Visit(Node *nd, vector<Node *> &toReturn){
469 vector<Node *> lt=getSuccNodes(nd);
470 for(vector<Node *>::iterator LI=lt.begin(), LE=lt.end(); LI!=LE; ++LI){
471 if((*LI)->getWeight()!=GREY && (*LI)->getWeight()!=BLACK)
472 DFS_Visit(*LI, toReturn);
474 toReturn.push_back(nd);
477 //Ordinarily, the graph is directional
478 //this converts the graph into an
479 //undirectional graph
480 //This is done by adding an edge
481 //v->u for all existing edges u->v
482 void Graph::makeUnDirectional(){
483 vector<Node* > allNodes=getAllNodes();
484 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
486 nodeList &nl = getNodeList(*NI);
487 for(nodeList::iterator NLI=nl.begin(), NLE=nl.end(); NLI!=NLE; ++NLI){
488 Edge ed(NLI->element, *NI, NLI->weight);
489 if(!hasEdgeAndWt(ed)){
490 DEBUG(cerr<<"######doesn't hv\n";
498 //reverse the sign of weights on edges
499 //this way, max-spanning tree could be obtained
500 //using min-spanning tree, and vice versa
501 void Graph::reverseWts(){
502 vector<Node *> allNodes=getAllNodes();
503 for(vector<Node *>::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
505 nodeList &node_list = getNodeList(*NI);
506 for(nodeList::iterator NLI=nodes[*NI].begin(), NLE=nodes[*NI].end();
508 NLI->weight=-NLI->weight;
513 //getting the backedges in a graph
514 //Its a variation of DFS to get the backedges in the graph
515 //We get back edges by associating a time
516 //and a color with each vertex.
517 //The time of a vertex is the time when it was first visited
518 //The color of a vertex is initially WHITE,
519 //Changes to GREY when it is first visited,
520 //and changes to BLACK when ALL its neighbors
522 //So we have a back edge when we meet a successor of
523 //a node with smaller time, and GREY color
524 void Graph::getBackEdges(vector<Edge > &be, map<Node *, int> &d){
525 map<Node *, Color > color;
528 getBackEdgesVisit(getRoot(), be, color, d, time);
531 //helper function to get back edges: it is called by
532 //the "getBackEdges" function above
533 void Graph::getBackEdgesVisit(Node *u, vector<Edge > &be,
534 map<Node *, Color > &color,
535 map<Node *, int > &d, int &time) {
540 vector<graphListElement> &succ_list = getNodeList(u);
542 for(vector<graphListElement>::iterator vl=succ_list.begin(),
543 ve=succ_list.end(); vl!=ve; ++vl){
545 if(color[v]!=GREY && color[v]!=BLACK){
546 getBackEdgesVisit(v, be, color, d, time);
549 //now checking for d and f vals
551 //so v is ancestor of u if time of u > time of v
553 Edge *ed=new Edge(u, v,vl->weight, vl->randId);
554 if (!(*u == *getExit() && *v == *getRoot()))
555 be.push_back(*ed); // choose the forward edges
559 color[u]=BLACK;//done with visiting the node and its neighbors