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/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Module.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "Support/CommandLine.h"
19 #include "Support/StringExtras.h"
26 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
27 cl::desc("Disable pointer hashing"));
29 static cl::list<string>
30 TraceFuncName("tracefunc", cl::desc("trace only specific functions"),
31 cl::value_desc("function"), cl::Hidden);
33 static void TraceValuesAtBBExit(BasicBlock *BB,
34 Function *Printf, Function* HashPtrToSeqNum,
35 vector<Instruction*> *valuesStoredInFunction);
37 // We trace a particular function if no functions to trace were specified
38 // or if the function is in the specified list.
41 TraceThisFunction(Function &func)
43 if (TraceFuncName.size() == 0)
46 return std::find(TraceFuncName.begin(), TraceFuncName.end(), func.getName())
47 != TraceFuncName.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, true, Init,
159 M->getGlobalList().push_back(GV);
165 // Check if this instruction has any uses outside its basic block,
166 // or if it used by either a Call or Return instruction.
168 static inline bool LiveAtBBExit(const Instruction* I) {
169 const BasicBlock *BB = I->getParent();
170 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
171 if (const Instruction *UI = dyn_cast<Instruction>(*U))
172 if (UI->getParent() != BB || isa<ReturnInst>(UI))
179 static inline bool TraceThisOpCode(unsigned opCode) {
180 // Explicitly test for opCodes *not* to trace so that any new opcodes will
181 // be traced by default (VoidTy's are already excluded)
183 return (opCode < Instruction::FirstOtherOp &&
184 opCode != Instruction::Alloca &&
185 opCode != Instruction::PHINode &&
186 opCode != Instruction::Cast);
190 static bool ShouldTraceValue(const Instruction *I) {
192 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
193 TraceThisOpCode(I->getOpcode());
196 static string getPrintfCodeFor(const Value *V) {
197 if (V == 0) return "";
198 if (V->getType()->isFloatingPoint())
200 else if (V->getType() == Type::LabelTy)
202 else if (isa<PointerType>(V->getType()))
203 return DisablePtrHashing ? "0x%p" : "%d";
204 else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
207 assert(0 && "Illegal value to print out...");
212 static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
214 Function *Printf, Function* HashPtrToSeqNum) {
215 // Escape Message by replacing all % characters with %% chars.
217 while ((Offset = Message.find('%', Offset)) != string::npos) {
218 Message.replace(Offset, 1, "%%");
219 Offset += 2; // Skip over the new %'s
222 Module *Mod = BB->getParent()->getParent();
224 // Turn the marker string into a global variable...
225 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
227 // Turn the format string into an sbyte *
229 new GetElementPtrInst(fmtVal,
230 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
232 BBI = ++BB->getInstList().insert(BBI, GEP);
234 // Insert a call to the hash function if this is a pointer value
235 if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
236 const Type *SBP = PointerType::get(Type::SByteTy);
237 if (V->getType() != SBP) { // Cast pointer to be sbyte*
238 Instruction *I = new CastInst(V, SBP, "Hash_cast");
239 BBI = ++BB->getInstList().insert(BBI, I);
243 vector<Value*> HashArgs(1, V);
244 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
245 BBI = ++BB->getInstList().insert(BBI, cast<Instruction>(V));
248 // Insert the first print instruction to print the string flag:
249 vector<Value*> PrintArgs;
250 PrintArgs.push_back(GEP);
251 if (V) PrintArgs.push_back(V);
252 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
253 BBI = ++BB->getInstList().insert(BBI, I);
257 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
258 BasicBlock::iterator &BBI,
259 const string &Message, Function *Printf,
260 Function* HashPtrToSeqNum) {
261 std::ostringstream OutStr;
262 if (V) WriteAsOperand(OutStr, V);
263 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ",
264 Printf, HashPtrToSeqNum);
268 InsertReleaseInst(Value *V, BasicBlock *BB,
269 BasicBlock::iterator &BBI,
270 Function* ReleasePtrFunc) {
272 const Type *SBP = PointerType::get(Type::SByteTy);
273 if (V->getType() != SBP) { // Cast pointer to be sbyte*
274 Instruction *I = new CastInst(V, SBP, "RPSN_cast");
275 BBI = ++BB->getInstList().insert(BBI, I);
278 vector<Value*> releaseArgs(1, V);
279 Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
280 BBI = ++BB->getInstList().insert(BBI, I);
284 InsertRecordInst(Value *V, BasicBlock *BB,
285 BasicBlock::iterator &BBI,
286 Function* RecordPtrFunc) {
287 const Type *SBP = PointerType::get(Type::SByteTy);
288 if (V->getType() != SBP) { // Cast pointer to be sbyte*
289 Instruction *I = new CastInst(V, SBP, "RP_cast");
290 BBI = ++BB->getInstList().insert(BBI, I);
293 vector<Value*> releaseArgs(1, V);
294 Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
295 BBI = ++BB->getInstList().insert(BBI, I);
299 InsertPushOnEntryFunc(Function *M,
300 Function* PushOnEntryFunc) {
301 // Get an iterator to point to the insertion location
302 BasicBlock &BB = M->getEntryNode();
303 BB.getInstList().insert(BB.begin(), new CallInst(PushOnEntryFunc,
308 InsertReleaseRecordedInst(BasicBlock *BB,
309 Function* ReleaseOnReturnFunc) {
310 BasicBlock::iterator BBI = --BB->end();
311 BBI = ++BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
315 // Look for alloca and free instructions. These are the ptrs to release.
316 // Release the free'd pointers immediately. Record the alloca'd pointers
317 // to be released on return from the current function.
320 ReleasePtrSeqNumbers(BasicBlock *BB,
321 ExternalFuncs& externalFuncs) {
323 for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
324 if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
325 InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
326 else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
328 BasicBlock::iterator nextI = ++II;
329 InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);
336 // Insert print instructions at the end of basic block BB for each value
337 // computed in BB that is live at the end of BB,
338 // or that is stored to memory in BB.
339 // If the value is stored to memory, we load it back before printing it
340 // We also return all such loaded values in the vector valuesStoredInFunction
341 // for printing at the exit from the function. (Note that in each invocation
342 // of the function, this will only get the last value stored for each static
343 // store instruction).
345 static void TraceValuesAtBBExit(BasicBlock *BB,
346 Function *Printf, Function* HashPtrToSeqNum,
347 vector<Instruction*> *valuesStoredInFunction) {
348 // Get an iterator to point to the insertion location, which is
349 // just before the terminator instruction.
351 BasicBlock::iterator InsertPos = --BB->end();
352 assert(InsertPos->isTerminator());
354 std::ostringstream OutStr;
355 WriteAsOperand(OutStr, BB, false);
356 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
357 Printf, HashPtrToSeqNum);
359 // Insert a print instruction for each instruction preceding InsertPos.
360 // The print instructions must go before InsertPos, so we use the
361 // instruction *preceding* InsertPos to check when to terminate the loop.
363 if (InsertPos != BB->begin()) { // there's at least one instr before InsertPos
364 BasicBlock::iterator II = BB->begin(), IEincl = InsertPos;
366 do { // do from II up to IEincl, inclusive
367 if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
368 assert(valuesStoredInFunction &&
369 "Should not be printing a store instruction at function exit");
370 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
371 "reload."+SI->getPointerOperand()->getName());
372 InsertPos = ++BB->getInstList().insert(InsertPos, LI);
373 valuesStoredInFunction->push_back(LI);
375 if (ShouldTraceValue(II))
376 InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf,HashPtrToSeqNum);
377 } while (II++ != IEincl);
381 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
382 Function* HashPtrToSeqNum){
383 // Get an iterator to point to the insertion location
384 BasicBlock &BB = F.getEntryNode();
385 BasicBlock::iterator BBI = BB.begin();
387 std::ostringstream OutStr;
388 WriteAsOperand(OutStr, &F, true);
389 InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
390 Printf, HashPtrToSeqNum);
392 // Now print all the incoming arguments
394 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
395 InsertVerbosePrintInst(I, &BB, BBI,
396 " Arg #" + utostr(ArgNo) + ": ", Printf,
402 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
404 Function* HashPtrToSeqNum) {
405 // Get an iterator to point to the insertion location
406 BasicBlock::iterator BBI = --BB->end();
407 ReturnInst &Ret = cast<ReturnInst>(BB->back());
409 std::ostringstream OutStr;
410 WriteAsOperand(OutStr, BB->getParent(), true);
411 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(),
412 Printf, HashPtrToSeqNum);
414 // print the return value, if any
415 if (BB->getParent()->getReturnType() != Type::VoidTy)
416 InsertPrintInst(Ret.getReturnValue(), BB, BBI, " Returning: ",
417 Printf, HashPtrToSeqNum);
421 bool InsertTraceCode::runOnFunction(Function &F) {
422 if (!TraceThisFunction(F))
425 vector<Instruction*> valuesStoredInFunction;
426 vector<BasicBlock*> exitBlocks;
428 // Insert code to trace values at function entry
429 InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
430 externalFuncs.HashPtrFunc);
432 // Push a pointer set for recording alloca'd pointers at entry.
433 if (!DisablePtrHashing)
434 InsertPushOnEntryFunc(&F, externalFuncs.PushOnEntryFunc);
436 for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
437 if (isa<ReturnInst>(BB->getTerminator()))
438 exitBlocks.push_back(BB); // record this as an exit block
440 // Insert trace code if this basic block is interesting...
441 handleBasicBlock(BB, valuesStoredInFunction);
443 if (!DisablePtrHashing) // release seq. numbers on free/ret
444 ReleasePtrSeqNumbers(BB, externalFuncs);
447 for (unsigned i=0; i != exitBlocks.size(); ++i)
449 // Insert code to trace values at function exit
450 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
451 externalFuncs.HashPtrFunc);
453 // Release all recorded pointers before RETURN. Do this LAST!
454 if (!DisablePtrHashing)
455 InsertReleaseRecordedInst(exitBlocks[i],
456 externalFuncs.ReleaseOnReturnFunc);