72c454187b3114bbceb9a64569dbf7d4f2b5f222
[oota-llvm.git] / lib / Transforms / Instrumentation / TraceValues.cpp
1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
2 //
3 // Support for inserting LLVM code to print values at basic block and method
4 // exits.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Instrumentation/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/ConstantVals.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Method.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/StringExtras.h"
21 #include <sstream>
22 using std::vector;
23 using std::string;
24
25 namespace {
26   class InsertTraceCode : public MethodPass {
27     bool TraceBasicBlockExits, TraceMethodExits;
28     Method *PrintfMeth;
29   public:
30     InsertTraceCode(bool traceBasicBlockExits, bool traceMethodExits)
31       : TraceBasicBlockExits(traceBasicBlockExits), 
32         TraceMethodExits(traceMethodExits) {}
33     
34     // Add a prototype for printf if it is not already in the program.
35     //
36     bool doInitialization(Module *M);
37     
38     //--------------------------------------------------------------------------
39     // Function InsertCodeToTraceValues
40     // 
41     // Inserts tracing code for all live values at basic block and/or method
42     // exits as specified by `traceBasicBlockExits' and `traceMethodExits'.
43     //
44     static bool doit(Method *M, bool traceBasicBlockExits,
45                      bool traceMethodExits, Method *Printf);
46     
47     // runOnMethod - This method does the work.  Always successful.
48     //
49     bool runOnMethod(Method *M) {
50       return doit(M, TraceBasicBlockExits, TraceMethodExits, PrintfMeth);
51     }
52   };
53 } // end anonymous namespace
54
55
56 Pass *createTraceValuesPassForMethod() {       // Just trace methods
57   return new InsertTraceCode(false, true);
58 }
59
60 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and methods
61   return new InsertTraceCode(true, true);
62 }
63
64
65
66
67 // Add a prototype for printf if it is not already in the program.
68 //
69 bool InsertTraceCode::doInitialization(Module *M) {
70   SymbolTable *ST = M->getSymbolTable();
71   const Type *SBP = PointerType::get(Type::SByteTy);
72   const MethodType *MTy =
73     MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
74
75   if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
76     PrintfMeth = cast<Method>(Meth);
77     return false;
78   }
79
80   // Create a new method and add it to the module
81   PrintfMeth = new Method(MTy, false, "printf");
82   M->getMethodList().push_back(PrintfMeth);
83   return true;
84 }
85
86
87 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
88   // Create a constant internal string reference...
89   Constant *Init = ConstantArray::get(str);
90
91   // Create the global variable and record it in the module
92   // The GV will be renamed to a unique name if needed.
93   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
94                                           "trstr");
95   M->getGlobalList().push_back(GV);
96   return GV;
97 }
98
99
100 // 
101 // Check if this instruction has any uses outside its basic block,
102 // or if it used by either a Call or Return instruction.
103 // 
104 static inline bool LiveAtBBExit(const Instruction* I) {
105   const BasicBlock *BB = I->getParent();
106   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
107     if (const Instruction *UI = dyn_cast<Instruction>(*U))
108       if (UI->getParent() != BB || isa<ReturnInst>(UI))
109         return true;
110
111   return false;
112 }
113
114
115 static inline bool TraceThisOpCode(unsigned opCode) {
116   // Explicitly test for opCodes *not* to trace so that any new opcodes will
117   // be traced by default (VoidTy's are already excluded)
118   // 
119   return (opCode  < Instruction::FirstOtherOp &&
120           opCode != Instruction::Alloca &&
121           opCode != Instruction::PHINode &&
122           opCode != Instruction::Cast);
123 }
124
125
126 static bool ShouldTraceValue(const Instruction *I) {
127   return
128     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
129     TraceThisOpCode(I->getOpcode());
130 }
131
132 static string getPrintfCodeFor(const Value *V) {
133   if (V == 0) return "";
134   switch (V->getType()->getPrimitiveID()) {
135   case Type::BoolTyID:
136   case Type::UByteTyID: case Type::UShortTyID:
137   case Type::UIntTyID:  case Type::ULongTyID:
138   case Type::SByteTyID: case Type::ShortTyID:
139   case Type::IntTyID:   case Type::LongTyID:
140     return "%d";
141     
142   case Type::FloatTyID: case Type::DoubleTyID:
143     return "%g";
144
145   case Type::LabelTyID: case Type::PointerTyID:
146     return "%p";
147     
148   default:
149     assert(0 && "Illegal value to print out...");
150     return "";
151   }
152 }
153
154
155 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
156                             string Message, Method *Printf) {
157   // Escape Message by replacing all % characters with %% chars.
158   unsigned Offset = 0;
159   while ((Offset = Message.find('%', Offset)) != string::npos) {
160     Message.replace(Offset, 2, "%%");
161     Offset += 2;  // Skip over the new %'s
162   }
163
164   Module *Mod = BB->getParent()->getParent();
165
166   // Turn the marker string into a global variable...
167   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
168
169   // Turn the format string into an sbyte *
170   Instruction *GEP = 
171     new GetElementPtrInst(fmtVal,
172                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
173                           "trstr");
174   BBI = BB->getInstList().insert(BBI, GEP)+1;
175   
176   // Insert the first print instruction to print the string flag:
177   vector<Value*> PrintArgs;
178   PrintArgs.push_back(GEP);
179   if (V) PrintArgs.push_back(V);
180   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
181   BBI = BB->getInstList().insert(BBI, I)+1;
182 }
183                             
184
185 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
186                                    BasicBlock::iterator &BBI,
187                                    const string &Message, Method *Printf) {
188   std::ostringstream OutStr;
189   if (V) WriteAsOperand(OutStr, V);
190   InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
191 }
192
193
194 // Insert print instructions at the end of the basic block *bb
195 // for each value in valueVec[] that is live at the end of that basic block,
196 // or that is stored to memory in this basic block.
197 // If the value is stored to memory, we load it back before printing
198 // We also return all such loaded values in the vector valuesStoredInMethod
199 // for printing at the exit from the method.  (Note that in each invocation
200 // of the method, this will only get the last value stored for each static
201 // store instruction).
202 // *bb must be the block in which the value is computed;
203 // this is not checked here.
204 // 
205 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
206                                 vector<Instruction*> *valuesStoredInMethod) {
207   // Get an iterator to point to the insertion location, which is
208   // just before the terminator instruction.
209   // 
210   BasicBlock::iterator InsertPos = BB->end()-1;
211   assert((*InsertPos)->isTerminator());
212   
213   // If the terminator is a conditional branch, insert the trace code just
214   // before the instruction that computes the branch condition (just to
215   // avoid putting a call between the CC-setting instruction and the branch).
216   // Use laterInstrSet to mark instructions that come after the setCC instr
217   // because those cannot be traced at the location we choose.
218   // 
219   Instruction *SetCC = 0;
220   if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
221     if (!Branch->isUnconditional())
222       if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
223         if (I->getParent() == BB) {
224           SetCC = I;
225           while (*InsertPos != SetCC)
226             --InsertPos;        // Back up until we can insert before the setcc
227         }
228
229   // Copy all of the instructions into a vector to avoid problems with Setcc
230   const vector<Instruction*> Insts(BB->begin(), InsertPos);
231
232   std::ostringstream OutStr;
233   WriteAsOperand(OutStr, BB, false);
234   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
235
236   // Insert a print instruction for each value.
237   // 
238   for (vector<Instruction*>::const_iterator II = Insts.begin(),
239          IE = Insts.end(); II != IE; ++II) {
240     Instruction *I = *II;
241     if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
242       assert(valuesStoredInMethod &&
243              "Should not be printing a store instruction at method exit");
244       LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
245                                   "reload");
246       InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
247       valuesStoredInMethod->push_back(LI);
248     }
249     if (ShouldTraceValue(I))
250       InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf);
251   }
252 }
253
254 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
255   // Get an iterator to point to the insertion location
256   BasicBlock *BB = M->getEntryNode();
257   BasicBlock::iterator BBI = BB->begin();
258
259   std::ostringstream OutStr;
260   WriteAsOperand(OutStr, M, true);
261   InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
262
263   // Now print all the incoming arguments
264   const Method::ArgumentListType &argList = M->getArgumentList();
265   unsigned ArgNo = 0;
266   for (Method::ArgumentListType::const_iterator
267          I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
268     InsertVerbosePrintInst(*I, BB, BBI,
269                            "  Arg #" + utostr(ArgNo), Printf);
270   }
271 }
272
273
274 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
275   // Get an iterator to point to the insertion location
276   BasicBlock::iterator BBI = BB->end()-1;
277   ReturnInst *Ret = cast<ReturnInst>(*BBI);
278   
279   std::ostringstream OutStr;
280   WriteAsOperand(OutStr, BB->getParent(), true);
281   InsertPrintInst(0, BB, BBI, "LEAVING  METHOD: " + OutStr.str(), Printf);
282   
283   // print the return value, if any
284   if (BB->getParent()->getReturnType() != Type::VoidTy)
285     InsertPrintInst(Ret->getReturnValue(), BB, BBI, "  Returning: ", Printf);
286 }
287
288
289 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
290                            bool traceMethodEvents, Method *Printf) {
291   if (!traceBasicBlockExits && !traceMethodEvents)
292     return false;
293
294   vector<Instruction*> valuesStoredInMethod;
295   vector<BasicBlock*>  exitBlocks;
296
297   if (traceMethodEvents)
298     InsertCodeToShowMethodEntry(M, Printf);
299   
300   for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
301     BasicBlock *BB = *BI;
302     if (isa<ReturnInst>(BB->getTerminator()))
303       exitBlocks.push_back(BB); // record this as an exit block
304     
305     if (traceBasicBlockExits)
306       TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
307   }
308
309   if (traceMethodEvents)
310     for (unsigned i=0; i < exitBlocks.size(); ++i) {
311 #if 0
312       TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
313                           /*indent*/ 0, /*isMethodExit*/ true,
314                           /*valuesStoredInMethod*/ NULL);
315 #endif
316       InsertCodeToShowMethodExit(exitBlocks[i], Printf);
317     }
318
319   return true;
320 }