Andrew Trick | 04317cc | 2011-01-29 01:09:53 +0000 | [diff] [blame] | 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(); |
Jay Foad | d8b4fb4 | 2011-03-30 11:19:20 +0000 | [diff] [blame^] | 932 | pred_iterator PB = pred_begin(node->getBlock()), |
| 933 | PE = pred_end(node->getBlock()); |
Andrew Trick | 04317cc | 2011-01-29 01:09:53 +0000 | [diff] [blame] | 934 | PHINode* phi = PHINode::Create(Type::getInt32Ty(*Context), "pathNumber", |
| 935 | insertPoint ); |
Jay Foad | d8b4fb4 | 2011-03-30 11:19:20 +0000 | [diff] [blame^] | 936 | phi->reserveOperandSpace(std::distance(PB, PE)); |
Andrew Trick | 04317cc | 2011-01-29 01:09:53 +0000 | [diff] [blame] | 937 | node->setPathPHI(phi); |
| 938 | node->setStartingPathNumber(phi); |
| 939 | node->setEndingPathNumber(phi); |
| 940 | |
Jay Foad | d8b4fb4 | 2011-03-30 11:19:20 +0000 | [diff] [blame^] | 941 | for(pred_iterator predIt = PB; predIt != PE; predIt++) { |
Andrew Trick | 04317cc | 2011-01-29 01:09:53 +0000 | [diff] [blame] | 942 | BasicBlock* pred = (*predIt); |
| 943 | |
| 944 | if(pred != NULL) |
| 945 | phi->addIncoming(createIncrementConstant((long)-1, 32), pred); |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | // Inserts source's pathNumber Value* into target. Target may or may not |
| 950 | // have multiple predecessors, and may or may not have its phiNode |
| 951 | // initalized. |
| 952 | void PathProfiler::pushValueIntoNode(BLInstrumentationNode* source, |
| 953 | BLInstrumentationNode* target) { |
| 954 | if(target->getBlock() == NULL) |
| 955 | return; |
| 956 | |
| 957 | |
| 958 | if(target->getNumberPredEdges() <= 1) { |
| 959 | assert(target->getStartingPathNumber() == NULL && |
| 960 | "Target already has path number"); |
| 961 | target->setStartingPathNumber(source->getEndingPathNumber()); |
| 962 | target->setEndingPathNumber(source->getEndingPathNumber()); |
| 963 | DEBUG(dbgs() << " Passing path number" |
| 964 | << (source->getEndingPathNumber() ? "" : " (null)") |
| 965 | << " value through.\n"); |
| 966 | } else { |
| 967 | if(target->getPathPHI() == NULL) { |
| 968 | DEBUG(dbgs() << " Initializing PHI node for block '" |
| 969 | << target->getName() << "'\n"); |
| 970 | preparePHI(target); |
| 971 | } |
| 972 | pushValueIntoPHI(target, source); |
| 973 | DEBUG(dbgs() << " Passing number value into PHI for block '" |
| 974 | << target->getName() << "'\n"); |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | // Inserts source's pathNumber Value* into the appropriate slot of |
| 979 | // target's phiNode. |
| 980 | void PathProfiler::pushValueIntoPHI(BLInstrumentationNode* target, |
| 981 | BLInstrumentationNode* source) { |
| 982 | PHINode* phi = target->getPathPHI(); |
| 983 | assert(phi != NULL && " Tried to push value into node with PHI, but node" |
| 984 | " actually had no PHI."); |
| 985 | phi->removeIncomingValue(source->getBlock(), false); |
| 986 | phi->addIncoming(source->getEndingPathNumber(), source->getBlock()); |
| 987 | } |
| 988 | |
| 989 | // The Value* in node, oldVal, is updated with a Value* correspodning to |
| 990 | // oldVal + addition. |
| 991 | void PathProfiler::insertNumberIncrement(BLInstrumentationNode* node, |
| 992 | Value* addition, bool atBeginning) { |
| 993 | BasicBlock* block = node->getBlock(); |
| 994 | assert(node->getStartingPathNumber() != NULL); |
| 995 | assert(node->getEndingPathNumber() != NULL); |
| 996 | |
| 997 | BasicBlock::iterator insertPoint; |
| 998 | |
| 999 | if( atBeginning ) |
| 1000 | insertPoint = block->getFirstNonPHI(); |
| 1001 | else |
| 1002 | insertPoint = block->getTerminator(); |
| 1003 | |
| 1004 | DEBUG(errs() << " Creating addition instruction.\n"); |
| 1005 | Value* newpn = BinaryOperator::Create(Instruction::Add, |
| 1006 | node->getStartingPathNumber(), |
| 1007 | addition, "pathNumber", insertPoint); |
| 1008 | |
| 1009 | node->setEndingPathNumber(newpn); |
| 1010 | |
| 1011 | if( atBeginning ) |
| 1012 | node->setStartingPathNumber(newpn); |
| 1013 | } |
| 1014 | |
| 1015 | // Creates a counter increment in the given node. The Value* in node is |
| 1016 | // taken as the index into an array or hash table. The hash table access |
| 1017 | // is a call to the runtime. |
| 1018 | void PathProfiler::insertCounterIncrement(Value* incValue, |
| 1019 | BasicBlock::iterator insertPoint, |
| 1020 | BLInstrumentationDag* dag, |
| 1021 | bool increment) { |
| 1022 | // Counter increment for array |
| 1023 | if( dag->getNumberOfPaths() <= HASH_THRESHHOLD ) { |
| 1024 | // Get pointer to the array location |
| 1025 | std::vector<Value*> gepIndices(2); |
| 1026 | gepIndices[0] = Constant::getNullValue(Type::getInt32Ty(*Context)); |
| 1027 | gepIndices[1] = incValue; |
| 1028 | |
| 1029 | GetElementPtrInst* pcPointer = |
| 1030 | GetElementPtrInst::Create(dag->getCounterArray(), |
| 1031 | gepIndices.begin(), gepIndices.end(), |
| 1032 | "counterInc", insertPoint); |
| 1033 | |
| 1034 | // Load from the array - call it oldPC |
| 1035 | LoadInst* oldPc = new LoadInst(pcPointer, "oldPC", insertPoint); |
| 1036 | |
| 1037 | // Test to see whether adding 1 will overflow the counter |
| 1038 | ICmpInst* isMax = new ICmpInst(insertPoint, CmpInst::ICMP_ULT, oldPc, |
| 1039 | createIncrementConstant(0xffffffff, 32), |
| 1040 | "isMax"); |
| 1041 | |
| 1042 | // Select increment for the path counter based on overflow |
| 1043 | SelectInst* inc = |
| 1044 | SelectInst::Create( isMax, createIncrementConstant(increment?1:-1,32), |
| 1045 | createIncrementConstant(0,32), |
| 1046 | "pathInc", insertPoint); |
| 1047 | |
| 1048 | // newPc = oldPc + inc |
| 1049 | BinaryOperator* newPc = BinaryOperator::Create(Instruction::Add, |
| 1050 | oldPc, inc, "newPC", |
| 1051 | insertPoint); |
| 1052 | |
| 1053 | // Store back in to the array |
| 1054 | new StoreInst(newPc, pcPointer, insertPoint); |
| 1055 | } else { // Counter increment for hash |
| 1056 | std::vector<Value*> args(2); |
| 1057 | args[0] = ConstantInt::get(Type::getInt32Ty(*Context), |
| 1058 | currentFunctionNumber); |
| 1059 | args[1] = incValue; |
| 1060 | |
| 1061 | CallInst::Create( |
| 1062 | increment ? llvmIncrementHashFunction : llvmDecrementHashFunction, |
| 1063 | args.begin(), args.end(), "", insertPoint); |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | // Inserts instrumentation for the given edge |
| 1068 | // |
| 1069 | // Pre: The edge's source node has pathNumber set if edge is non zero |
| 1070 | // path number increment. |
| 1071 | // |
| 1072 | // Post: Edge's target node has a pathNumber set to the path number Value |
| 1073 | // corresponding to the value of the path register after edge's |
| 1074 | // execution. |
| 1075 | // |
| 1076 | // FIXME: This should be reworked so it's not recursive. |
| 1077 | void PathProfiler::insertInstrumentationStartingAt(BLInstrumentationEdge* edge, |
| 1078 | BLInstrumentationDag* dag) { |
| 1079 | // Mark the edge as instrumented |
| 1080 | edge->setHasInstrumentation(true); |
| 1081 | DEBUG(dbgs() << "\nInstrumenting edge: " << (*edge) << "\n"); |
| 1082 | |
| 1083 | // create a new node for this edge's instrumentation |
| 1084 | splitCritical(edge, dag); |
| 1085 | |
| 1086 | BLInstrumentationNode* sourceNode = (BLInstrumentationNode*)edge->getSource(); |
| 1087 | BLInstrumentationNode* targetNode = (BLInstrumentationNode*)edge->getTarget(); |
| 1088 | BLInstrumentationNode* instrumentNode; |
| 1089 | BLInstrumentationNode* nextSourceNode; |
| 1090 | |
| 1091 | bool atBeginning = false; |
| 1092 | |
| 1093 | // Source node has only 1 successor so any information can be simply |
| 1094 | // inserted in to it without splitting |
| 1095 | if( sourceNode->getBlock() && sourceNode->getNumberSuccEdges() <= 1) { |
| 1096 | DEBUG(dbgs() << " Potential instructions to be placed in: " |
| 1097 | << sourceNode->getName() << " (at end)\n"); |
| 1098 | instrumentNode = sourceNode; |
| 1099 | nextSourceNode = targetNode; // ... since we never made any new nodes |
| 1100 | } |
| 1101 | |
| 1102 | // The target node only has one predecessor, so we can safely insert edge |
| 1103 | // instrumentation into it. If there was splitting, it must have been |
| 1104 | // successful. |
| 1105 | else if( targetNode->getNumberPredEdges() == 1 ) { |
| 1106 | DEBUG(dbgs() << " Potential instructions to be placed in: " |
| 1107 | << targetNode->getName() << " (at beginning)\n"); |
| 1108 | pushValueIntoNode(sourceNode, targetNode); |
| 1109 | instrumentNode = targetNode; |
| 1110 | nextSourceNode = NULL; // ... otherwise we'll just keep splitting |
| 1111 | atBeginning = true; |
| 1112 | } |
| 1113 | |
| 1114 | // Somehow, splitting must have failed. |
| 1115 | else { |
| 1116 | errs() << "Instrumenting could not split a critical edge.\n"; |
| 1117 | DEBUG(dbgs() << " Couldn't split edge " << (*edge) << ".\n"); |
| 1118 | return; |
| 1119 | } |
| 1120 | |
| 1121 | // Insert instrumentation if this is a back or split edge |
| 1122 | if( edge->getType() == BallLarusEdge::BACKEDGE || |
| 1123 | edge->getType() == BallLarusEdge::SPLITEDGE ) { |
| 1124 | BLInstrumentationEdge* top = |
| 1125 | (BLInstrumentationEdge*) edge->getPhonyRoot(); |
| 1126 | BLInstrumentationEdge* bottom = |
| 1127 | (BLInstrumentationEdge*) edge->getPhonyExit(); |
| 1128 | |
| 1129 | assert( top->isInitialization() && " Top phony edge did not" |
| 1130 | " contain a path number initialization."); |
| 1131 | assert( bottom->isCounterIncrement() && " Bottom phony edge" |
| 1132 | " did not contain a path counter increment."); |
| 1133 | |
| 1134 | // split edge has yet to be initialized |
| 1135 | if( !instrumentNode->getEndingPathNumber() ) { |
| 1136 | instrumentNode->setStartingPathNumber(createIncrementConstant(0,32)); |
| 1137 | instrumentNode->setEndingPathNumber(createIncrementConstant(0,32)); |
| 1138 | } |
| 1139 | |
| 1140 | BasicBlock::iterator insertPoint = atBeginning ? |
| 1141 | instrumentNode->getBlock()->getFirstNonPHI() : |
| 1142 | instrumentNode->getBlock()->getTerminator(); |
| 1143 | |
| 1144 | // add information from the bottom edge, if it exists |
| 1145 | if( bottom->getIncrement() ) { |
| 1146 | Value* newpn = |
| 1147 | BinaryOperator::Create(Instruction::Add, |
| 1148 | instrumentNode->getStartingPathNumber(), |
| 1149 | createIncrementConstant(bottom), |
| 1150 | "pathNumber", insertPoint); |
| 1151 | instrumentNode->setEndingPathNumber(newpn); |
| 1152 | } |
| 1153 | |
| 1154 | insertCounterIncrement(instrumentNode->getEndingPathNumber(), |
| 1155 | insertPoint, dag); |
| 1156 | |
| 1157 | if( atBeginning ) |
| 1158 | instrumentNode->setStartingPathNumber(createIncrementConstant(top)); |
| 1159 | |
| 1160 | instrumentNode->setEndingPathNumber(createIncrementConstant(top)); |
| 1161 | |
| 1162 | // Check for path counter increments |
| 1163 | if( top->isCounterIncrement() ) { |
| 1164 | insertCounterIncrement(instrumentNode->getEndingPathNumber(), |
| 1165 | instrumentNode->getBlock()->getTerminator(),dag); |
| 1166 | instrumentNode->setEndingPathNumber(0); |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | // Insert instrumentation if this is a normal edge |
| 1171 | else { |
| 1172 | BasicBlock::iterator insertPoint = atBeginning ? |
| 1173 | instrumentNode->getBlock()->getFirstNonPHI() : |
| 1174 | instrumentNode->getBlock()->getTerminator(); |
| 1175 | |
| 1176 | if( edge->isInitialization() ) { // initialize path number |
| 1177 | instrumentNode->setEndingPathNumber(createIncrementConstant(edge)); |
| 1178 | } else if( edge->getIncrement() ) {// increment path number |
| 1179 | Value* newpn = |
| 1180 | BinaryOperator::Create(Instruction::Add, |
| 1181 | instrumentNode->getStartingPathNumber(), |
| 1182 | createIncrementConstant(edge), |
| 1183 | "pathNumber", insertPoint); |
| 1184 | instrumentNode->setEndingPathNumber(newpn); |
| 1185 | |
| 1186 | if( atBeginning ) |
| 1187 | instrumentNode->setStartingPathNumber(newpn); |
| 1188 | } |
| 1189 | |
| 1190 | // Check for path counter increments |
| 1191 | if( edge->isCounterIncrement() ) { |
| 1192 | insertCounterIncrement(instrumentNode->getEndingPathNumber(), |
| 1193 | insertPoint, dag); |
| 1194 | instrumentNode->setEndingPathNumber(0); |
| 1195 | } |
| 1196 | } |
| 1197 | |
| 1198 | // Push it along |
| 1199 | if (nextSourceNode && instrumentNode->getEndingPathNumber()) |
| 1200 | pushValueIntoNode(instrumentNode, nextSourceNode); |
| 1201 | |
| 1202 | // Add all the successors |
| 1203 | for( BLEdgeIterator next = targetNode->succBegin(), |
| 1204 | end = targetNode->succEnd(); next != end; next++ ) { |
| 1205 | // So long as it is un-instrumented, add it to the list |
| 1206 | if( !((BLInstrumentationEdge*)(*next))->hasInstrumentation() ) |
| 1207 | insertInstrumentationStartingAt((BLInstrumentationEdge*)*next,dag); |
| 1208 | else |
| 1209 | DEBUG(dbgs() << " Edge " << *(BLInstrumentationEdge*)(*next) |
| 1210 | << " already instrumented.\n"); |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | // Inserts instrumentation according to the marked edges in dag. Phony edges |
| 1215 | // must be unlinked from the DAG, but accessible from the backedges. Dag |
| 1216 | // must have initializations, path number increments, and counter increments |
| 1217 | // present. |
| 1218 | // |
| 1219 | // Counter storage is created here. |
| 1220 | void PathProfiler::insertInstrumentation( |
| 1221 | BLInstrumentationDag& dag, Module &M) { |
| 1222 | |
| 1223 | BLInstrumentationEdge* exitRootEdge = |
| 1224 | (BLInstrumentationEdge*) dag.getExitRootEdge(); |
| 1225 | insertInstrumentationStartingAt(exitRootEdge, &dag); |
| 1226 | |
| 1227 | // Iterate through each call edge and apply the appropriate hash increment |
| 1228 | // and decrement functions |
| 1229 | BLEdgeVector callEdges = dag.getCallPhonyEdges(); |
| 1230 | for( BLEdgeIterator edge = callEdges.begin(), |
| 1231 | end = callEdges.end(); edge != end; edge++ ) { |
| 1232 | BLInstrumentationNode* node = |
| 1233 | (BLInstrumentationNode*)(*edge)->getSource(); |
| 1234 | BasicBlock::iterator insertPoint = node->getBlock()->getFirstNonPHI(); |
| 1235 | |
| 1236 | // Find the first function call |
| 1237 | while( ((Instruction&)(*insertPoint)).getOpcode() != Instruction::Call ) |
| 1238 | insertPoint++; |
| 1239 | |
| 1240 | DEBUG(dbgs() << "\nInstrumenting method call block '" |
| 1241 | << node->getBlock()->getNameStr() << "'\n"); |
| 1242 | DEBUG(dbgs() << " Path number initialized: " |
| 1243 | << ((node->getStartingPathNumber()) ? "yes" : "no") << "\n"); |
| 1244 | |
| 1245 | Value* newpn; |
| 1246 | if( node->getStartingPathNumber() ) { |
| 1247 | long inc = ((BLInstrumentationEdge*)(*edge))->getIncrement(); |
| 1248 | if ( inc ) |
| 1249 | newpn = BinaryOperator::Create(Instruction::Add, |
| 1250 | node->getStartingPathNumber(), |
| 1251 | createIncrementConstant(inc,32), |
| 1252 | "pathNumber", insertPoint); |
| 1253 | else |
| 1254 | newpn = node->getStartingPathNumber(); |
| 1255 | } else { |
| 1256 | newpn = (Value*)createIncrementConstant( |
| 1257 | ((BLInstrumentationEdge*)(*edge))->getIncrement(), 32); |
| 1258 | } |
| 1259 | |
| 1260 | insertCounterIncrement(newpn, insertPoint, &dag); |
| 1261 | insertCounterIncrement(newpn, node->getBlock()->getTerminator(), |
| 1262 | &dag, false); |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | // Entry point of the module |
| 1267 | void PathProfiler::runOnFunction(std::vector<Constant*> &ftInit, |
| 1268 | Function &F, Module &M) { |
| 1269 | // Build DAG from CFG |
| 1270 | BLInstrumentationDag dag = BLInstrumentationDag(F); |
| 1271 | dag.init(); |
| 1272 | |
| 1273 | // give each path a unique integer value |
| 1274 | dag.calculatePathNumbers(); |
| 1275 | |
| 1276 | // modify path increments to increase the efficiency |
| 1277 | // of instrumentation |
| 1278 | dag.calculateSpanningTree(); |
| 1279 | dag.calculateChordIncrements(); |
| 1280 | dag.pushInitialization(); |
| 1281 | dag.pushCounters(); |
| 1282 | dag.unlinkPhony(); |
| 1283 | |
| 1284 | // potentially generate .dot graph for the dag |
| 1285 | if (DotPathDag) |
| 1286 | dag.generateDotGraph (); |
| 1287 | |
| 1288 | // Should we store the information in an array or hash |
| 1289 | if( dag.getNumberOfPaths() <= HASH_THRESHHOLD ) { |
| 1290 | const Type* t = ArrayType::get(Type::getInt32Ty(*Context), |
| 1291 | dag.getNumberOfPaths()); |
| 1292 | |
| 1293 | dag.setCounterArray(new GlobalVariable(M, t, false, |
| 1294 | GlobalValue::InternalLinkage, |
| 1295 | Constant::getNullValue(t), "")); |
| 1296 | } |
| 1297 | |
| 1298 | insertInstrumentation(dag, M); |
| 1299 | |
| 1300 | // Add to global function reference table |
| 1301 | unsigned type; |
| 1302 | const Type* voidPtr = TypeBuilder<types::i<8>*, true>::get(*Context); |
| 1303 | |
| 1304 | if( dag.getNumberOfPaths() <= HASH_THRESHHOLD ) |
| 1305 | type = ProfilingArray; |
| 1306 | else |
| 1307 | type = ProfilingHash; |
| 1308 | |
| 1309 | std::vector<Constant*> entryArray(3); |
| 1310 | entryArray[0] = createIncrementConstant(type,32); |
| 1311 | entryArray[1] = createIncrementConstant(dag.getNumberOfPaths(),32); |
| 1312 | entryArray[2] = dag.getCounterArray() ? |
| 1313 | ConstantExpr::getBitCast(dag.getCounterArray(), voidPtr) : |
| 1314 | Constant::getNullValue(voidPtr); |
| 1315 | |
| 1316 | const StructType* at = ftEntryTypeBuilder::get(*Context); |
| 1317 | ConstantStruct* functionEntry = |
| 1318 | (ConstantStruct*)ConstantStruct::get(at, entryArray); |
| 1319 | ftInit.push_back(functionEntry); |
| 1320 | } |
| 1321 | |
| 1322 | // Output the bitcode if we want to observe instrumentation changess |
| 1323 | #define PRINT_MODULE dbgs() << \ |
| 1324 | "\n\n============= MODULE BEGIN ===============\n" << M << \ |
| 1325 | "\n============== MODULE END ================\n" |
| 1326 | |
| 1327 | bool PathProfiler::runOnModule(Module &M) { |
| 1328 | Context = &M.getContext(); |
| 1329 | |
| 1330 | DEBUG(dbgs() |
| 1331 | << "****************************************\n" |
| 1332 | << "****************************************\n" |
| 1333 | << "** **\n" |
| 1334 | << "** PATH PROFILING INSTRUMENTATION **\n" |
| 1335 | << "** **\n" |
| 1336 | << "****************************************\n" |
| 1337 | << "****************************************\n"); |
| 1338 | |
| 1339 | // No main, no instrumentation! |
| 1340 | Function *Main = M.getFunction("main"); |
| 1341 | |
| 1342 | // Using fortran? ... this kind of works |
| 1343 | if (!Main) |
| 1344 | Main = M.getFunction("MAIN__"); |
| 1345 | |
| 1346 | if (!Main) { |
| 1347 | errs() << "WARNING: cannot insert path profiling into a module" |
| 1348 | << " with no main function!\n"; |
| 1349 | return false; |
| 1350 | } |
| 1351 | |
| 1352 | BasicBlock::iterator insertPoint = Main->getEntryBlock().getFirstNonPHI(); |
| 1353 | |
| 1354 | llvmIncrementHashFunction = M.getOrInsertFunction( |
| 1355 | "llvm_increment_path_count", |
| 1356 | Type::getVoidTy(*Context), // return type |
| 1357 | Type::getInt32Ty(*Context), // function number |
| 1358 | Type::getInt32Ty(*Context), // path number |
| 1359 | NULL ); |
| 1360 | |
| 1361 | llvmDecrementHashFunction = M.getOrInsertFunction( |
| 1362 | "llvm_decrement_path_count", |
| 1363 | Type::getVoidTy(*Context), // return type |
| 1364 | Type::getInt32Ty(*Context), // function number |
| 1365 | Type::getInt32Ty(*Context), // path number |
| 1366 | NULL ); |
| 1367 | |
| 1368 | std::vector<Constant*> ftInit; |
| 1369 | unsigned functionNumber = 0; |
| 1370 | for (Module::iterator F = M.begin(), E = M.end(); F != E; F++) { |
| 1371 | if (F->isDeclaration()) |
| 1372 | continue; |
| 1373 | |
| 1374 | DEBUG(dbgs() << "Function: " << F->getNameStr() << "\n"); |
| 1375 | functionNumber++; |
| 1376 | |
| 1377 | // set function number |
| 1378 | currentFunctionNumber = functionNumber; |
| 1379 | runOnFunction(ftInit, *F, M); |
| 1380 | } |
| 1381 | |
| 1382 | const Type *t = ftEntryTypeBuilder::get(*Context); |
| 1383 | const ArrayType* ftArrayType = ArrayType::get(t, ftInit.size()); |
| 1384 | Constant* ftInitConstant = ConstantArray::get(ftArrayType, ftInit); |
| 1385 | |
| 1386 | DEBUG(dbgs() << " ftArrayType:" << *ftArrayType << "\n"); |
| 1387 | |
| 1388 | GlobalVariable* functionTable = |
| 1389 | new GlobalVariable(M, ftArrayType, false, GlobalValue::InternalLinkage, |
| 1390 | ftInitConstant, "functionPathTable"); |
| 1391 | const Type *eltType = ftArrayType->getTypeAtIndex((unsigned)0); |
| 1392 | InsertProfilingInitCall(Main, "llvm_start_path_profiling", functionTable, |
| 1393 | PointerType::getUnqual(eltType)); |
| 1394 | |
| 1395 | DEBUG(PRINT_MODULE); |
| 1396 | |
| 1397 | return true; |
| 1398 | } |
| 1399 | |
| 1400 | // If this edge is a critical edge, then inserts a node at this edge. |
| 1401 | // This edge becomes the first edge, and a new BallLarusEdge is created. |
| 1402 | // Returns true if the edge was split |
| 1403 | bool PathProfiler::splitCritical(BLInstrumentationEdge* edge, |
| 1404 | BLInstrumentationDag* dag) { |
| 1405 | unsigned succNum = edge->getSuccessorNumber(); |
| 1406 | BallLarusNode* sourceNode = edge->getSource(); |
| 1407 | BallLarusNode* targetNode = edge->getTarget(); |
| 1408 | BasicBlock* sourceBlock = sourceNode->getBlock(); |
| 1409 | BasicBlock* targetBlock = targetNode->getBlock(); |
| 1410 | |
| 1411 | if(sourceBlock == NULL || targetBlock == NULL |
| 1412 | || sourceNode->getNumberSuccEdges() <= 1 |
| 1413 | || targetNode->getNumberPredEdges() == 1 ) { |
| 1414 | return(false); |
| 1415 | } |
| 1416 | |
| 1417 | TerminatorInst* terminator = sourceBlock->getTerminator(); |
| 1418 | |
| 1419 | if( SplitCriticalEdge(terminator, succNum, this, false)) { |
| 1420 | BasicBlock* newBlock = terminator->getSuccessor(succNum); |
| 1421 | dag->splitUpdate(edge, newBlock); |
| 1422 | return(true); |
| 1423 | } else |
| 1424 | return(false); |
| 1425 | } |