Use the new interface, simplifies code
[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 function
4 // exits.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Instrumentation.h"
9 #include "llvm/Constants.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Module.h"
15 #include "llvm/Pass.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "Support/CommandLine.h"
18 #include "Support/StringExtras.h"
19 #include <algorithm>
20 #include <sstream>
21 using std::vector;
22 using std::string;
23
24 static cl::opt<bool>
25 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
26                   cl::desc("Disable pointer hashing in the -trace or -tracem "
27                            "passes"));
28
29 static cl::list<string>
30 TraceFuncNames("tracefunc", cl::desc("Only trace specific functions in the "
31                                      "-trace or -tracem passes"),
32                cl::value_desc("function"), cl::Hidden);
33
34 static void TraceValuesAtBBExit(BasicBlock *BB,
35                                 Function *Printf, Function* HashPtrToSeqNum,
36                                 vector<Instruction*> *valuesStoredInFunction);
37
38 // We trace a particular function if no functions to trace were specified
39 // or if the function is in the specified list.
40 // 
41 inline static bool
42 TraceThisFunction(Function &F)
43 {
44   if (TraceFuncNames.empty()) return true;
45
46   return std::find(TraceFuncNames.begin(), TraceFuncNames.end(), F.getName())
47                   != TraceFuncNames.end();
48 }
49
50
51 namespace {
52   struct ExternalFuncs {
53     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
54     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
55     void doInitialization(Module &M); // Add prototypes for external functions
56   };
57   
58   class InsertTraceCode : public FunctionPass {
59   protected:
60     ExternalFuncs externalFuncs;
61   public:
62     
63     // Add a prototype for runtime functions not already in the program.
64     //
65     bool doInitialization(Module &M);
66     
67     //--------------------------------------------------------------------------
68     // Function InsertCodeToTraceValues
69     // 
70     // Inserts tracing code for all live values at basic block and/or function
71     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
72     //
73     bool doit(Function *M);
74
75     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
76
77     // runOnFunction - This method does the work.
78     //
79     bool runOnFunction(Function &F);
80
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.setPreservesCFG();
83     }
84   };
85
86   struct FunctionTracer : public InsertTraceCode {
87     // Ignore basic blocks here...
88     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
89   };
90
91   struct BasicBlockTracer : public InsertTraceCode {
92     // Trace basic blocks here...
93     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
94       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
95                           externalFuncs.HashPtrFunc, &VI);
96     }
97   };
98
99   // Register the passes...
100   RegisterOpt<FunctionTracer>  X("tracem","Insert Function trace code only");
101   RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
102 } // end anonymous namespace
103
104
105 Pass *createTraceValuesPassForFunction() {     // Just trace functions
106   return new FunctionTracer();
107 }
108
109 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
110   return new BasicBlockTracer();
111 }
112
113
114 // Add a prototype for external functions used by the tracing code.
115 //
116 void ExternalFuncs::doInitialization(Module &M) {
117   const Type *SBP = PointerType::get(Type::SByteTy);
118   const FunctionType *MTy =
119     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
120   PrintfFunc = M.getOrInsertFunction("printf", MTy);
121
122   // uint (sbyte*)
123   HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", Type::UIntTy, SBP,
124                                       0);
125   
126   // void (sbyte*)
127   ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", 
128                                          Type::VoidTy, SBP, 0);
129   RecordPtrFunc  = M.getOrInsertFunction("RecordPointer",
130                                          Type::VoidTy, SBP, 0);
131   
132   PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", Type::VoidTy, 0);
133   ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
134                                               Type::VoidTy, 0);
135 }
136
137
138 // Add a prototype for external functions used by the tracing code.
139 //
140 bool InsertTraceCode::doInitialization(Module &M) {
141   externalFuncs.doInitialization(M);
142   return false;
143 }
144
145
146 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
147   // Create a constant internal string reference...
148   Constant *Init = ConstantArray::get(str);
149
150   // Create the global variable and record it in the module
151   // The GV will be renamed to a unique name if needed.
152   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, 
153                                           GlobalValue::InternalLinkage, Init,
154                                           "trstr");
155   M->getGlobalList().push_back(GV);
156   return GV;
157 }
158
159
160 // 
161 // Check if this instruction has any uses outside its basic block,
162 // or if it used by either a Call or Return instruction (ditto).
163 // (Values stored to memory within this BB are live at end of BB but are
164 // traced at the store instruction, not where they are computed.)
165 // 
166 static inline bool LiveAtBBExit(const Instruction* I) {
167   const BasicBlock *BB = I->getParent();
168   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
169     if (const Instruction *UI = dyn_cast<Instruction>(*U))
170       if (UI->getParent() != BB || isa<ReturnInst>(UI))
171         return true;
172
173   return false;
174 }
175
176
177 static inline bool TraceThisOpCode(unsigned opCode) {
178   // Explicitly test for opCodes *not* to trace so that any new opcodes will
179   // be traced by default (VoidTy's are already excluded)
180   // 
181   return (opCode  < Instruction::OtherOpsBegin &&
182           opCode != Instruction::Alloca &&
183           opCode != Instruction::PHINode &&
184           opCode != Instruction::Cast);
185 }
186
187
188 // Trace a value computed by an instruction if it is non-void, it is computed
189 // by a real computation, not just a copy (see TraceThisOpCode), and
190 // -- it is a load instruction: we want to check values read from memory
191 // -- or it is live at exit from the basic block (i.e., ignore local temps)
192 // 
193 static bool ShouldTraceValue(const Instruction *I) {
194   return
195     I->getType() != Type::VoidTy &&
196     TraceThisOpCode(I->getOpcode()) &&
197     (isa<LoadInst>(I) || LiveAtBBExit(I));
198 }
199
200 static string getPrintfCodeFor(const Value *V) {
201   if (V == 0) return "";
202   if (V->getType()->isFloatingPoint())
203     return "%g";
204   else if (V->getType() == Type::LabelTy)
205     return "0x%p";
206   else if (isa<PointerType>(V->getType()))
207     return DisablePtrHashing ? "0x%p" : "%d";
208   else if (V->getType()->isIntegral())
209     return "%d";
210   
211   assert(0 && "Illegal value to print out...");
212   return "";
213 }
214
215
216 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
217                             string Message,
218                             Function *Printf, Function* HashPtrToSeqNum) {
219   // Escape Message by replacing all % characters with %% chars.
220   string Tmp;
221   std::swap(Tmp, Message);
222   string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
223   while (I != Tmp.end()) {
224     Message.append(Tmp.begin(), I);
225     Message += "%%";
226     ++I; // Make sure to erase the % as well...
227     Tmp.erase(Tmp.begin(), I);
228     I = std::find(Tmp.begin(), Tmp.end(), '%');
229   }
230   Message += Tmp;
231   Module *Mod = BB->getParent()->getParent();
232
233   // Turn the marker string into a global variable...
234   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
235
236   // Turn the format string into an sbyte *
237   Constant *GEP =ConstantExpr::getGetElementPtr(ConstantPointerRef::get(fmtVal),
238                      vector<Constant*>(2,Constant::getNullValue(Type::LongTy)));
239   
240   // Insert a call to the hash function if this is a pointer value
241   if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
242     const Type *SBP = PointerType::get(Type::SByteTy);
243     if (V->getType() != SBP)     // Cast pointer to be sbyte*
244       V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
245
246     vector<Value*> HashArgs(1, V);
247     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
248   }
249   
250   // Insert the first print instruction to print the string flag:
251   vector<Value*> PrintArgs;
252   PrintArgs.push_back(GEP);
253   if (V) PrintArgs.push_back(V);
254   new CallInst(Printf, PrintArgs, "trace", InsertBefore);
255 }
256                             
257
258 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
259                                    Instruction *InsertBefore,
260                                    const string &Message, Function *Printf,
261                                    Function* HashPtrToSeqNum) {
262   std::ostringstream OutStr;
263   if (V) WriteAsOperand(OutStr, V);
264   InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
265                   Printf, HashPtrToSeqNum);
266 }
267
268 static void 
269 InsertReleaseInst(Value *V, BasicBlock *BB,
270                   Instruction *InsertBefore,
271                   Function* ReleasePtrFunc) {
272   
273   const Type *SBP = PointerType::get(Type::SByteTy);
274   if (V->getType() != SBP)    // Cast pointer to be sbyte*
275     V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
276
277   vector<Value*> releaseArgs(1, V);
278   new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
279 }
280
281 static void 
282 InsertRecordInst(Value *V, BasicBlock *BB,
283                  Instruction *InsertBefore,
284                  Function* RecordPtrFunc) {
285     const Type *SBP = PointerType::get(Type::SByteTy);
286   if (V->getType() != SBP)     // Cast pointer to be sbyte*
287     V = new CastInst(V, SBP, "RP_cast", InsertBefore);
288
289   vector<Value*> releaseArgs(1, V);
290   new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
291 }
292
293 // Look for alloca and free instructions. These are the ptrs to release.
294 // Release the free'd pointers immediately.  Record the alloca'd pointers
295 // to be released on return from the current function.
296 // 
297 static void
298 ReleasePtrSeqNumbers(BasicBlock *BB,
299                      ExternalFuncs& externalFuncs) {
300   
301   for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
302     if (FreeInst *FI = dyn_cast<FreeInst>(II))
303       InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
304     else if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
305       InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
306 }  
307
308
309 // Insert print instructions at the end of basic block BB for each value
310 // computed in BB that is live at the end of BB,
311 // or that is stored to memory in BB.
312 // If the value is stored to memory, we load it back before printing it
313 // We also return all such loaded values in the vector valuesStoredInFunction
314 // for printing at the exit from the function.  (Note that in each invocation
315 // of the function, this will only get the last value stored for each static
316 // store instruction).
317 // 
318 static void TraceValuesAtBBExit(BasicBlock *BB,
319                                 Function *Printf, Function* HashPtrToSeqNum,
320                                 vector<Instruction*> *valuesStoredInFunction) {
321   // Get an iterator to point to the insertion location, which is
322   // just before the terminator instruction.
323   // 
324   TerminatorInst *InsertPos = BB->getTerminator();
325   
326   std::ostringstream OutStr;
327   WriteAsOperand(OutStr, BB, false);
328   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
329                   Printf, HashPtrToSeqNum);
330
331   // Insert a print instruction for each instruction preceding InsertPos.
332   // The print instructions must go before InsertPos, so we use the
333   // instruction *preceding* InsertPos to check when to terminate the loop.
334   // 
335   for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
336     if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
337       // Trace the stored value and address
338       InsertVerbosePrintInst(SI->getOperand(0), BB, InsertPos,
339                              "  (store value) ", Printf, HashPtrToSeqNum);
340       InsertVerbosePrintInst(SI->getOperand(1), BB, InsertPos,
341                              "  (store addr ) ", Printf, HashPtrToSeqNum);
342     }
343     else if (ShouldTraceValue(II))
344       InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf, HashPtrToSeqNum);
345   }
346 }
347
348 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
349                                                  Function* HashPtrToSeqNum){
350   // Get an iterator to point to the insertion location
351   BasicBlock &BB = F.getEntryNode();
352   Instruction *InsertPos = BB.begin();
353
354   std::ostringstream OutStr;
355   WriteAsOperand(OutStr, &F);
356   InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
357                   Printf, HashPtrToSeqNum);
358
359   // Now print all the incoming arguments
360   unsigned ArgNo = 0;
361   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
362     InsertVerbosePrintInst(I, &BB, InsertPos,
363                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
364                            HashPtrToSeqNum);
365   }
366 }
367
368
369 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
370                                                 Function *Printf,
371                                                 Function* HashPtrToSeqNum) {
372   // Get an iterator to point to the insertion location
373   ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
374   
375   std::ostringstream OutStr;
376   WriteAsOperand(OutStr, BB->getParent(), true);
377   InsertPrintInst(0, BB, Ret, "LEAVING  FUNCTION: " + OutStr.str(),
378                   Printf, HashPtrToSeqNum);
379   
380   // print the return value, if any
381   if (BB->getParent()->getReturnType() != Type::VoidTy)
382     InsertPrintInst(Ret->getReturnValue(), BB, Ret, "  Returning: ",
383                     Printf, HashPtrToSeqNum);
384 }
385
386
387 bool InsertTraceCode::runOnFunction(Function &F) {
388   if (!TraceThisFunction(F))
389     return false;
390   
391   vector<Instruction*> valuesStoredInFunction;
392   vector<BasicBlock*>  exitBlocks;
393
394   // Insert code to trace values at function entry
395   InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
396                                 externalFuncs.HashPtrFunc);
397   
398   // Push a pointer set for recording alloca'd pointers at entry.
399   if (!DisablePtrHashing)
400     new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
401                  F.getEntryNode().begin());
402
403   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
404     if (isa<ReturnInst>(BB->getTerminator()))
405       exitBlocks.push_back(BB); // record this as an exit block
406
407     // Insert trace code if this basic block is interesting...
408     handleBasicBlock(BB, valuesStoredInFunction);
409
410     if (!DisablePtrHashing)          // release seq. numbers on free/ret
411       ReleasePtrSeqNumbers(BB, externalFuncs);
412   }
413   
414   for (unsigned i=0; i != exitBlocks.size(); ++i)
415     {
416       // Insert code to trace values at function exit
417       InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
418                                    externalFuncs.HashPtrFunc);
419       
420       // Release all recorded pointers before RETURN.  Do this LAST!
421       if (!DisablePtrHashing)
422         new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
423                      exitBlocks[i]->getTerminator());
424     }
425   
426   return true;
427 }