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