-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPathLogging.cpp
1655 lines (1352 loc) · 58 KB
/
PathLogging.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- PathProfiling.cpp - Inserts counters for path profiling ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass instruments functions for Ball-Larus path profiling. Ball-Larus
// profiling converts the CFG into a DAG by replacing backedges with edges
// from entry to the start block and from the end block to exit. The paths
// along the new DAG are enumrated, i.e. each path is given a path number.
// Edges are instrumented to increment the path number register, such that the
// path number register will equal the path number of the path taken at the
// exit.
//
// This file defines classes for building a CFG for use with different stages
// in the Ball-Larus path profiling instrumentation [Ball96]. The
// requirements are formatting the llvm CFG into the Ball-Larus DAG, path
// numbering, finding a spanning tree, moving increments from the spanning
// tree to chords.
//
// Terms:
// DAG - Directed Acyclic Graph.
// Ball-Larus DAG - A CFG with an entry node, an exit node, and backedges
// removed in the following manner. For every backedge
// v->w, insert edge ENTRY->w and edge v->EXIT.
// Path Number - The number corresponding to a specific path through a
// Ball-Larus DAG.
// Spanning Tree - A subgraph, S, is a spanning tree if S covers all
// vertices and is a tree.
// Chord - An edge not in the spanning tree.
//
// [Ball96]
// T. Ball and J. R. Larus. "Efficient Path Profiling."
// International Symposium on Microarchitecture, pages 46-57, 1996.
// http://portal.acm.org/citation.cfm?id=243857
//
// [Ball94]
// Thomas Ball. "Efficiently Counting Program Events with Support for
// On-line queries."
// ACM Transactions on Programmmg Languages and Systems, Vol 16, No 5,
// September 1994, Pages 1399-1410.
//===----------------------------------------------------------------------===//
#include <iostream>
#define DEBUG_TYPE "insert-path-logging"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Analysis/PathNumbering.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/TypeBuilder.h"
#include "llvm/Pass.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include <vector>
#include "llvm/PassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
//#define HASH_THRESHHOLD 100000
#define HASH_THRESHHOLD 0
using namespace llvm;
using namespace std;
static int64_t totalPaths;
static int64_t maxPaths;
namespace {
void InsertProfilingInitCall(Function *MainFn, const char *FnName,
GlobalValue *Array,
PointerType *arrayType) {
LLVMContext &Context = MainFn->getContext();
Type *ArgVTy =
PointerType::getUnqual(Type::getInt8PtrTy(Context));
PointerType *UIntPtr = arrayType ? arrayType :
Type::getInt32PtrTy(Context);
Module &M = *MainFn->getParent();
Constant *InitFn = M.getOrInsertFunction(FnName, Type::getInt32Ty(Context),
Type::getInt32Ty(Context),
ArgVTy, UIntPtr,
Type::getInt32Ty(Context),
(Type *)0);
// This could force argc and argv into programs that wouldn't otherwise have
// them, but instead we just pass null values in.
std::vector<Value*> Args(4);
Args[0] = Constant::getNullValue(Type::getInt32Ty(Context));
Args[1] = Constant::getNullValue(ArgVTy);
// Skip over any allocas in the entry block.
BasicBlock *Entry = MainFn->begin();
BasicBlock::iterator InsertPos = Entry->begin();
while (isa<AllocaInst>(InsertPos)) ++InsertPos;
std::vector<Constant*> GEPIndices(2,
Constant::getNullValue(Type::getInt32Ty(Context)));
unsigned NumElements = 0;
if (Array) {
Args[2] = ConstantExpr::getGetElementPtr(Array, GEPIndices);
NumElements =
cast<ArrayType>(Array->getType()->getElementType())->getNumElements();
} else {
// If this profiling instrumentation doesn't have a constant array, just
// pass null.
Args[2] = ConstantPointerNull::get(UIntPtr);
}
Args[3] = ConstantInt::get(Type::getInt32Ty(Context), NumElements);
CallInst *InitCall = CallInst::Create(InitFn, Args, "newargc", InsertPos);
// If argc or argv are not available in main, just pass null values in.
Function::arg_iterator AI;
switch (MainFn->arg_size()) {
default:
case 2:
AI = MainFn->arg_begin(); ++AI;
if (AI->getType() != ArgVTy) {
Instruction::CastOps opcode = CastInst::getCastOpcode(AI, false, ArgVTy,
false);
InitCall->setArgOperand(1,
CastInst::Create(opcode, AI, ArgVTy, "argv.cast", InitCall));
} else {
InitCall->setArgOperand(1, AI);
}
/* FALL THROUGH */
case 1:
AI = MainFn->arg_begin();
// If the program looked at argc, have it look at the return value of the
// init call instead.
if (!AI->getType()->isIntegerTy(32)) {
Instruction::CastOps opcode;
if (!AI->use_empty()) {
opcode = CastInst::getCastOpcode(InitCall, true, AI->getType(), true);
AI->replaceAllUsesWith(
CastInst::Create(opcode, InitCall, AI->getType(), "", InsertPos));
}
opcode = CastInst::getCastOpcode(AI, true,
Type::getInt32Ty(Context), true);
InitCall->setArgOperand(0,
CastInst::Create(opcode, AI, Type::getInt32Ty(Context),
"argc.cast", InitCall));
} else {
AI->replaceAllUsesWith(InitCall);
InitCall->setArgOperand(0, AI);
}
case 0: break;
}
}
void IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
GlobalValue *CounterArray, bool beginning) {
// Insert the increment after any alloca or PHI instructions...
BasicBlock::iterator InsertPos = beginning ? BB->getFirstInsertionPt() :
BB->getTerminator();
while (isa<AllocaInst>(InsertPos))
++InsertPos;
LLVMContext &Context = BB->getContext();
// Create the getelementptr constant expression
std::vector<Constant*> Indices(2);
Indices[0] = Constant::getNullValue(Type::getInt32Ty(Context));
Indices[1] = ConstantInt::get(Type::getInt32Ty(Context), CounterNum);
Constant *ElementPtr =
ConstantExpr::getGetElementPtr(CounterArray, Indices);
// Load, increment and store the value back.
Value *OldVal = new LoadInst(ElementPtr, "OldFuncCounter", InsertPos);
Value *NewVal = BinaryOperator::Create(Instruction::Add, OldVal,
ConstantInt::get(Type::getInt32Ty(Context), 1),
"NewFuncCounter", InsertPos);
new StoreInst(NewVal, ElementPtr, InsertPos);
}
void InsertProfilingShutdownCall(Function *Callee, Module *Mod) {
// llvm.global_dtors is an array of type { i32, void ()* }. Prepare those
// types.
Type *GlobalDtorElems[2] = {
Type::getInt32Ty(Mod->getContext()),
FunctionType::get(Type::getVoidTy(Mod->getContext()), false)->getPointerTo()
};
StructType *GlobalDtorElemTy =
StructType::get(Mod->getContext(), GlobalDtorElems, false);
// Construct the new element we'll be adding.
Constant *Elem[2] = {
ConstantInt::get(Type::getInt32Ty(Mod->getContext()), 65535),
ConstantExpr::getBitCast(Callee, GlobalDtorElems[1])
};
// If llvm.global_dtors exists, make a copy of the things in its list and
// delete it, to replace it with one that has a larger array type.
std::vector<Constant *> dtors;
if (GlobalVariable *GlobalDtors = Mod->getNamedGlobal("llvm.global_dtors")) {
if (ConstantArray *InitList =
dyn_cast<ConstantArray>(GlobalDtors->getInitializer())) {
for (unsigned i = 0, e = InitList->getType()->getNumElements();
i != e; ++i)
dtors.push_back(cast<Constant>(InitList->getOperand(i)));
}
GlobalDtors->eraseFromParent();
}
// Build up llvm.global_dtors with our new item in it.
GlobalVariable *GlobalDtors = new GlobalVariable(
*Mod, ArrayType::get(GlobalDtorElemTy, 1), false,
GlobalValue::AppendingLinkage, NULL, "llvm.global_dtors");
dtors.push_back(ConstantStruct::get(GlobalDtorElemTy, Elem));
GlobalDtors->setInitializer(ConstantArray::get(
cast<ArrayType>(GlobalDtors->getType()->getElementType()), dtors));
}
} // namespace <anon>
namespace {
class BLInstrumentationNode;
class BLInstrumentationEdge;
class BLInstrumentationDag;
// ---------------------------------------------------------------------------
// BLInstrumentationNode extends BallLarusNode with member used by the
// instrumentation algortihms.
// ---------------------------------------------------------------------------
class BLInstrumentationNode : public BallLarusNode {
public:
// Creates a new BLInstrumentationNode from a BasicBlock.
BLInstrumentationNode(BasicBlock* BB);
// Get/sets the Value corresponding to the pathNumber register,
// constant or phinode. Used by the instrumentation code to remember
// path number Values.
Value* getStartingPathNumber();
void setStartingPathNumber(Value* pathNumber);
Value* getEndingPathNumber();
void setEndingPathNumber(Value* pathNumber);
// Get/set the PHINode Instruction for this node.
PHINode* getPathPHI();
void setPathPHI(PHINode* pathPHI);
private:
Value* _startingPathNumber; // The Value for the current pathNumber.
Value* _endingPathNumber; // The Value for the current pathNumber.
PHINode* _pathPHI; // The PHINode for current pathNumber.
};
// --------------------------------------------------------------------------
// BLInstrumentationEdge extends BallLarusEdge with data about the
// instrumentation that will end up on each edge.
// --------------------------------------------------------------------------
class BLInstrumentationEdge : public BallLarusEdge {
public:
BLInstrumentationEdge(BLInstrumentationNode* source,
BLInstrumentationNode* target);
// Sets the target node of this edge. Required to split edges.
void setTarget(BallLarusNode* node);
// Get/set whether edge is in the spanning tree.
bool isInSpanningTree() const;
void setIsInSpanningTree(bool isInSpanningTree);
// Get/ set whether this edge will be instrumented with a path number
// initialization.
bool isInitialization() const;
void setIsInitialization(bool isInitialization);
// Get/set whether this edge will be instrumented with a path counter
// increment. Notice this is incrementing the path counter
// corresponding to the path number register. The path number
// increment is determined by getIncrement().
bool isCounterIncrement() const;
void setIsCounterIncrement(bool isCounterIncrement);
// Get/set the path number increment that this edge will be instrumented
// with. This is distinct from the path counter increment and the
// weight. The counter increment counts the number of executions of
// some path, whereas the path number keeps track of which path number
// the program is on.
long getIncrement() const;
void setIncrement(long increment);
// Get/set whether the edge has been instrumented.
bool hasInstrumentation();
void setHasInstrumentation(bool hasInstrumentation);
// Returns the successor number of this edge in the source.
unsigned getSuccessorNumber();
private:
// The increment that the code will be instrumented with.
long long _increment;
// Whether this edge is in the spanning tree.
bool _isInSpanningTree;
// Whether this edge is an initialiation of the path number.
bool _isInitialization;
// Whether this edge is a path counter increment.
bool _isCounterIncrement;
// Whether this edge has been instrumented.
bool _hasInstrumentation;
};
// ---------------------------------------------------------------------------
// BLInstrumentationDag extends BallLarusDag with algorithms that
// determine where instrumentation should be placed.
// ---------------------------------------------------------------------------
class BLInstrumentationDag : public BallLarusDag {
public:
BLInstrumentationDag(Function &F);
// Returns the Exit->Root edge. This edge is required for creating
// directed cycles in the algorithm for moving instrumentation off of
// the spanning tree
BallLarusEdge* getExitRootEdge();
// Returns an array of phony edges which mark those nodes
// with function calls
BLEdgeVector getCallPhonyEdges();
// Gets/sets the path counter array
GlobalVariable* getCounterArray();
void setCounterArray(GlobalVariable* c);
// Calculates the increments for the chords, thereby removing
// instrumentation from the spanning tree edges. Implementation is based
// on the algorithm in Figure 4 of [Ball94]
void calculateChordIncrements();
// Updates the state when an edge has been split
void splitUpdate(BLInstrumentationEdge* formerEdge, BasicBlock* newBlock);
// Calculates a spanning tree of the DAG ignoring cycles. Whichever
// edges are in the spanning tree will not be instrumented, but this
// implementation does not try to minimize the instrumentation overhead
// by trying to find hot edges.
void calculateSpanningTree();
// Pushes initialization further down in order to group the first
// increment and initialization.
void pushInitialization();
// Pushes the path counter increments up in order to group the last path
// number increment.
void pushCounters();
// Removes phony edges from the successor list of the source, and the
// predecessor list of the target.
void unlinkPhony();
// Generate dot graph for the function
void generateDotGraph();
protected:
// BLInstrumentationDag creates BLInstrumentationNode objects in this
// method overriding the creation of BallLarusNode objects.
//
// Allows subclasses to determine which type of Node is created.
// Override this method to produce subclasses of BallLarusNode if
// necessary.
virtual BallLarusNode* createNode(BasicBlock* BB);
// BLInstrumentationDag create BLInstrumentationEdges.
//
// Allows subclasses to determine which type of Edge is created.
// Override this method to produce subclasses of BallLarusEdge if
// necessary. Parameters source and target will have been created by
// createNode and can be cast to the subclass of BallLarusNode*
// returned by createNode.
virtual BallLarusEdge* createEdge(
BallLarusNode* source, BallLarusNode* target, unsigned edgeNumber);
private:
BLEdgeVector _treeEdges; // All edges in the spanning tree.
BLEdgeVector _chordEdges; // All edges not in the spanning tree.
GlobalVariable* _counterArray; // Array to store path counters
// Removes the edge from the appropriate predecessor and successor lists.
void unlinkEdge(BallLarusEdge* edge);
// Makes an edge part of the spanning tree.
void makeEdgeSpanning(BLInstrumentationEdge* edge);
// Pushes initialization and calls itself recursively.
void pushInitializationFromEdge(BLInstrumentationEdge* edge);
// Pushes path counter increments up recursively.
void pushCountersFromEdge(BLInstrumentationEdge* edge);
// Depth first algorithm for determining the chord increments.f
void calculateChordIncrementsDfs(
long weight, BallLarusNode* v, BallLarusEdge* e);
// Determines the relative direction of two edges.
int calculateChordIncrementsDir(BallLarusEdge* e, BallLarusEdge* f);
};
// ---------------------------------------------------------------------------
// PathProfiler is a module pass which instruments path profiling instructions
// ---------------------------------------------------------------------------
class PathProfiler : public ModulePass {
private:
// Current context for multi threading support.
LLVMContext* Context;
// Which function are we currently instrumenting
unsigned currentFunctionNumber;
// The function prototype in the profiling runtime for incrementing a
// single path counter in a hash table.
Constant* llvmIncrementHashFunction;
Constant* llvmDecrementHashFunction;
// Instruments each function with path profiling. 'main' is instrumented
// with code to save the profile to disk.
bool runOnModule(Module &M);
// Analyzes the function for Ball-Larus path profiling, and inserts code.
void runOnFunction(std::vector<Constant*> &ftInit, Function &F, Module &M);
// Creates an increment constant representing incr.
ConstantInt* createIncrementConstant(long incr, int bitsize);
// Creates an increment constant representing the value in
// edge->getIncrement().
ConstantInt* createIncrementConstant(BLInstrumentationEdge* edge);
// Finds the insertion point after pathNumber in block. PathNumber may
// be NULL.
BasicBlock::iterator getInsertionPoint(
BasicBlock* block, Value* pathNumber);
// Inserts source's pathNumber Value* into target. Target may or may not
// have multiple predecessors, and may or may not have its phiNode
// initalized.
void pushValueIntoNode(
BLInstrumentationNode* source, BLInstrumentationNode* target);
// Inserts source's pathNumber Value* into the appropriate slot of
// target's phiNode.
void pushValueIntoPHI(
BLInstrumentationNode* target, BLInstrumentationNode* source);
// The Value* in node, oldVal, is updated with a Value* correspodning to
// oldVal + addition.
void insertNumberIncrement(BLInstrumentationNode* node, Value* addition,
bool atBeginning);
// Creates a counter increment in the given node. The Value* in node is
// taken as the index into a hash table.
void insertCounterIncrement(
Value* incValue,
BasicBlock::iterator insertPoint,
BLInstrumentationDag* dag,
Function& F,
bool increment = true);
// A PHINode is created in the node, and its values initialized to -1U.
void preparePHI(BLInstrumentationNode* node);
// Inserts instrumentation for the given edge
//
// Pre: The edge's source node has pathNumber set if edge is non zero
// path number increment.
//
// Post: Edge's target node has a pathNumber set to the path number Value
// corresponding to the value of the path register after edge's
// execution.
void insertInstrumentationStartingAt(
BLInstrumentationEdge* edge,
BLInstrumentationDag* dag,
Function& F);
// If this edge is a critical edge, then inserts a node at this edge.
// This edge becomes the first edge, and a new BallLarusEdge is created.
bool splitCritical(BLInstrumentationEdge* edge, BLInstrumentationDag* dag);
// Inserts instrumentation according to the marked edges in dag. Phony
// edges must be unlinked from the DAG, but accessible from the
// backedges. Dag must have initializations, path number increments, and
// counter increments present.
//
// Counter storage is created here.
void insertInstrumentation( BLInstrumentationDag& dag, Function& F, Module &M);
public:
static char ID; // Pass identification, replacement for typeid
PathProfiler() : ModulePass(ID) {
initializePathProfilerPass(*PassRegistry::getPassRegistry());
}
virtual const char *getPassName() const {
return "Path Logger";
}
};
} // end anonymous namespace
// Should we print the dot-graphs
static cl::opt<bool> DotPathDag("path-logging-pathdag", cl::Hidden,
cl::desc("Output the path profiling DAG for each function."));
// Register the path profiler as a pass
char PathProfiler::ID = 0;
INITIALIZE_PASS(PathProfiler, "insert-path-logging",
"Insert instrumentation for Ball-Larus path profiling",
false, false)
static void registerMyPass(const PassManagerBuilder &,
PassManagerBase &PM) {
PM.add(new PathProfiler());
}
static RegisterStandardPasses
RegisterMyPass(PassManagerBuilder::EP_OptimizerLast,
registerMyPass);
ModulePass *llvm::createPathProfilerPass() { return new PathProfiler(); }
namespace llvm {
class PathProfilingFunctionTable {};
// Type for global array storing references to hashes or arrays
template<bool xcompile> class TypeBuilder<PathProfilingFunctionTable,
xcompile> {
public:
static StructType *get(LLVMContext& C) {
return( StructType::get(
TypeBuilder<types::i<32>, xcompile>::get(C), // type
TypeBuilder<types::i<32>, xcompile>::get(C), // array size
TypeBuilder<types::i<8>*, xcompile>::get(C), // array/hash ptr
NULL));
}
};
typedef TypeBuilder<PathProfilingFunctionTable, true>
ftEntryTypeBuilder;
// BallLarusEdge << operator overloading
raw_ostream& operator<<(raw_ostream& os,
const BLInstrumentationEdge& edge)
LLVM_ATTRIBUTE_USED;
raw_ostream& operator<<(raw_ostream& os,
const BLInstrumentationEdge& edge) {
os << "[" << edge.getSource()->getName() << " -> "
<< edge.getTarget()->getName() << "] init: "
<< (edge.isInitialization() ? "yes" : "no")
<< " incr:" << edge.getIncrement() << " cinc: "
<< (edge.isCounterIncrement() ? "yes" : "no");
return(os);
}
}
// Creates a new BLInstrumentationNode from a BasicBlock.
BLInstrumentationNode::BLInstrumentationNode(BasicBlock* BB) :
BallLarusNode(BB),
_startingPathNumber(NULL), _endingPathNumber(NULL), _pathPHI(NULL) {}
// Constructor for BLInstrumentationEdge.
BLInstrumentationEdge::BLInstrumentationEdge(BLInstrumentationNode* source,
BLInstrumentationNode* target)
: BallLarusEdge(source, target, 0),
_increment(0), _isInSpanningTree(false), _isInitialization(false),
_isCounterIncrement(false), _hasInstrumentation(false) {}
// Sets the target node of this edge. Required to split edges.
void BLInstrumentationEdge::setTarget(BallLarusNode* node) {
_target = node;
}
// Returns whether this edge is in the spanning tree.
bool BLInstrumentationEdge::isInSpanningTree() const {
return(_isInSpanningTree);
}
// Sets whether this edge is in the spanning tree.
void BLInstrumentationEdge::setIsInSpanningTree(bool isInSpanningTree) {
_isInSpanningTree = isInSpanningTree;
}
// Returns whether this edge will be instrumented with a path number
// initialization.
bool BLInstrumentationEdge::isInitialization() const {
return(_isInitialization);
}
// Sets whether this edge will be instrumented with a path number
// initialization.
void BLInstrumentationEdge::setIsInitialization(bool isInitialization) {
_isInitialization = isInitialization;
}
// Returns whether this edge will be instrumented with a path counter
// increment. Notice this is incrementing the path counter
// corresponding to the path number register. The path number
// increment is determined by getIncrement().
bool BLInstrumentationEdge::isCounterIncrement() const {
return(_isCounterIncrement);
}
// Sets whether this edge will be instrumented with a path counter
// increment.
void BLInstrumentationEdge::setIsCounterIncrement(bool isCounterIncrement) {
_isCounterIncrement = isCounterIncrement;
}
// Gets the path number increment that this edge will be instrumented
// with. This is distinct from the path counter increment and the
// weight. The counter increment is counts the number of executions of
// some path, whereas the path number keeps track of which path number
// the program is on.
long BLInstrumentationEdge::getIncrement() const {
return(_increment);
}
// Set whether this edge will be instrumented with a path number
// increment.
void BLInstrumentationEdge::setIncrement(long increment) {
_increment = increment;
}
// True iff the edge has already been instrumented.
bool BLInstrumentationEdge::hasInstrumentation() {
return(_hasInstrumentation);
}
// Set whether this edge has been instrumented.
void BLInstrumentationEdge::setHasInstrumentation(bool hasInstrumentation) {
_hasInstrumentation = hasInstrumentation;
}
// Returns the successor number of this edge in the source.
unsigned BLInstrumentationEdge::getSuccessorNumber() {
BallLarusNode* sourceNode = getSource();
BallLarusNode* targetNode = getTarget();
BasicBlock* source = sourceNode->getBlock();
BasicBlock* target = targetNode->getBlock();
if(source == NULL || target == NULL)
return(0);
TerminatorInst* terminator = source->getTerminator();
unsigned i;
for(i=0; i < terminator->getNumSuccessors(); i++) {
if(terminator->getSuccessor(i) == target)
break;
}
return(i);
}
// BLInstrumentationDag constructor initializes a DAG for the given Function.
BLInstrumentationDag::BLInstrumentationDag(Function &F) : BallLarusDag(F),
_counterArray(0) {
}
// Returns the Exit->Root edge. This edge is required for creating
// directed cycles in the algorithm for moving instrumentation off of
// the spanning tree
BallLarusEdge* BLInstrumentationDag::getExitRootEdge() {
BLEdgeIterator erEdge = getExit()->succBegin();
return(*erEdge);
}
BLEdgeVector BLInstrumentationDag::getCallPhonyEdges () {
BLEdgeVector callEdges;
for( BLEdgeIterator edge = _edges.begin(), end = _edges.end();
edge != end; edge++ ) {
if( (*edge)->getType() == BallLarusEdge::CALLEDGE_PHONY )
callEdges.push_back(*edge);
}
return callEdges;
}
// Gets the path counter array
GlobalVariable* BLInstrumentationDag::getCounterArray() {
return _counterArray;
}
void BLInstrumentationDag::setCounterArray(GlobalVariable* c) {
_counterArray = c;
}
// Calculates the increment for the chords, thereby removing
// instrumentation from the spanning tree edges. Implementation is based on
// the algorithm in Figure 4 of [Ball94]
void BLInstrumentationDag::calculateChordIncrements() {
calculateChordIncrementsDfs(0, getRoot(), NULL);
BLInstrumentationEdge* chord;
for(BLEdgeIterator chordEdge = _chordEdges.begin(),
end = _chordEdges.end(); chordEdge != end; chordEdge++) {
chord = (BLInstrumentationEdge*) *chordEdge;
chord->setIncrement(chord->getIncrement() + chord->getWeight());
}
}
// Updates the state when an edge has been split
void BLInstrumentationDag::splitUpdate(BLInstrumentationEdge* formerEdge,
BasicBlock* newBlock) {
BallLarusNode* oldTarget = formerEdge->getTarget();
BallLarusNode* newNode = addNode(newBlock);
formerEdge->setTarget(newNode);
newNode->addPredEdge(formerEdge);
DEBUG(dbgs() << " Edge split: " << *formerEdge << "\n");
oldTarget->removePredEdge(formerEdge);
BallLarusEdge* newEdge = addEdge(newNode, oldTarget,0);
if( formerEdge->getType() == BallLarusEdge::BACKEDGE ||
formerEdge->getType() == BallLarusEdge::SPLITEDGE) {
newEdge->setType(formerEdge->getType());
newEdge->setPhonyRoot(formerEdge->getPhonyRoot());
newEdge->setPhonyExit(formerEdge->getPhonyExit());
formerEdge->setType(BallLarusEdge::NORMAL);
formerEdge->setPhonyRoot(NULL);
formerEdge->setPhonyExit(NULL);
}
}
// Calculates a spanning tree of the DAG ignoring cycles. Whichever
// edges are in the spanning tree will not be instrumented, but this
// implementation does not try to minimize the instrumentation overhead
// by trying to find hot edges.
void BLInstrumentationDag::calculateSpanningTree() {
std::stack<BallLarusNode*> dfsStack;
for(BLNodeIterator nodeIt = _nodes.begin(), end = _nodes.end();
nodeIt != end; nodeIt++) {
(*nodeIt)->setColor(BallLarusNode::WHITE);
}
dfsStack.push(getRoot());
while(dfsStack.size() > 0) {
BallLarusNode* node = dfsStack.top();
dfsStack.pop();
if(node->getColor() == BallLarusNode::WHITE)
continue;
BallLarusNode* nextNode;
bool forward = true;
BLEdgeIterator succEnd = node->succEnd();
node->setColor(BallLarusNode::WHITE);
// first iterate over successors then predecessors
for(BLEdgeIterator edge = node->succBegin(), predEnd = node->predEnd();
edge != predEnd; edge++) {
if(edge == succEnd) {
edge = node->predBegin();
forward = false;
}
// Ignore split edges
if ((*edge)->getType() == BallLarusEdge::SPLITEDGE)
continue;
nextNode = forward? (*edge)->getTarget(): (*edge)->getSource();
if(nextNode->getColor() != BallLarusNode::WHITE) {
nextNode->setColor(BallLarusNode::WHITE);
makeEdgeSpanning((BLInstrumentationEdge*)(*edge));
}
}
}
for(BLEdgeIterator edge = _edges.begin(), end = _edges.end();
edge != end; edge++) {
BLInstrumentationEdge* instEdge = (BLInstrumentationEdge*) (*edge);
// safe since createEdge is overriden
if(!instEdge->isInSpanningTree() && (*edge)->getType()
!= BallLarusEdge::SPLITEDGE)
_chordEdges.push_back(instEdge);
}
}
// Pushes initialization further down in order to group the first
// increment and initialization.
void BLInstrumentationDag::pushInitialization() {
BLInstrumentationEdge* exitRootEdge =
(BLInstrumentationEdge*) getExitRootEdge();
exitRootEdge->setIsInitialization(true);
pushInitializationFromEdge(exitRootEdge);
}
// Pushes the path counter increments up in order to group the last path
// number increment.
void BLInstrumentationDag::pushCounters() {
BLInstrumentationEdge* exitRootEdge =
(BLInstrumentationEdge*) getExitRootEdge();
exitRootEdge->setIsCounterIncrement(true);
pushCountersFromEdge(exitRootEdge);
}
// Removes phony edges from the successor list of the source, and the
// predecessor list of the target.
void BLInstrumentationDag::unlinkPhony() {
BallLarusEdge* edge;
for(BLEdgeIterator next = _edges.begin(),
end = _edges.end(); next != end; next++) {
edge = (*next);
if( edge->getType() == BallLarusEdge::BACKEDGE_PHONY ||
edge->getType() == BallLarusEdge::SPLITEDGE_PHONY ||
edge->getType() == BallLarusEdge::CALLEDGE_PHONY ) {
unlinkEdge(edge);
}
}
}
// Generate a .dot graph to represent the DAG and pathNumbers
void BLInstrumentationDag::generateDotGraph() {
std::string errorInfo;
std::string functionName = getFunction().getName().str();
std::string filename = "pathdag." + functionName + ".dot";
DEBUG (dbgs() << "Writing '" << filename << "'...\n");
raw_fd_ostream dotFile(filename.c_str(), errorInfo);
if (!errorInfo.empty()) {
errs() << "Error opening '" << filename.c_str() <<"' for writing!";
errs() << "\n";
return;
}
dotFile << "digraph " << functionName << " {\n";
for( BLEdgeIterator edge = _edges.begin(), end = _edges.end();
edge != end; edge++) {
std::string sourceName = (*edge)->getSource()->getName();
std::string targetName = (*edge)->getTarget()->getName();
dotFile << "\t\"" << sourceName.c_str() << "\" -> \""
<< targetName.c_str() << "\" ";
long inc = ((BLInstrumentationEdge*)(*edge))->getIncrement();
switch( (*edge)->getType() ) {
case BallLarusEdge::NORMAL:
dotFile << "[label=" << inc << "] [color=black];\n";
break;
case BallLarusEdge::BACKEDGE:
dotFile << "[color=cyan];\n";
break;
case BallLarusEdge::BACKEDGE_PHONY:
dotFile << "[label=" << inc
<< "] [color=blue];\n";
break;
case BallLarusEdge::SPLITEDGE:
dotFile << "[color=violet];\n";
break;
case BallLarusEdge::SPLITEDGE_PHONY:
dotFile << "[label=" << inc << "] [color=red];\n";
break;
case BallLarusEdge::CALLEDGE_PHONY:
dotFile << "[label=" << inc << "] [color=green];\n";
break;
}
}
dotFile << "}\n";
}
// Allows subclasses to determine which type of Node is created.
// Override this method to produce subclasses of BallLarusNode if
// necessary. The destructor of BallLarusDag will call free on each pointer
// created.
BallLarusNode* BLInstrumentationDag::createNode(BasicBlock* BB) {
return( new BLInstrumentationNode(BB) );
}
// Allows subclasses to determine which type of Edge is created.
// Override this method to produce subclasses of BallLarusEdge if
// necessary. The destructor of BallLarusDag will call free on each pointer
// created.
BallLarusEdge* BLInstrumentationDag::createEdge(BallLarusNode* source,
BallLarusNode* target, unsigned edgeNumber) {
// One can cast from BallLarusNode to BLInstrumentationNode since createNode
// is overriden to produce BLInstrumentationNode.
return( new BLInstrumentationEdge((BLInstrumentationNode*)source,
(BLInstrumentationNode*)target) );
}
// Sets the Value corresponding to the pathNumber register, constant,
// or phinode. Used by the instrumentation code to remember path
// number Values.
Value* BLInstrumentationNode::getStartingPathNumber(){
return(_startingPathNumber);
}
// Sets the Value of the pathNumber. Used by the instrumentation code.
void BLInstrumentationNode::setStartingPathNumber(Value* pathNumber) {
DEBUG(dbgs() << " SPN-" << getName() << " <-- " << (pathNumber ?
pathNumber->getName() :
"unused") << "\n");
_startingPathNumber = pathNumber;
}
Value* BLInstrumentationNode::getEndingPathNumber(){
return(_endingPathNumber);
}
void BLInstrumentationNode::setEndingPathNumber(Value* pathNumber) {
DEBUG(dbgs() << " EPN-" << getName() << " <-- "
<< (pathNumber ? pathNumber->getName() : "unused") << "\n");
_endingPathNumber = pathNumber;
}
// Get the PHINode Instruction for this node. Used by instrumentation
// code.
PHINode* BLInstrumentationNode::getPathPHI() {
return(_pathPHI);
}
// Set the PHINode Instruction for this node. Used by instrumentation
// code.
void BLInstrumentationNode::setPathPHI(PHINode* pathPHI) {
_pathPHI = pathPHI;
}
// Removes the edge from the appropriate predecessor and successor
// lists.
void BLInstrumentationDag::unlinkEdge(BallLarusEdge* edge) {
if(edge == getExitRootEdge())
DEBUG(dbgs() << " Removing exit->root edge\n");
edge->getSource()->removeSuccEdge(edge);
edge->getTarget()->removePredEdge(edge);
}
// Makes an edge part of the spanning tree.
void BLInstrumentationDag::makeEdgeSpanning(BLInstrumentationEdge* edge) {
edge->setIsInSpanningTree(true);
_treeEdges.push_back(edge);
}
// Pushes initialization and calls itself recursively.
void BLInstrumentationDag::pushInitializationFromEdge(
BLInstrumentationEdge* edge) {
BallLarusNode* target;
target = edge->getTarget();
if( target->getNumberPredEdges() > 1 || target == getExit() ) {
return;
} else {
for(BLEdgeIterator next = target->succBegin(),
end = target->succEnd(); next != end; next++) {
BLInstrumentationEdge* intoEdge = (BLInstrumentationEdge*) *next;
// Skip split edges
if (intoEdge->getType() == BallLarusEdge::SPLITEDGE)
continue;
intoEdge->setIncrement(intoEdge->getIncrement() +
edge->getIncrement());