1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and method
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Instrumentation/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/ConstantVals.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Function.h"
17 #include "llvm/Module.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/StringExtras.h"
26 class InsertTraceCode : public MethodPass {
27 bool TraceBasicBlockExits, TraceFunctionExits;
30 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
31 : TraceBasicBlockExits(traceBasicBlockExits),
32 TraceFunctionExits(traceFunctionExits) {}
34 // Add a prototype for printf if it is not already in the program.
36 bool doInitialization(Module *M);
38 //--------------------------------------------------------------------------
39 // Function InsertCodeToTraceValues
41 // Inserts tracing code for all live values at basic block and/or method
42 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
44 static bool doit(Function *M, bool traceBasicBlockExits,
45 bool traceFunctionExits, Function *Printf);
47 // runOnMethod - This method does the work. Always successful.
49 bool runOnMethod(Function *F) {
50 return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc);
53 } // end anonymous namespace
56 Pass *createTraceValuesPassForMethod() { // Just trace methods
57 return new InsertTraceCode(false, true);
60 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and methods
61 return new InsertTraceCode(true, true);
67 // Add a prototype for printf if it is not already in the program.
69 bool InsertTraceCode::doInitialization(Module *M) {
70 const Type *SBP = PointerType::get(Type::SByteTy);
71 const FunctionType *MTy =
72 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
74 PrintfFunc = M->getOrInsertFunction("printf", MTy);
79 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
80 // Create a constant internal string reference...
81 Constant *Init = ConstantArray::get(str);
83 // Create the global variable and record it in the module
84 // The GV will be renamed to a unique name if needed.
85 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
87 M->getGlobalList().push_back(GV);
93 // Check if this instruction has any uses outside its basic block,
94 // or if it used by either a Call or Return instruction.
96 static inline bool LiveAtBBExit(const Instruction* I) {
97 const BasicBlock *BB = I->getParent();
98 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
99 if (const Instruction *UI = dyn_cast<Instruction>(*U))
100 if (UI->getParent() != BB || isa<ReturnInst>(UI))
107 static inline bool TraceThisOpCode(unsigned opCode) {
108 // Explicitly test for opCodes *not* to trace so that any new opcodes will
109 // be traced by default (VoidTy's are already excluded)
111 return (opCode < Instruction::FirstOtherOp &&
112 opCode != Instruction::Alloca &&
113 opCode != Instruction::PHINode &&
114 opCode != Instruction::Cast);
118 static bool ShouldTraceValue(const Instruction *I) {
120 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
121 TraceThisOpCode(I->getOpcode());
124 static string getPrintfCodeFor(const Value *V) {
125 if (V == 0) return "";
126 switch (V->getType()->getPrimitiveID()) {
128 case Type::UByteTyID: case Type::UShortTyID:
129 case Type::UIntTyID: case Type::ULongTyID:
130 case Type::SByteTyID: case Type::ShortTyID:
131 case Type::IntTyID: case Type::LongTyID:
134 case Type::FloatTyID: case Type::DoubleTyID:
137 case Type::LabelTyID: case Type::PointerTyID:
141 assert(0 && "Illegal value to print out...");
147 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
148 string Message, Function *Printf) {
149 // Escape Message by replacing all % characters with %% chars.
151 while ((Offset = Message.find('%', Offset)) != string::npos) {
152 Message.replace(Offset, 2, "%%");
153 Offset += 2; // Skip over the new %'s
156 Module *Mod = BB->getParent()->getParent();
158 // Turn the marker string into a global variable...
159 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
161 // Turn the format string into an sbyte *
163 new GetElementPtrInst(fmtVal,
164 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
166 BBI = BB->getInstList().insert(BBI, GEP)+1;
168 // Insert the first print instruction to print the string flag:
169 vector<Value*> PrintArgs;
170 PrintArgs.push_back(GEP);
171 if (V) PrintArgs.push_back(V);
172 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
173 BBI = BB->getInstList().insert(BBI, I)+1;
177 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
178 BasicBlock::iterator &BBI,
179 const string &Message, Function *Printf) {
180 std::ostringstream OutStr;
181 if (V) WriteAsOperand(OutStr, V);
182 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
186 // Insert print instructions at the end of the basic block *bb
187 // for each value in valueVec[] that is live at the end of that basic block,
188 // or that is stored to memory in this basic block.
189 // If the value is stored to memory, we load it back before printing
190 // We also return all such loaded values in the vector valuesStoredInFunction
191 // for printing at the exit from the method. (Note that in each invocation
192 // of the method, this will only get the last value stored for each static
193 // store instruction).
194 // *bb must be the block in which the value is computed;
195 // this is not checked here.
197 static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf,
198 vector<Instruction*> *valuesStoredInFunction) {
199 // Get an iterator to point to the insertion location, which is
200 // just before the terminator instruction.
202 BasicBlock::iterator InsertPos = BB->end()-1;
203 assert((*InsertPos)->isTerminator());
205 // If the terminator is a conditional branch, insert the trace code just
206 // before the instruction that computes the branch condition (just to
207 // avoid putting a call between the CC-setting instruction and the branch).
208 // Use laterInstrSet to mark instructions that come after the setCC instr
209 // because those cannot be traced at the location we choose.
211 Instruction *SetCC = 0;
212 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
213 if (!Branch->isUnconditional())
214 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
215 if (I->getParent() == BB) {
217 while (*InsertPos != SetCC)
218 --InsertPos; // Back up until we can insert before the setcc
221 // Copy all of the instructions into a vector to avoid problems with Setcc
222 const vector<Instruction*> Insts(BB->begin(), InsertPos);
224 std::ostringstream OutStr;
225 WriteAsOperand(OutStr, BB, false);
226 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
228 // Insert a print instruction for each value.
230 for (vector<Instruction*>::const_iterator II = Insts.begin(),
231 IE = Insts.end(); II != IE; ++II) {
232 Instruction *I = *II;
233 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
234 assert(valuesStoredInFunction &&
235 "Should not be printing a store instruction at method exit");
236 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
238 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
239 valuesStoredInFunction->push_back(LI);
241 if (ShouldTraceValue(I))
242 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
246 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){
247 // Get an iterator to point to the insertion location
248 BasicBlock *BB = M->getEntryNode();
249 BasicBlock::iterator BBI = BB->begin();
251 std::ostringstream OutStr;
252 WriteAsOperand(OutStr, M, true);
253 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
255 // Now print all the incoming arguments
256 const Function::ArgumentListType &argList = M->getArgumentList();
258 for (Function::ArgumentListType::const_iterator
259 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
260 InsertVerbosePrintInst(*I, BB, BBI,
261 " Arg #" + utostr(ArgNo), Printf);
266 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
268 // Get an iterator to point to the insertion location
269 BasicBlock::iterator BBI = BB->end()-1;
270 ReturnInst *Ret = cast<ReturnInst>(*BBI);
272 std::ostringstream OutStr;
273 WriteAsOperand(OutStr, BB->getParent(), true);
274 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
276 // print the return value, if any
277 if (BB->getParent()->getReturnType() != Type::VoidTy)
278 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
282 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
283 bool traceFunctionEvents, Function *Printf) {
284 if (!traceBasicBlockExits && !traceFunctionEvents)
287 vector<Instruction*> valuesStoredInFunction;
288 vector<BasicBlock*> exitBlocks;
290 if (traceFunctionEvents)
291 InsertCodeToShowFunctionEntry(M, Printf);
293 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
294 BasicBlock *BB = *BI;
295 if (isa<ReturnInst>(BB->getTerminator()))
296 exitBlocks.push_back(BB); // record this as an exit block
298 if (traceBasicBlockExits)
299 TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction);
302 if (traceFunctionEvents)
303 for (unsigned i=0; i < exitBlocks.size(); ++i) {
305 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module,
306 /*indent*/ 0, /*isFunctionExit*/ true,
307 /*valuesStoredInFunction*/ NULL);
309 InsertCodeToShowFunctionExit(exitBlocks[i], Printf);