Implementation of path profiling.
[oota-llvm.git] / lib / Transforms / Instrumentation / PathProfiling.cpp
1 //===- PathProfiling.cpp - Inserts counters for path profiling ------------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass instruments functions for Ball-Larus path profiling.  Ball-Larus
11 // profiling converts the CFG into a DAG by replacing backedges with edges
12 // from entry to the start block and from the end block to exit.  The paths
13 // along the new DAG are enumrated, i.e. each path is given a path number.
14 // Edges are instrumented to increment the path number register, such that the
15 // path number register will equal the path number of the path taken at the
16 // exit.
17 //
18 // This file defines classes for building a CFG for use with different stages
19 // in the Ball-Larus path profiling instrumentation [Ball96].  The
20 // requirements are formatting the llvm CFG into the Ball-Larus DAG, path
21 // numbering, finding a spanning tree, moving increments from the spanning
22 // tree to chords.
23 //
24 // Terms:
25 // DAG            - Directed Acyclic Graph.
26 // Ball-Larus DAG - A CFG with an entry node, an exit node, and backedges
27 //                  removed in the following manner.  For every backedge
28 //                  v->w, insert edge ENTRY->w and edge v->EXIT.
29 // Path Number    - The number corresponding to a specific path through a
30 //                  Ball-Larus DAG.
31 // Spanning Tree  - A subgraph, S, is a spanning tree if S covers all
32 //                  vertices and is a tree.
33 // Chord          - An edge not in the spanning tree.
34 //
35 // [Ball96]
36 //  T. Ball and J. R. Larus. "Efficient Path Profiling."
37 //  International Symposium on Microarchitecture, pages 46-57, 1996.
38 //  http://portal.acm.org/citation.cfm?id=243857
39 //
40 // [Ball94]
41 //  Thomas Ball.  "Efficiently Counting Program Events with Support for
42 //  On-line queries."
43 //  ACM Transactions on Programmmg Languages and Systems, Vol 16, No 5,
44 //  September 1994, Pages 1399-1410.
45 //===----------------------------------------------------------------------===//
46 #define DEBUG_TYPE "insert-path-profiling"
47
48 #include "llvm/DerivedTypes.h"
49 #include "ProfilingUtils.h"
50 #include "llvm/Analysis/PathNumbering.h"
51 #include "llvm/Constants.h"
52 #include "llvm/DerivedTypes.h"
53 #include "llvm/InstrTypes.h"
54 #include "llvm/Instructions.h"
55 #include "llvm/LLVMContext.h"
56 #include "llvm/Module.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/CFG.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/TypeBuilder.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include <map>
67 #include <vector>
68
69 #define HASH_THRESHHOLD 100000
70
71 using namespace llvm;
72
73 namespace {
74 class BLInstrumentationNode;
75 class BLInstrumentationEdge;
76 class BLInstrumentationDag;
77
78 // ---------------------------------------------------------------------------
79 // BLInstrumentationNode extends BallLarusNode with member used by the
80 // instrumentation algortihms.
81 // ---------------------------------------------------------------------------
82 class BLInstrumentationNode : public BallLarusNode {
83 public:
84   // Creates a new BLInstrumentationNode from a BasicBlock.
85   BLInstrumentationNode(BasicBlock* BB);
86
87   // Get/sets the Value corresponding to the pathNumber register,
88   // constant or phinode.  Used by the instrumentation code to remember
89   // path number Values.
90   Value* getStartingPathNumber();
91   void setStartingPathNumber(Value* pathNumber);
92
93   Value* getEndingPathNumber();
94   void setEndingPathNumber(Value* pathNumber);
95
96   // Get/set the PHINode Instruction for this node.
97   PHINode* getPathPHI();
98   void setPathPHI(PHINode* pathPHI);
99
100 private:
101
102   Value* _startingPathNumber; // The Value for the current pathNumber.
103   Value* _endingPathNumber; // The Value for the current pathNumber.
104   PHINode* _pathPHI; // The PHINode for current pathNumber.
105 };
106
107 // --------------------------------------------------------------------------
108 // BLInstrumentationEdge extends BallLarusEdge with data about the
109 // instrumentation that will end up on each edge.
110 // --------------------------------------------------------------------------
111 class BLInstrumentationEdge : public BallLarusEdge {
112 public:
113   BLInstrumentationEdge(BLInstrumentationNode* source,
114                         BLInstrumentationNode* target);
115
116   // Sets the target node of this edge.  Required to split edges.
117   void setTarget(BallLarusNode* node);
118
119   // Get/set whether edge is in the spanning tree.
120   bool isInSpanningTree() const;
121   void setIsInSpanningTree(bool isInSpanningTree);
122
123   // Get/ set whether this edge will be instrumented with a path number
124   // initialization.
125   bool isInitialization() const;
126   void setIsInitialization(bool isInitialization);
127
128   // Get/set whether this edge will be instrumented with a path counter
129   // increment.  Notice this is incrementing the path counter
130   // corresponding to the path number register.  The path number
131   // increment is determined by getIncrement().
132   bool isCounterIncrement() const;
133   void setIsCounterIncrement(bool isCounterIncrement);
134
135   // Get/set the path number increment that this edge will be instrumented
136   // with.  This is distinct from the path counter increment and the
137   // weight.  The counter increment counts the number of executions of
138   // some path, whereas the path number keeps track of which path number
139   // the program is on.
140   long getIncrement() const;
141   void setIncrement(long increment);
142
143   // Get/set whether the edge has been instrumented.
144   bool hasInstrumentation();
145   void setHasInstrumentation(bool hasInstrumentation);
146
147   // Returns the successor number of this edge in the source.
148   unsigned getSuccessorNumber();
149
150 private:
151   // The increment that the code will be instrumented with.
152   long long _increment;
153
154   // Whether this edge is in the spanning tree.
155   bool _isInSpanningTree;
156
157   // Whether this edge is an initialiation of the path number.
158   bool _isInitialization;
159
160   // Whether this edge is a path counter increment.
161   bool _isCounterIncrement;
162
163   // Whether this edge has been instrumented.
164   bool _hasInstrumentation;
165 };
166
167 // ---------------------------------------------------------------------------
168 // BLInstrumentationDag extends BallLarusDag with algorithms that
169 // determine where instrumentation should be placed.
170 // ---------------------------------------------------------------------------
171 class BLInstrumentationDag : public BallLarusDag {
172 public:
173   BLInstrumentationDag(Function &F);
174
175   // Returns the Exit->Root edge. This edge is required for creating
176   // directed cycles in the algorithm for moving instrumentation off of
177   // the spanning tree
178   BallLarusEdge* getExitRootEdge();
179
180   // Returns an array of phony edges which mark those nodes
181   // with function calls
182   BLEdgeVector getCallPhonyEdges();
183
184   // Gets/sets the path counter array
185   GlobalVariable* getCounterArray();
186   void setCounterArray(GlobalVariable* c);
187
188   // Calculates the increments for the chords, thereby removing
189   // instrumentation from the spanning tree edges. Implementation is based
190   // on the algorithm in Figure 4 of [Ball94]
191   void calculateChordIncrements();
192
193   // Updates the state when an edge has been split
194   void splitUpdate(BLInstrumentationEdge* formerEdge, BasicBlock* newBlock);
195
196   // Calculates a spanning tree of the DAG ignoring cycles.  Whichever
197   // edges are in the spanning tree will not be instrumented, but this
198   // implementation does not try to minimize the instrumentation overhead
199   // by trying to find hot edges.
200   void calculateSpanningTree();
201
202   // Pushes initialization further down in order to group the first
203   // increment and initialization.
204   void pushInitialization();
205
206   // Pushes the path counter increments up in order to group the last path
207   // number increment.
208   void pushCounters();
209
210   // Removes phony edges from the successor list of the source, and the
211   // predecessor list of the target.
212   void unlinkPhony();
213
214   // Generate dot graph for the function
215   void generateDotGraph();
216
217 protected:
218   // BLInstrumentationDag creates BLInstrumentationNode objects in this
219   // method overriding the creation of BallLarusNode objects.
220   //
221   // Allows subclasses to determine which type of Node is created.
222   // Override this method to produce subclasses of BallLarusNode if
223   // necessary.
224   virtual BallLarusNode* createNode(BasicBlock* BB);
225
226   // BLInstrumentationDag create BLInstrumentationEdges.
227   //
228   // Allows subclasses to determine which type of Edge is created.
229   // Override this method to produce subclasses of BallLarusEdge if
230   // necessary.  Parameters source and target will have been created by
231   // createNode and can be cast to the subclass of BallLarusNode*
232   // returned by createNode.
233   virtual BallLarusEdge* createEdge(
234     BallLarusNode* source, BallLarusNode* target, unsigned edgeNumber);
235
236 private:
237   BLEdgeVector _treeEdges; // All edges in the spanning tree.
238   BLEdgeVector _chordEdges; // All edges not in the spanning tree.
239   GlobalVariable* _counterArray; // Array to store path counters
240
241   // Removes the edge from the appropriate predecessor and successor lists.
242   void unlinkEdge(BallLarusEdge* edge);
243
244   // Makes an edge part of the spanning tree.
245   void makeEdgeSpanning(BLInstrumentationEdge* edge);
246
247   // Pushes initialization and calls itself recursively.
248   void pushInitializationFromEdge(BLInstrumentationEdge* edge);
249
250   // Pushes path counter increments up recursively.
251   void pushCountersFromEdge(BLInstrumentationEdge* edge);
252
253   // Depth first algorithm for determining the chord increments.f
254   void calculateChordIncrementsDfs(
255     long weight, BallLarusNode* v, BallLarusEdge* e);
256
257   // Determines the relative direction of two edges.
258   int calculateChordIncrementsDir(BallLarusEdge* e, BallLarusEdge* f);
259 };
260
261 // ---------------------------------------------------------------------------
262 // PathProfiler is a module pass which intruments path profiling instructions
263 // ---------------------------------------------------------------------------
264 class PathProfiler : public ModulePass {
265 private:
266   // Current context for multi threading support.
267   LLVMContext* Context;
268
269   // Which function are we currently instrumenting
270   unsigned currentFunctionNumber;
271
272   // The function prototype in the profiling runtime for incrementing a
273   // single path counter in a hash table.
274   Constant* llvmIncrementHashFunction;
275   Constant* llvmDecrementHashFunction;
276
277   // Instruments each function with path profiling.  'main' is instrumented
278   // with code to save the profile to disk.
279   bool runOnModule(Module &M);
280
281   // Analyzes the function for Ball-Larus path profiling, and inserts code.
282   void runOnFunction(std::vector<Constant*> &ftInit, Function &F, Module &M);
283
284   // Creates an increment constant representing incr.
285   ConstantInt* createIncrementConstant(long incr, int bitsize);
286
287   // Creates an increment constant representing the value in
288   // edge->getIncrement().
289   ConstantInt* createIncrementConstant(BLInstrumentationEdge* edge);
290
291   // Finds the insertion point after pathNumber in block.  PathNumber may
292   // be NULL.
293   BasicBlock::iterator getInsertionPoint(
294     BasicBlock* block, Value* pathNumber);
295
296   // Inserts source's pathNumber Value* into target.  Target may or may not
297   // have multiple predecessors, and may or may not have its phiNode
298   // initalized.
299   void pushValueIntoNode(
300     BLInstrumentationNode* source, BLInstrumentationNode* target);
301
302   // Inserts source's pathNumber Value* into the appropriate slot of
303   // target's phiNode.
304   void pushValueIntoPHI(
305     BLInstrumentationNode* target, BLInstrumentationNode* source);
306
307   // The Value* in node, oldVal,  is updated with a Value* correspodning to
308   // oldVal + addition.
309   void insertNumberIncrement(BLInstrumentationNode* node, Value* addition,
310                              bool atBeginning);
311
312   // Creates a counter increment in the given node.  The Value* in node is
313   // taken as the index into a hash table.
314   void insertCounterIncrement(
315     Value* incValue,
316     BasicBlock::iterator insertPoint,
317     BLInstrumentationDag* dag,
318     bool increment = true);
319
320   // A PHINode is created in the node, and its values initialized to -1U.
321   void preparePHI(BLInstrumentationNode* node);
322
323   // Inserts instrumentation for the given edge
324   //
325   // Pre: The edge's source node has pathNumber set if edge is non zero
326   // path number increment.
327   //
328   // Post: Edge's target node has a pathNumber set to the path number Value
329   // corresponding to the value of the path register after edge's
330   // execution.
331   void insertInstrumentationStartingAt(
332     BLInstrumentationEdge* edge,
333     BLInstrumentationDag* dag);
334
335   // If this edge is a critical edge, then inserts a node at this edge.
336   // This edge becomes the first edge, and a new BallLarusEdge is created.
337   bool splitCritical(BLInstrumentationEdge* edge, BLInstrumentationDag* dag);
338
339   // Inserts instrumentation according to the marked edges in dag.  Phony
340   // edges must be unlinked from the DAG, but accessible from the
341   // backedges.  Dag must have initializations, path number increments, and
342   // counter increments present.
343   //
344   // Counter storage is created here.
345   void insertInstrumentation( BLInstrumentationDag& dag, Module &M);
346
347 public:
348   static char ID; // Pass identification, replacement for typeid
349   PathProfiler() : ModulePass(ID) {
350     initializePathProfilerPass(*PassRegistry::getPassRegistry());
351   }
352
353   virtual const char *getPassName() const {
354     return "Path Profiler";
355   }
356 };
357 } // end anonymous namespace
358
359 // Should we print the dot-graphs
360 static cl::opt<bool> DotPathDag("path-profile-pathdag", cl::Hidden,
361         cl::desc("Output the path profiling DAG for each function."));
362
363 // Register the path profiler as a pass
364 char PathProfiler::ID = 0;
365 INITIALIZE_PASS(PathProfiler, "insert-path-profiling",
366                 "Insert instrumentation for Ball-Larus path profiling",
367                 false, false)
368
369 ModulePass *llvm::createPathProfilerPass() { return new PathProfiler(); }
370
371 namespace llvm {
372   class PathProfilingFunctionTable {};
373
374   // Type for global array storing references to hashes or arrays
375   template<bool xcompile> class TypeBuilder<PathProfilingFunctionTable,
376                                             xcompile> {
377   public:
378     static const StructType *get(LLVMContext& C) {
379       return( StructType::get(
380                 C, TypeBuilder<types::i<32>, xcompile>::get(C), // type
381                 TypeBuilder<types::i<32>, xcompile>::get(C), // array size
382                 TypeBuilder<types::i<8>*, xcompile>::get(C), // array/hash ptr
383                 NULL));
384     }
385   };
386
387   typedef TypeBuilder<PathProfilingFunctionTable, true>
388   ftEntryTypeBuilder;
389
390   // BallLarusEdge << operator overloading
391   raw_ostream& operator<<(raw_ostream& os,
392                           const BLInstrumentationEdge& edge) {
393     os << "[" << edge.getSource()->getName() << " -> "
394        << edge.getTarget()->getName() << "] init: "
395        << (edge.isInitialization() ? "yes" : "no")
396        << " incr:" << edge.getIncrement() << " cinc: "
397        << (edge.isCounterIncrement() ? "yes" : "no");
398     return(os);
399   }
400 }
401
402 // Creates a new BLInstrumentationNode from a BasicBlock.
403 BLInstrumentationNode::BLInstrumentationNode(BasicBlock* BB) :
404   BallLarusNode(BB),
405   _startingPathNumber(NULL), _endingPathNumber(NULL), _pathPHI(NULL) {}
406
407 // Constructor for BLInstrumentationEdge.
408 BLInstrumentationEdge::BLInstrumentationEdge(BLInstrumentationNode* source,
409                                              BLInstrumentationNode* target)
410   : BallLarusEdge(source, target, 0),
411     _increment(0), _isInSpanningTree(false), _isInitialization(false),
412     _isCounterIncrement(false), _hasInstrumentation(false) {}
413
414 // Sets the target node of this edge.  Required to split edges.
415 void BLInstrumentationEdge::setTarget(BallLarusNode* node) {
416   _target = node;
417 }
418
419 // Returns whether this edge is in the spanning tree.
420 bool BLInstrumentationEdge::isInSpanningTree() const {
421   return(_isInSpanningTree);
422 }
423
424 // Sets whether this edge is in the spanning tree.
425 void BLInstrumentationEdge::setIsInSpanningTree(bool isInSpanningTree) {
426   _isInSpanningTree = isInSpanningTree;
427 }
428
429 // Returns whether this edge will be instrumented with a path number
430 // initialization.
431 bool BLInstrumentationEdge::isInitialization() const {
432   return(_isInitialization);
433 }
434
435 // Sets whether this edge will be instrumented with a path number
436 // initialization.
437 void BLInstrumentationEdge::setIsInitialization(bool isInitialization) {
438   _isInitialization = isInitialization;
439 }
440
441 // Returns whether this edge will be instrumented with a path counter
442 // increment.  Notice this is incrementing the path counter
443 // corresponding to the path number register.  The path number
444 // increment is determined by getIncrement().
445 bool BLInstrumentationEdge::isCounterIncrement() const {
446   return(_isCounterIncrement);
447 }
448
449 // Sets whether this edge will be instrumented with a path counter
450 // increment.
451 void BLInstrumentationEdge::setIsCounterIncrement(bool isCounterIncrement) {
452   _isCounterIncrement = isCounterIncrement;
453 }
454
455 // Gets the path number increment that this edge will be instrumented
456 // with.  This is distinct from the path counter increment and the
457 // weight.  The counter increment is counts the number of executions of
458 // some path, whereas the path number keeps track of which path number
459 // the program is on.
460 long BLInstrumentationEdge::getIncrement() const {
461   return(_increment);
462 }
463
464 // Set whether this edge will be instrumented with a path number
465 // increment.
466 void BLInstrumentationEdge::setIncrement(long increment) {
467   _increment = increment;
468 }
469
470 // True iff the edge has already been instrumented.
471 bool BLInstrumentationEdge::hasInstrumentation() {
472   return(_hasInstrumentation);
473 }
474
475 // Set whether this edge has been instrumented.
476 void BLInstrumentationEdge::setHasInstrumentation(bool hasInstrumentation) {
477   _hasInstrumentation = hasInstrumentation;
478 }
479
480 // Returns the successor number of this edge in the source.
481 unsigned BLInstrumentationEdge::getSuccessorNumber() {
482   BallLarusNode* sourceNode = getSource();
483   BallLarusNode* targetNode = getTarget();
484   BasicBlock* source = sourceNode->getBlock();
485   BasicBlock* target = targetNode->getBlock();
486
487   if(source == NULL || target == NULL)
488     return(0);
489
490   TerminatorInst* terminator = source->getTerminator();
491
492         unsigned i;
493   for(i=0; i < terminator->getNumSuccessors(); i++) {
494     if(terminator->getSuccessor(i) == target)
495       break;
496   }
497
498   return(i);
499 }
500
501 // BLInstrumentationDag constructor initializes a DAG for the given Function.
502 BLInstrumentationDag::BLInstrumentationDag(Function &F) : BallLarusDag(F),
503                                                           _counterArray(0) {
504 }
505
506 // Returns the Exit->Root edge. This edge is required for creating
507 // directed cycles in the algorithm for moving instrumentation off of
508 // the spanning tree
509 BallLarusEdge* BLInstrumentationDag::getExitRootEdge() {
510   BLEdgeIterator erEdge = getExit()->succBegin();
511   return(*erEdge);
512 }
513
514 BLEdgeVector BLInstrumentationDag::getCallPhonyEdges () {
515   BLEdgeVector callEdges;
516
517   for( BLEdgeIterator edge = _edges.begin(), end = _edges.end();
518        edge != end; edge++ ) {
519     if( (*edge)->getType() == BallLarusEdge::CALLEDGE_PHONY )
520       callEdges.push_back(*edge);
521   }
522
523   return callEdges;
524 }
525
526 // Gets the path counter array
527 GlobalVariable* BLInstrumentationDag::getCounterArray() {
528   return _counterArray;
529 }
530
531 void BLInstrumentationDag::setCounterArray(GlobalVariable* c) {
532   _counterArray = c;
533 }
534
535 // Calculates the increment for the chords, thereby removing
536 // instrumentation from the spanning tree edges. Implementation is based on
537 // the algorithm in Figure 4 of [Ball94]
538 void BLInstrumentationDag::calculateChordIncrements() {
539   calculateChordIncrementsDfs(0, getRoot(), NULL);
540
541   BLInstrumentationEdge* chord;
542   for(BLEdgeIterator chordEdge = _chordEdges.begin(),
543       end = _chordEdges.end(); chordEdge != end; chordEdge++) {
544     chord = (BLInstrumentationEdge*) *chordEdge;
545     chord->setIncrement(chord->getIncrement() + chord->getWeight());
546   }
547 }
548
549 // Updates the state when an edge has been split
550 void BLInstrumentationDag::splitUpdate(BLInstrumentationEdge* formerEdge,
551                                        BasicBlock* newBlock) {
552   BallLarusNode* oldTarget = formerEdge->getTarget();
553   BallLarusNode* newNode = addNode(newBlock);
554   formerEdge->setTarget(newNode);
555   newNode->addPredEdge(formerEdge);
556
557   DEBUG(dbgs() << "  Edge split: " << *formerEdge << "\n");
558
559   oldTarget->removePredEdge(formerEdge);
560   BallLarusEdge* newEdge = addEdge(newNode, oldTarget,0);
561
562   if( formerEdge->getType() == BallLarusEdge::BACKEDGE ||
563                         formerEdge->getType() == BallLarusEdge::SPLITEDGE) {
564                 newEdge->setType(formerEdge->getType());
565     newEdge->setPhonyRoot(formerEdge->getPhonyRoot());
566     newEdge->setPhonyExit(formerEdge->getPhonyExit());
567     formerEdge->setType(BallLarusEdge::NORMAL);
568                 formerEdge->setPhonyRoot(NULL);
569     formerEdge->setPhonyExit(NULL);
570   }
571 }
572
573 // Calculates a spanning tree of the DAG ignoring cycles.  Whichever
574 // edges are in the spanning tree will not be instrumented, but this
575 // implementation does not try to minimize the instrumentation overhead
576 // by trying to find hot edges.
577 void BLInstrumentationDag::calculateSpanningTree() {
578   std::stack<BallLarusNode*> dfsStack;
579
580   for(BLNodeIterator nodeIt = _nodes.begin(), end = _nodes.end();
581       nodeIt != end; nodeIt++) {
582     (*nodeIt)->setColor(BallLarusNode::WHITE);
583   }
584
585   dfsStack.push(getRoot());
586   while(dfsStack.size() > 0) {
587     BallLarusNode* node = dfsStack.top();
588     dfsStack.pop();
589
590     if(node->getColor() == BallLarusNode::WHITE)
591       continue;
592
593     BallLarusNode* nextNode;
594     bool forward = true;
595     BLEdgeIterator succEnd = node->succEnd();
596
597     node->setColor(BallLarusNode::WHITE);
598     // first iterate over successors then predecessors
599     for(BLEdgeIterator edge = node->succBegin(), predEnd = node->predEnd();
600         edge != predEnd; edge++) {
601       if(edge == succEnd) {
602         edge = node->predBegin();
603         forward = false;
604       }
605
606       // Ignore split edges
607       if ((*edge)->getType() == BallLarusEdge::SPLITEDGE)
608         continue;
609
610       nextNode = forward? (*edge)->getTarget(): (*edge)->getSource();
611       if(nextNode->getColor() != BallLarusNode::WHITE) {
612         nextNode->setColor(BallLarusNode::WHITE);
613         makeEdgeSpanning((BLInstrumentationEdge*)(*edge));
614       }
615     }
616   }
617
618   for(BLEdgeIterator edge = _edges.begin(), end = _edges.end();
619       edge != end; edge++) {
620     BLInstrumentationEdge* instEdge = (BLInstrumentationEdge*) (*edge);
621       // safe since createEdge is overriden
622     if(!instEdge->isInSpanningTree() && (*edge)->getType()
623         != BallLarusEdge::SPLITEDGE)
624       _chordEdges.push_back(instEdge);
625   }
626 }
627
628 // Pushes initialization further down in order to group the first
629 // increment and initialization.
630 void BLInstrumentationDag::pushInitialization() {
631   BLInstrumentationEdge* exitRootEdge =
632                 (BLInstrumentationEdge*) getExitRootEdge();
633   exitRootEdge->setIsInitialization(true);
634   pushInitializationFromEdge(exitRootEdge);
635 }
636
637 // Pushes the path counter increments up in order to group the last path
638 // number increment.
639 void BLInstrumentationDag::pushCounters() {
640   BLInstrumentationEdge* exitRootEdge =
641     (BLInstrumentationEdge*) getExitRootEdge();
642   exitRootEdge->setIsCounterIncrement(true);
643   pushCountersFromEdge(exitRootEdge);
644 }
645
646 // Removes phony edges from the successor list of the source, and the
647 // predecessor list of the target.
648 void BLInstrumentationDag::unlinkPhony() {
649   BallLarusEdge* edge;
650
651   for(BLEdgeIterator next = _edges.begin(),
652       end = _edges.end(); next != end; next++) {
653     edge = (*next);
654
655     if( edge->getType() == BallLarusEdge::BACKEDGE_PHONY ||
656         edge->getType() == BallLarusEdge::SPLITEDGE_PHONY ||
657         edge->getType() == BallLarusEdge::CALLEDGE_PHONY ) {
658       unlinkEdge(edge);
659     }
660   }
661 }
662
663 // Generate a .dot graph to represent the DAG and pathNumbers
664 void BLInstrumentationDag::generateDotGraph() {
665   std::string errorInfo;
666   std::string functionName = getFunction().getNameStr();
667   std::string filename = "pathdag." + functionName + ".dot";
668
669   DEBUG (dbgs() << "Writing '" << filename << "'...\n");
670   raw_fd_ostream dotFile(filename.c_str(), errorInfo);
671
672   if (!errorInfo.empty()) {
673     errs() << "Error opening '" << filename.c_str() <<"' for writing!";
674     errs() << "\n";
675     return;
676   }
677
678   dotFile << "digraph " << functionName << " {\n";
679
680   for( BLEdgeIterator edge = _edges.begin(), end = _edges.end();
681        edge != end; edge++) {
682     std::string sourceName = (*edge)->getSource()->getName();
683     std::string targetName = (*edge)->getTarget()->getName();
684
685     dotFile << "\t\"" << sourceName.c_str() << "\" -> \""
686             << targetName.c_str() << "\" ";
687
688     long inc = ((BLInstrumentationEdge*)(*edge))->getIncrement();
689
690     switch( (*edge)->getType() ) {
691     case BallLarusEdge::NORMAL:
692       dotFile << "[label=" << inc << "] [color=black];\n";
693       break;
694
695     case BallLarusEdge::BACKEDGE:
696       dotFile << "[color=cyan];\n";
697       break;
698
699     case BallLarusEdge::BACKEDGE_PHONY:
700       dotFile << "[label=" << inc
701               << "] [color=blue];\n";
702       break;
703
704     case BallLarusEdge::SPLITEDGE:
705       dotFile << "[color=violet];\n";
706       break;
707
708     case BallLarusEdge::SPLITEDGE_PHONY:
709       dotFile << "[label=" << inc << "] [color=red];\n";
710       break;
711
712     case BallLarusEdge::CALLEDGE_PHONY:
713       dotFile << "[label=" << inc     << "] [color=green];\n";
714       break;
715     }
716   }
717
718   dotFile << "}\n";
719 }
720
721 // Allows subclasses to determine which type of Node is created.
722 // Override this method to produce subclasses of BallLarusNode if
723 // necessary. The destructor of BallLarusDag will call free on each pointer
724 // created.
725 BallLarusNode* BLInstrumentationDag::createNode(BasicBlock* BB) {
726   return( new BLInstrumentationNode(BB) );
727 }
728
729 // Allows subclasses to determine which type of Edge is created.
730 // Override this method to produce subclasses of BallLarusEdge if
731 // necessary. The destructor of BallLarusDag will call free on each pointer
732 // created.
733 BallLarusEdge* BLInstrumentationDag::createEdge(BallLarusNode* source,
734                                                 BallLarusNode* target, unsigned edgeNumber) {
735   // One can cast from BallLarusNode to BLInstrumentationNode since createNode
736   // is overriden to produce BLInstrumentationNode.
737   return( new BLInstrumentationEdge((BLInstrumentationNode*)source,
738                                     (BLInstrumentationNode*)target) );
739 }
740
741 // Sets the Value corresponding to the pathNumber register, constant,
742 // or phinode.  Used by the instrumentation code to remember path
743 // number Values.
744 Value* BLInstrumentationNode::getStartingPathNumber(){
745   return(_startingPathNumber);
746 }
747
748 // Sets the Value of the pathNumber.  Used by the instrumentation code.
749 void BLInstrumentationNode::setStartingPathNumber(Value* pathNumber) {
750   DEBUG(dbgs() << "  SPN-" << getName() << " <-- " << (pathNumber ?
751                                                        pathNumber->getNameStr() : "unused") << "\n");
752   _startingPathNumber = pathNumber;
753 }
754
755 Value* BLInstrumentationNode::getEndingPathNumber(){
756   return(_endingPathNumber);
757 }
758
759 void BLInstrumentationNode::setEndingPathNumber(Value* pathNumber) {
760   DEBUG(dbgs() << "  EPN-" << getName() << " <-- "
761         << (pathNumber ? pathNumber->getNameStr() : "unused") << "\n");
762   _endingPathNumber = pathNumber;
763 }
764
765 // Get the PHINode Instruction for this node.  Used by instrumentation
766 // code.
767 PHINode* BLInstrumentationNode::getPathPHI() {
768   return(_pathPHI);
769 }
770
771 // Set the PHINode Instruction for this node.  Used by instrumentation
772 // code.
773 void BLInstrumentationNode::setPathPHI(PHINode* pathPHI) {
774   _pathPHI = pathPHI;
775 }
776
777 // Removes the edge from the appropriate predecessor and successor
778 // lists.
779 void BLInstrumentationDag::unlinkEdge(BallLarusEdge* edge) {
780   if(edge == getExitRootEdge())
781     DEBUG(dbgs() << " Removing exit->root edge\n");
782
783   edge->getSource()->removeSuccEdge(edge);
784   edge->getTarget()->removePredEdge(edge);
785 }
786
787 // Makes an edge part of the spanning tree.
788 void BLInstrumentationDag::makeEdgeSpanning(BLInstrumentationEdge* edge) {
789   edge->setIsInSpanningTree(true);
790   _treeEdges.push_back(edge);
791 }
792
793 // Pushes initialization and calls itself recursively.
794 void BLInstrumentationDag::pushInitializationFromEdge(
795   BLInstrumentationEdge* edge) {
796   BallLarusNode* target;
797
798   target = edge->getTarget();
799   if( target->getNumberPredEdges() > 1 || target == getExit() ) {
800     return;
801   } else {
802     for(BLEdgeIterator next = target->succBegin(),
803           end = target->succEnd(); next != end; next++) {
804       BLInstrumentationEdge* intoEdge = (BLInstrumentationEdge*) *next;
805
806       // Skip split edges
807       if (intoEdge->getType() == BallLarusEdge::SPLITEDGE)
808         continue;
809
810       intoEdge->setIncrement(intoEdge->getIncrement() +
811                              edge->getIncrement());
812       intoEdge->setIsInitialization(true);
813       pushInitializationFromEdge(intoEdge);
814     }
815
816     edge->setIncrement(0);
817     edge->setIsInitialization(false);
818   }
819 }
820
821 // Pushes path counter increments up recursively.
822 void BLInstrumentationDag::pushCountersFromEdge(BLInstrumentationEdge* edge) {
823   BallLarusNode* source;
824
825   source = edge->getSource();
826   if(source->getNumberSuccEdges() > 1 || source == getRoot()
827      || edge->isInitialization()) {
828     return;
829   } else {
830     for(BLEdgeIterator previous = source->predBegin(),
831           end = source->predEnd(); previous != end; previous++) {
832       BLInstrumentationEdge* fromEdge = (BLInstrumentationEdge*) *previous;
833
834       // Skip split edges
835       if (fromEdge->getType() == BallLarusEdge::SPLITEDGE)
836         continue;
837
838       fromEdge->setIncrement(fromEdge->getIncrement() +
839                              edge->getIncrement());
840       fromEdge->setIsCounterIncrement(true);
841       pushCountersFromEdge(fromEdge);
842     }
843
844     edge->setIncrement(0);
845     edge->setIsCounterIncrement(false);
846   }
847 }
848
849 // Depth first algorithm for determining the chord increments.
850 void BLInstrumentationDag::calculateChordIncrementsDfs(long weight,
851                                                        BallLarusNode* v, BallLarusEdge* e) {
852   BLInstrumentationEdge* f;
853
854   for(BLEdgeIterator treeEdge = _treeEdges.begin(),
855         end = _treeEdges.end(); treeEdge != end; treeEdge++) {
856     f = (BLInstrumentationEdge*) *treeEdge;
857     if(e != f && v == f->getTarget()) {
858       calculateChordIncrementsDfs(
859         calculateChordIncrementsDir(e,f)*(weight) +
860         f->getWeight(), f->getSource(), f);
861     }
862     if(e != f && v == f->getSource()) {
863       calculateChordIncrementsDfs(
864         calculateChordIncrementsDir(e,f)*(weight) +
865         f->getWeight(), f->getTarget(), f);
866     }
867   }
868
869   for(BLEdgeIterator chordEdge = _chordEdges.begin(),
870         end = _chordEdges.end(); chordEdge != end; chordEdge++) {
871     f = (BLInstrumentationEdge*) *chordEdge;
872     if(v == f->getSource() || v == f->getTarget()) {
873       f->setIncrement(f->getIncrement() +
874                       calculateChordIncrementsDir(e,f)*weight);
875     }
876   }
877 }
878
879 // Determines the relative direction of two edges.
880 int BLInstrumentationDag::calculateChordIncrementsDir(BallLarusEdge* e,
881                                                       BallLarusEdge* f) {
882   if( e == NULL)
883     return(1);
884   else if(e->getSource() == f->getTarget()
885           || e->getTarget() == f->getSource())
886     return(1);
887
888   return(-1);
889 }
890
891 // Creates an increment constant representing incr.
892 ConstantInt* PathProfiler::createIncrementConstant(long incr,
893                                                    int bitsize) {
894   return(ConstantInt::get(IntegerType::get(*Context, 32), incr));
895 }
896
897 // Creates an increment constant representing the value in
898 // edge->getIncrement().
899 ConstantInt* PathProfiler::createIncrementConstant(
900   BLInstrumentationEdge* edge) {
901   return(createIncrementConstant(edge->getIncrement(), 32));
902 }
903
904 // Finds the insertion point after pathNumber in block.  PathNumber may
905 // be NULL.
906 BasicBlock::iterator PathProfiler::getInsertionPoint(BasicBlock* block, Value*
907                                                      pathNumber) {
908   if(pathNumber == NULL || isa<ConstantInt>(pathNumber)
909      || (((Instruction*)(pathNumber))->getParent()) != block) {
910     return(block->getFirstNonPHI());
911   } else {
912     Instruction* pathNumberInst = (Instruction*) (pathNumber);
913     BasicBlock::iterator insertPoint;
914     BasicBlock::iterator end = block->end();
915
916     for(insertPoint = block->begin();
917         insertPoint != end; insertPoint++) {
918       Instruction* insertInst = &(*insertPoint);
919
920       if(insertInst == pathNumberInst)
921         return(++insertPoint);
922     }
923
924     return(insertPoint);
925   }
926 }
927
928 // A PHINode is created in the node, and its values initialized to -1U.
929 void PathProfiler::preparePHI(BLInstrumentationNode* node) {
930   BasicBlock* block = node->getBlock();
931   BasicBlock::iterator insertPoint = block->getFirstNonPHI();
932   PHINode* phi = PHINode::Create(Type::getInt32Ty(*Context), "pathNumber",
933                                  insertPoint );
934   node->setPathPHI(phi);
935   node->setStartingPathNumber(phi);
936   node->setEndingPathNumber(phi);
937
938   for(pred_iterator predIt = pred_begin(node->getBlock()),
939         end = pred_end(node->getBlock()); predIt != end; predIt++) {
940     BasicBlock* pred = (*predIt);
941
942     if(pred != NULL)
943       phi->addIncoming(createIncrementConstant((long)-1, 32), pred);
944   }
945 }
946
947 // Inserts source's pathNumber Value* into target.  Target may or may not
948 // have multiple predecessors, and may or may not have its phiNode
949 // initalized.
950 void PathProfiler::pushValueIntoNode(BLInstrumentationNode* source,
951                                      BLInstrumentationNode* target) {
952   if(target->getBlock() == NULL)
953     return;
954
955
956   if(target->getNumberPredEdges() <= 1) {
957     assert(target->getStartingPathNumber() == NULL &&
958            "Target already has path number");
959     target->setStartingPathNumber(source->getEndingPathNumber());
960     target->setEndingPathNumber(source->getEndingPathNumber());
961     DEBUG(dbgs() << "  Passing path number"
962           << (source->getEndingPathNumber() ? "" : " (null)")
963           << " value through.\n");
964   } else {
965     if(target->getPathPHI() == NULL) {
966       DEBUG(dbgs() << "  Initializing PHI node for block '"
967             << target->getName() << "'\n");
968       preparePHI(target);
969     }
970     pushValueIntoPHI(target, source);
971     DEBUG(dbgs() << "  Passing number value into PHI for block '"
972           << target->getName() << "'\n");
973   }
974 }
975
976 // Inserts source's pathNumber Value* into the appropriate slot of
977 // target's phiNode.
978 void PathProfiler::pushValueIntoPHI(BLInstrumentationNode* target,
979                                     BLInstrumentationNode* source) {
980   PHINode* phi = target->getPathPHI();
981   assert(phi != NULL && "  Tried to push value into node with PHI, but node"
982          " actually had no PHI.");
983   phi->removeIncomingValue(source->getBlock(), false);
984   phi->addIncoming(source->getEndingPathNumber(), source->getBlock());
985 }
986
987 // The Value* in node, oldVal,  is updated with a Value* correspodning to
988 // oldVal + addition.
989 void PathProfiler::insertNumberIncrement(BLInstrumentationNode* node,
990                                          Value* addition, bool atBeginning) {
991   BasicBlock* block = node->getBlock();
992   assert(node->getStartingPathNumber() != NULL);
993   assert(node->getEndingPathNumber() != NULL);
994
995   BasicBlock::iterator insertPoint;
996
997   if( atBeginning )
998     insertPoint = block->getFirstNonPHI();
999   else
1000     insertPoint = block->getTerminator();
1001
1002   DEBUG(errs() << "  Creating addition instruction.\n");
1003   Value* newpn = BinaryOperator::Create(Instruction::Add,
1004                                         node->getStartingPathNumber(),
1005                                         addition, "pathNumber", insertPoint);
1006
1007   node->setEndingPathNumber(newpn);
1008
1009   if( atBeginning )
1010     node->setStartingPathNumber(newpn);
1011 }
1012
1013 // Creates a counter increment in the given node.  The Value* in node is
1014 // taken as the index into an array or hash table.  The hash table access
1015 // is a call to the runtime.
1016 void PathProfiler::insertCounterIncrement(Value* incValue,
1017                                           BasicBlock::iterator insertPoint,
1018                                           BLInstrumentationDag* dag,
1019                                           bool increment) {
1020   // Counter increment for array
1021   if( dag->getNumberOfPaths() <= HASH_THRESHHOLD ) {
1022     // Get pointer to the array location
1023     std::vector<Value*> gepIndices(2);
1024     gepIndices[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
1025     gepIndices[1] = incValue;
1026
1027     GetElementPtrInst* pcPointer =
1028       GetElementPtrInst::Create(dag->getCounterArray(),
1029                                 gepIndices.begin(), gepIndices.end(),
1030                                 "counterInc", insertPoint);
1031
1032     // Load from the array - call it oldPC
1033     LoadInst* oldPc = new LoadInst(pcPointer, "oldPC", insertPoint);
1034
1035     // Test to see whether adding 1 will overflow the counter
1036     ICmpInst* isMax = new ICmpInst(insertPoint, CmpInst::ICMP_ULT, oldPc,
1037                                    createIncrementConstant(0xffffffff, 32),
1038                                    "isMax");
1039
1040     // Select increment for the path counter based on overflow
1041     SelectInst* inc =
1042       SelectInst::Create( isMax, createIncrementConstant(increment?1:-1,32),
1043                           createIncrementConstant(0,32),
1044                           "pathInc", insertPoint);
1045
1046     // newPc = oldPc + inc
1047     BinaryOperator* newPc = BinaryOperator::Create(Instruction::Add,
1048                                                    oldPc, inc, "newPC",
1049                                                    insertPoint);
1050
1051     // Store back in to the array
1052     new StoreInst(newPc, pcPointer, insertPoint);
1053   } else { // Counter increment for hash
1054     std::vector<Value*> args(2);
1055     args[0] = ConstantInt::get(Type::getInt32Ty(*Context),
1056                                currentFunctionNumber);
1057     args[1] = incValue;
1058
1059     CallInst::Create(
1060       increment ? llvmIncrementHashFunction : llvmDecrementHashFunction,
1061       args.begin(), args.end(), "", insertPoint);
1062   }
1063 }
1064
1065 // Inserts instrumentation for the given edge
1066 //
1067 // Pre: The edge's source node has pathNumber set if edge is non zero
1068 // path number increment.
1069 //
1070 // Post: Edge's target node has a pathNumber set to the path number Value
1071 // corresponding to the value of the path register after edge's
1072 // execution.
1073 //
1074 // FIXME: This should be reworked so it's not recursive.
1075 void PathProfiler::insertInstrumentationStartingAt(BLInstrumentationEdge* edge,
1076                                                    BLInstrumentationDag* dag) {
1077   // Mark the edge as instrumented
1078   edge->setHasInstrumentation(true);
1079   DEBUG(dbgs() << "\nInstrumenting edge: " << (*edge) << "\n");
1080
1081   // create a new node for this edge's instrumentation
1082   splitCritical(edge, dag);
1083
1084   BLInstrumentationNode* sourceNode = (BLInstrumentationNode*)edge->getSource();
1085   BLInstrumentationNode* targetNode = (BLInstrumentationNode*)edge->getTarget();
1086   BLInstrumentationNode* instrumentNode;
1087   BLInstrumentationNode* nextSourceNode;
1088
1089   bool atBeginning = false;
1090
1091   // Source node has only 1 successor so any information can be simply
1092   // inserted in to it without splitting
1093   if( sourceNode->getBlock() && sourceNode->getNumberSuccEdges() <= 1) {
1094     DEBUG(dbgs() << "  Potential instructions to be placed in: "
1095           << sourceNode->getName() << " (at end)\n");
1096     instrumentNode = sourceNode;
1097     nextSourceNode = targetNode; // ... since we never made any new nodes
1098   }
1099
1100   // The target node only has one predecessor, so we can safely insert edge
1101   // instrumentation into it. If there was splitting, it must have been
1102   // successful.
1103   else if( targetNode->getNumberPredEdges() == 1 ) {
1104     DEBUG(dbgs() << "  Potential instructions to be placed in: "
1105           << targetNode->getName() << " (at beginning)\n");
1106     pushValueIntoNode(sourceNode, targetNode);
1107     instrumentNode = targetNode;
1108     nextSourceNode = NULL; // ... otherwise we'll just keep splitting
1109     atBeginning = true;
1110   }
1111
1112   // Somehow, splitting must have failed.
1113   else {
1114     errs() << "Instrumenting could not split a critical edge.\n";
1115     DEBUG(dbgs() << "  Couldn't split edge " << (*edge) << ".\n");
1116     return;
1117   }
1118
1119   // Insert instrumentation if this is a back or split edge
1120   if( edge->getType() == BallLarusEdge::BACKEDGE ||
1121       edge->getType() == BallLarusEdge::SPLITEDGE ) {
1122     BLInstrumentationEdge* top =
1123       (BLInstrumentationEdge*) edge->getPhonyRoot();
1124     BLInstrumentationEdge* bottom =
1125       (BLInstrumentationEdge*) edge->getPhonyExit();
1126
1127     assert( top->isInitialization() && " Top phony edge did not"
1128             " contain a path number initialization.");
1129     assert( bottom->isCounterIncrement() && " Bottom phony edge"
1130             " did not contain a path counter increment.");
1131
1132     // split edge has yet to be initialized
1133     if( !instrumentNode->getEndingPathNumber() ) {
1134       instrumentNode->setStartingPathNumber(createIncrementConstant(0,32));
1135       instrumentNode->setEndingPathNumber(createIncrementConstant(0,32));
1136     }
1137
1138     BasicBlock::iterator insertPoint = atBeginning ?
1139       instrumentNode->getBlock()->getFirstNonPHI() :
1140       instrumentNode->getBlock()->getTerminator();
1141
1142     // add information from the bottom edge, if it exists
1143     if( bottom->getIncrement() ) {
1144       Value* newpn =
1145         BinaryOperator::Create(Instruction::Add,
1146                                instrumentNode->getStartingPathNumber(),
1147                                createIncrementConstant(bottom),
1148                                "pathNumber", insertPoint);
1149       instrumentNode->setEndingPathNumber(newpn);
1150     }
1151
1152     insertCounterIncrement(instrumentNode->getEndingPathNumber(),
1153                            insertPoint, dag);
1154
1155     if( atBeginning )
1156       instrumentNode->setStartingPathNumber(createIncrementConstant(top));
1157
1158     instrumentNode->setEndingPathNumber(createIncrementConstant(top));
1159
1160     // Check for path counter increments
1161     if( top->isCounterIncrement() ) {
1162       insertCounterIncrement(instrumentNode->getEndingPathNumber(),
1163                              instrumentNode->getBlock()->getTerminator(),dag);
1164       instrumentNode->setEndingPathNumber(0);
1165     }
1166   }
1167
1168   // Insert instrumentation if this is a normal edge
1169   else {
1170     BasicBlock::iterator insertPoint = atBeginning ?
1171       instrumentNode->getBlock()->getFirstNonPHI() :
1172       instrumentNode->getBlock()->getTerminator();
1173
1174     if( edge->isInitialization() ) { // initialize path number
1175       instrumentNode->setEndingPathNumber(createIncrementConstant(edge));
1176     } else if( edge->getIncrement() )       {// increment path number
1177       Value* newpn =
1178         BinaryOperator::Create(Instruction::Add,
1179                                instrumentNode->getStartingPathNumber(),
1180                                createIncrementConstant(edge),
1181                                "pathNumber", insertPoint);
1182       instrumentNode->setEndingPathNumber(newpn);
1183
1184       if( atBeginning )
1185         instrumentNode->setStartingPathNumber(newpn);
1186     }
1187
1188     // Check for path counter increments
1189     if( edge->isCounterIncrement() ) {
1190       insertCounterIncrement(instrumentNode->getEndingPathNumber(),
1191                              insertPoint, dag);
1192       instrumentNode->setEndingPathNumber(0);
1193     }
1194   }
1195
1196   // Push it along
1197   if (nextSourceNode && instrumentNode->getEndingPathNumber())
1198     pushValueIntoNode(instrumentNode, nextSourceNode);
1199
1200   // Add all the successors
1201   for( BLEdgeIterator next = targetNode->succBegin(),
1202          end = targetNode->succEnd(); next != end; next++ ) {
1203     // So long as it is un-instrumented, add it to the list
1204     if( !((BLInstrumentationEdge*)(*next))->hasInstrumentation() )
1205       insertInstrumentationStartingAt((BLInstrumentationEdge*)*next,dag);
1206     else
1207       DEBUG(dbgs() << "  Edge " << *(BLInstrumentationEdge*)(*next)
1208             << " already instrumented.\n");
1209   }
1210 }
1211
1212 // Inserts instrumentation according to the marked edges in dag.  Phony edges
1213 // must be unlinked from the DAG, but accessible from the backedges.  Dag
1214 // must have initializations, path number increments, and counter increments
1215 // present.
1216 //
1217 // Counter storage is created here.
1218 void PathProfiler::insertInstrumentation(
1219   BLInstrumentationDag& dag, Module &M) {
1220
1221   BLInstrumentationEdge* exitRootEdge =
1222     (BLInstrumentationEdge*) dag.getExitRootEdge();
1223   insertInstrumentationStartingAt(exitRootEdge, &dag);
1224
1225   // Iterate through each call edge and apply the appropriate hash increment
1226   // and decrement functions
1227   BLEdgeVector callEdges = dag.getCallPhonyEdges();
1228   for( BLEdgeIterator edge = callEdges.begin(),
1229          end = callEdges.end(); edge != end; edge++ ) {
1230     BLInstrumentationNode* node =
1231       (BLInstrumentationNode*)(*edge)->getSource();
1232     BasicBlock::iterator insertPoint = node->getBlock()->getFirstNonPHI();
1233
1234     // Find the first function call
1235     while( ((Instruction&)(*insertPoint)).getOpcode() != Instruction::Call )
1236       insertPoint++;
1237
1238     DEBUG(dbgs() << "\nInstrumenting method call block '"
1239           << node->getBlock()->getNameStr() << "'\n");
1240     DEBUG(dbgs() << "   Path number initialized: "
1241           << ((node->getStartingPathNumber()) ? "yes" : "no") << "\n");
1242
1243     Value* newpn;
1244     if( node->getStartingPathNumber() ) {
1245       long inc = ((BLInstrumentationEdge*)(*edge))->getIncrement();
1246       if ( inc )
1247         newpn = BinaryOperator::Create(Instruction::Add,
1248                                        node->getStartingPathNumber(),
1249                                        createIncrementConstant(inc,32),
1250                                        "pathNumber", insertPoint);
1251       else
1252         newpn = node->getStartingPathNumber();
1253     } else {
1254       newpn = (Value*)createIncrementConstant(
1255         ((BLInstrumentationEdge*)(*edge))->getIncrement(), 32);
1256     }
1257
1258     insertCounterIncrement(newpn, insertPoint, &dag);
1259     insertCounterIncrement(newpn, node->getBlock()->getTerminator(),
1260                            &dag, false);
1261   }
1262 }
1263
1264 // Entry point of the module
1265 void PathProfiler::runOnFunction(std::vector<Constant*> &ftInit,
1266                                  Function &F, Module &M) {
1267   // Build DAG from CFG
1268   BLInstrumentationDag dag = BLInstrumentationDag(F);
1269   dag.init();
1270
1271   // give each path a unique integer value
1272   dag.calculatePathNumbers();
1273
1274   // modify path increments to increase the efficiency
1275   // of instrumentation
1276   dag.calculateSpanningTree();
1277   dag.calculateChordIncrements();
1278   dag.pushInitialization();
1279   dag.pushCounters();
1280   dag.unlinkPhony();
1281
1282   // potentially generate .dot graph for the dag
1283   if (DotPathDag)
1284     dag.generateDotGraph ();
1285
1286   // Should we store the information in an array or hash
1287   if( dag.getNumberOfPaths() <= HASH_THRESHHOLD ) {
1288     const Type* t = ArrayType::get(Type::getInt32Ty(*Context),
1289                                    dag.getNumberOfPaths());
1290
1291     dag.setCounterArray(new GlobalVariable(M, t, false,
1292                                            GlobalValue::InternalLinkage,
1293                                            Constant::getNullValue(t), ""));
1294   }
1295
1296   insertInstrumentation(dag, M);
1297
1298   // Add to global function reference table
1299   unsigned type;
1300   const Type* voidPtr = TypeBuilder<types::i<8>*, true>::get(*Context);
1301
1302   if( dag.getNumberOfPaths() <= HASH_THRESHHOLD )
1303     type = ProfilingArray;
1304   else
1305     type = ProfilingHash;
1306
1307   std::vector<Constant*> entryArray(3);
1308   entryArray[0] = createIncrementConstant(type,32);
1309   entryArray[1] = createIncrementConstant(dag.getNumberOfPaths(),32);
1310   entryArray[2] = dag.getCounterArray() ?
1311     ConstantExpr::getBitCast(dag.getCounterArray(), voidPtr) :
1312     Constant::getNullValue(voidPtr);
1313
1314   const StructType* at = ftEntryTypeBuilder::get(*Context);
1315   ConstantStruct* functionEntry =
1316     (ConstantStruct*)ConstantStruct::get(at, entryArray);
1317   ftInit.push_back(functionEntry);
1318 }
1319
1320 // Output the bitcode if we want to observe instrumentation changess
1321 #define PRINT_MODULE dbgs() <<                               \
1322   "\n\n============= MODULE BEGIN ===============\n" << M << \
1323   "\n============== MODULE END ================\n"
1324
1325 bool PathProfiler::runOnModule(Module &M) {
1326   Context = &M.getContext();
1327
1328   DEBUG(dbgs()
1329         << "****************************************\n"
1330         << "****************************************\n"
1331         << "**                                    **\n"
1332         << "**   PATH PROFILING INSTRUMENTATION   **\n"
1333         << "**                                    **\n"
1334         << "****************************************\n"
1335         << "****************************************\n");
1336
1337   // No main, no instrumentation!
1338   Function *Main = M.getFunction("main");
1339
1340   // Using fortran? ... this kind of works
1341   if (!Main)
1342     Main = M.getFunction("MAIN__");
1343
1344   if (!Main) {
1345     errs() << "WARNING: cannot insert path profiling into a module"
1346            << " with no main function!\n";
1347     return false;
1348   }
1349
1350   BasicBlock::iterator insertPoint = Main->getEntryBlock().getFirstNonPHI();
1351
1352   llvmIncrementHashFunction = M.getOrInsertFunction(
1353     "llvm_increment_path_count",
1354     Type::getVoidTy(*Context), // return type
1355     Type::getInt32Ty(*Context), // function number
1356     Type::getInt32Ty(*Context), // path number
1357     NULL );
1358
1359   llvmDecrementHashFunction = M.getOrInsertFunction(
1360     "llvm_decrement_path_count",
1361     Type::getVoidTy(*Context), // return type
1362     Type::getInt32Ty(*Context), // function number
1363     Type::getInt32Ty(*Context), // path number
1364     NULL );
1365
1366   std::vector<Constant*> ftInit;
1367   unsigned functionNumber = 0;
1368   for (Module::iterator F = M.begin(), E = M.end(); F != E; F++) {
1369     if (F->isDeclaration())
1370       continue;
1371
1372     DEBUG(dbgs() << "Function: " << F->getNameStr() << "\n");
1373     functionNumber++;
1374
1375     // set function number
1376     currentFunctionNumber = functionNumber;
1377     runOnFunction(ftInit, *F, M);
1378   }
1379
1380   const Type *t = ftEntryTypeBuilder::get(*Context);
1381   const ArrayType* ftArrayType = ArrayType::get(t, ftInit.size());
1382   Constant* ftInitConstant = ConstantArray::get(ftArrayType, ftInit);
1383
1384   DEBUG(dbgs() << " ftArrayType:" << *ftArrayType << "\n");
1385
1386   GlobalVariable* functionTable =
1387     new GlobalVariable(M, ftArrayType, false, GlobalValue::InternalLinkage,
1388                        ftInitConstant, "functionPathTable");
1389   const Type *eltType = ftArrayType->getTypeAtIndex((unsigned)0);
1390   InsertProfilingInitCall(Main, "llvm_start_path_profiling", functionTable,
1391                           PointerType::getUnqual(eltType));
1392
1393   DEBUG(PRINT_MODULE);
1394
1395   return true;
1396 }
1397
1398 // If this edge is a critical edge, then inserts a node at this edge.
1399 // This edge becomes the first edge, and a new BallLarusEdge is created.
1400 // Returns true if the edge was split
1401 bool PathProfiler::splitCritical(BLInstrumentationEdge* edge,
1402                                  BLInstrumentationDag* dag) {
1403   unsigned succNum = edge->getSuccessorNumber();
1404   BallLarusNode* sourceNode = edge->getSource();
1405   BallLarusNode* targetNode = edge->getTarget();
1406   BasicBlock* sourceBlock = sourceNode->getBlock();
1407   BasicBlock* targetBlock = targetNode->getBlock();
1408
1409   if(sourceBlock == NULL || targetBlock == NULL
1410      || sourceNode->getNumberSuccEdges() <= 1
1411      || targetNode->getNumberPredEdges() == 1 ) {
1412     return(false);
1413   }
1414
1415   TerminatorInst* terminator = sourceBlock->getTerminator();
1416
1417   if( SplitCriticalEdge(terminator, succNum, this, false)) {
1418     BasicBlock* newBlock = terminator->getSuccessor(succNum);
1419     dag->splitUpdate(edge, newBlock);
1420     return(true);
1421   } else
1422     return(false);
1423 }