1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and function
6 //===----------------------------------------------------------------------===//
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"
25 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
26 cl::desc("Disable pointer hashing in the -trace or -tracem "
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);
34 static void TraceValuesAtBBExit(BasicBlock *BB,
35 Function *Printf, Function* HashPtrToSeqNum,
36 vector<Instruction*> *valuesStoredInFunction);
38 // We trace a particular function if no functions to trace were specified
39 // or if the function is in the specified list.
42 TraceThisFunction(Function &F)
44 if (TraceFuncNames.empty()) return true;
46 return std::find(TraceFuncNames.begin(), TraceFuncNames.end(), F.getName())
47 != TraceFuncNames.end();
52 struct ExternalFuncs {
53 Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
54 Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
55 void doInitialization(Module &M); // Add prototypes for external functions
58 class InsertTraceCode : public FunctionPass {
60 ExternalFuncs externalFuncs;
63 // Add a prototype for runtime functions not already in the program.
65 bool doInitialization(Module &M);
67 //--------------------------------------------------------------------------
68 // Function InsertCodeToTraceValues
70 // Inserts tracing code for all live values at basic block and/or function
71 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
73 bool doit(Function *M);
75 virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
77 // runOnFunction - This method does the work.
79 bool runOnFunction(Function &F);
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86 struct FunctionTracer : public InsertTraceCode {
87 // Ignore basic blocks here...
88 virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
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);
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
105 Pass *createTraceValuesPassForFunction() { // Just trace functions
106 return new FunctionTracer();
109 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
110 return new BasicBlockTracer();
114 // Add a prototype for external functions used by the tracing code.
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);
123 const FunctionType *hashFuncTy =
124 FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
125 HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
128 const FunctionType *voidSBPFuncTy =
129 FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
131 ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
132 RecordPtrFunc = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
134 const FunctionType *voidvoidFuncTy =
135 FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
137 PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
138 ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
143 // Add a prototype for external functions used by the tracing code.
145 bool InsertTraceCode::doInitialization(Module &M) {
146 externalFuncs.doInitialization(M);
151 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
152 // Create a constant internal string reference...
153 Constant *Init = ConstantArray::get(str);
155 // Create the global variable and record it in the module
156 // The GV will be renamed to a unique name if needed.
157 GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
158 GlobalValue::InternalLinkage, Init,
160 M->getGlobalList().push_back(GV);
166 // Check if this instruction has any uses outside its basic block,
167 // or if it used by either a Call or Return instruction (ditto).
168 // (Values stored to memory within this BB are live at end of BB but are
169 // traced at the store instruction, not where they are computed.)
171 static inline bool LiveAtBBExit(const Instruction* I) {
172 const BasicBlock *BB = I->getParent();
173 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
174 if (const Instruction *UI = dyn_cast<Instruction>(*U))
175 if (UI->getParent() != BB || isa<ReturnInst>(UI))
182 static inline bool TraceThisOpCode(unsigned opCode) {
183 // Explicitly test for opCodes *not* to trace so that any new opcodes will
184 // be traced by default (VoidTy's are already excluded)
186 return (opCode < Instruction::OtherOpsBegin &&
187 opCode != Instruction::Alloca &&
188 opCode != Instruction::PHINode &&
189 opCode != Instruction::Cast);
193 // Trace a value computed by an instruction if it is non-void, it is computed
194 // by a real computation, not just a copy (see TraceThisOpCode), and
195 // -- it is a load instruction: we want to check values read from memory
196 // -- or it is live at exit from the basic block (i.e., ignore local temps)
198 static bool ShouldTraceValue(const Instruction *I) {
200 I->getType() != Type::VoidTy &&
201 TraceThisOpCode(I->getOpcode()) &&
202 (isa<LoadInst>(I) || LiveAtBBExit(I));
205 static string getPrintfCodeFor(const Value *V) {
206 if (V == 0) return "";
207 if (V->getType()->isFloatingPoint())
209 else if (V->getType() == Type::LabelTy)
211 else if (isa<PointerType>(V->getType()))
212 return DisablePtrHashing ? "0x%p" : "%d";
213 else if (V->getType()->isIntegral())
216 assert(0 && "Illegal value to print out...");
221 static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
223 Function *Printf, Function* HashPtrToSeqNum) {
224 // Escape Message by replacing all % characters with %% chars.
226 std::swap(Tmp, Message);
227 string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
228 while (I != Tmp.end()) {
229 Message.append(Tmp.begin(), I);
231 ++I; // Make sure to erase the % as well...
232 Tmp.erase(Tmp.begin(), I);
233 I = std::find(Tmp.begin(), Tmp.end(), '%');
236 Module *Mod = BB->getParent()->getParent();
238 // Turn the marker string into a global variable...
239 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
241 // Turn the format string into an sbyte *
242 Constant *GEP =ConstantExpr::getGetElementPtr(ConstantPointerRef::get(fmtVal),
243 vector<Constant*>(2,Constant::getNullValue(Type::LongTy)));
245 // Insert a call to the hash function if this is a pointer value
246 if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
247 const Type *SBP = PointerType::get(Type::SByteTy);
248 if (V->getType() != SBP) // Cast pointer to be sbyte*
249 V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
251 vector<Value*> HashArgs(1, V);
252 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
255 // Insert the first print instruction to print the string flag:
256 vector<Value*> PrintArgs;
257 PrintArgs.push_back(GEP);
258 if (V) PrintArgs.push_back(V);
259 new CallInst(Printf, PrintArgs, "trace", InsertBefore);
263 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
264 Instruction *InsertBefore,
265 const string &Message, Function *Printf,
266 Function* HashPtrToSeqNum) {
267 std::ostringstream OutStr;
268 if (V) WriteAsOperand(OutStr, V);
269 InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
270 Printf, HashPtrToSeqNum);
274 InsertReleaseInst(Value *V, BasicBlock *BB,
275 Instruction *InsertBefore,
276 Function* ReleasePtrFunc) {
278 const Type *SBP = PointerType::get(Type::SByteTy);
279 if (V->getType() != SBP) // Cast pointer to be sbyte*
280 V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
282 vector<Value*> releaseArgs(1, V);
283 new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
287 InsertRecordInst(Value *V, BasicBlock *BB,
288 Instruction *InsertBefore,
289 Function* RecordPtrFunc) {
290 const Type *SBP = PointerType::get(Type::SByteTy);
291 if (V->getType() != SBP) // Cast pointer to be sbyte*
292 V = new CastInst(V, SBP, "RP_cast", InsertBefore);
294 vector<Value*> releaseArgs(1, V);
295 new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
298 // Look for alloca and free instructions. These are the ptrs to release.
299 // Release the free'd pointers immediately. Record the alloca'd pointers
300 // to be released on return from the current function.
303 ReleasePtrSeqNumbers(BasicBlock *BB,
304 ExternalFuncs& externalFuncs) {
306 for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
307 if (FreeInst *FI = dyn_cast<FreeInst>(II))
308 InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
309 else if (AllocaInst *AI = dyn_cast<AllocaInst>(II))
310 InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
314 // Insert print instructions at the end of basic block BB for each value
315 // computed in BB that is live at the end of BB,
316 // or that is stored to memory in BB.
317 // If the value is stored to memory, we load it back before printing it
318 // We also return all such loaded values in the vector valuesStoredInFunction
319 // for printing at the exit from the function. (Note that in each invocation
320 // of the function, this will only get the last value stored for each static
321 // store instruction).
323 static void TraceValuesAtBBExit(BasicBlock *BB,
324 Function *Printf, Function* HashPtrToSeqNum,
325 vector<Instruction*> *valuesStoredInFunction) {
326 // Get an iterator to point to the insertion location, which is
327 // just before the terminator instruction.
329 TerminatorInst *InsertPos = BB->getTerminator();
331 std::ostringstream OutStr;
332 WriteAsOperand(OutStr, BB, false);
333 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
334 Printf, HashPtrToSeqNum);
336 // Insert a print instruction for each instruction preceding InsertPos.
337 // The print instructions must go before InsertPos, so we use the
338 // instruction *preceding* InsertPos to check when to terminate the loop.
340 for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
341 if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
342 // Trace the stored value and address
343 InsertVerbosePrintInst(SI->getOperand(0), BB, InsertPos,
344 " (store value) ", Printf, HashPtrToSeqNum);
345 InsertVerbosePrintInst(SI->getOperand(1), BB, InsertPos,
346 " (store addr ) ", Printf, HashPtrToSeqNum);
348 else if (ShouldTraceValue(II))
349 InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
353 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
354 Function* HashPtrToSeqNum){
355 // Get an iterator to point to the insertion location
356 BasicBlock &BB = F.getEntryNode();
357 Instruction *InsertPos = BB.begin();
359 std::ostringstream OutStr;
360 WriteAsOperand(OutStr, &F);
361 InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
362 Printf, HashPtrToSeqNum);
364 // Now print all the incoming arguments
366 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
367 InsertVerbosePrintInst(I, &BB, InsertPos,
368 " Arg #" + utostr(ArgNo) + ": ", Printf,
374 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
376 Function* HashPtrToSeqNum) {
377 // Get an iterator to point to the insertion location
378 ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
380 std::ostringstream OutStr;
381 WriteAsOperand(OutStr, BB->getParent(), true);
382 InsertPrintInst(0, BB, Ret, "LEAVING FUNCTION: " + OutStr.str(),
383 Printf, HashPtrToSeqNum);
385 // print the return value, if any
386 if (BB->getParent()->getReturnType() != Type::VoidTy)
387 InsertPrintInst(Ret->getReturnValue(), BB, Ret, " Returning: ",
388 Printf, HashPtrToSeqNum);
392 bool InsertTraceCode::runOnFunction(Function &F) {
393 if (!TraceThisFunction(F))
396 vector<Instruction*> valuesStoredInFunction;
397 vector<BasicBlock*> exitBlocks;
399 // Insert code to trace values at function entry
400 InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
401 externalFuncs.HashPtrFunc);
403 // Push a pointer set for recording alloca'd pointers at entry.
404 if (!DisablePtrHashing)
405 new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
406 F.getEntryNode().begin());
408 for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
409 if (isa<ReturnInst>(BB->getTerminator()))
410 exitBlocks.push_back(BB); // record this as an exit block
412 // Insert trace code if this basic block is interesting...
413 handleBasicBlock(BB, valuesStoredInFunction);
415 if (!DisablePtrHashing) // release seq. numbers on free/ret
416 ReleasePtrSeqNumbers(BB, externalFuncs);
419 for (unsigned i=0; i != exitBlocks.size(); ++i)
421 // Insert code to trace values at function exit
422 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
423 externalFuncs.HashPtrFunc);
425 // Release all recorded pointers before RETURN. Do this LAST!
426 if (!DisablePtrHashing)
427 new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
428 exitBlocks[i]->getTerminator());