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