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/Method.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.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, TraceMethodExits;
30 InsertTraceCode(bool traceBasicBlockExits, bool traceMethodExits)
31 : TraceBasicBlockExits(traceBasicBlockExits),
32 TraceMethodExits(traceMethodExits) {}
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 `traceMethodExits'.
44 static bool doit(Method *M, bool traceBasicBlockExits,
45 bool traceMethodExits, Method *Printf);
47 // runOnMethod - This method does the work. Always successful.
49 bool runOnMethod(Method *M) {
50 return doit(M, TraceBasicBlockExits, TraceMethodExits, PrintfMeth);
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 SymbolTable *ST = M->getSymbolTable();
71 const Type *SBP = PointerType::get(Type::SByteTy);
72 const MethodType *MTy =
73 MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
75 if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
76 PrintfMeth = cast<Method>(Meth);
80 // Create a new method and add it to the module
81 PrintfMeth = new Method(MTy, false, "printf");
82 M->getMethodList().push_back(PrintfMeth);
87 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
88 // Create a constant internal string reference...
89 Constant *Init = ConstantArray::get(str);
91 // Create the global variable and record it in the module
92 // The GV will be renamed to a unique name if needed.
93 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
95 M->getGlobalList().push_back(GV);
101 // Check if this instruction has any uses outside its basic block,
102 // or if it used by either a Call or Return instruction.
104 static inline bool LiveAtBBExit(const Instruction* I) {
105 const BasicBlock *BB = I->getParent();
106 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
107 if (const Instruction *UI = dyn_cast<Instruction>(*U))
108 if (UI->getParent() != BB || isa<ReturnInst>(UI))
115 static inline bool TraceThisOpCode(unsigned opCode) {
116 // Explicitly test for opCodes *not* to trace so that any new opcodes will
117 // be traced by default (VoidTy's are already excluded)
119 return (opCode < Instruction::FirstOtherOp &&
120 opCode != Instruction::Alloca &&
121 opCode != Instruction::PHINode &&
122 opCode != Instruction::Cast);
126 static bool ShouldTraceValue(const Instruction *I) {
128 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
129 TraceThisOpCode(I->getOpcode());
132 static string getPrintfCodeFor(const Value *V) {
133 if (V == 0) return "";
134 switch (V->getType()->getPrimitiveID()) {
136 case Type::UByteTyID: case Type::UShortTyID:
137 case Type::UIntTyID: case Type::ULongTyID:
138 case Type::SByteTyID: case Type::ShortTyID:
139 case Type::IntTyID: case Type::LongTyID:
142 case Type::FloatTyID: case Type::DoubleTyID:
145 case Type::LabelTyID: case Type::PointerTyID:
149 assert(0 && "Illegal value to print out...");
155 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
156 string Message, Method *Printf) {
157 // Escape Message by replacing all % characters with %% chars.
159 while ((Offset = Message.find('%', Offset)) != string::npos) {
160 Message.replace(Offset, 2, "%%");
161 Offset += 2; // Skip over the new %'s
164 Module *Mod = BB->getParent()->getParent();
166 // Turn the marker string into a global variable...
167 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
169 // Turn the format string into an sbyte *
171 new GetElementPtrInst(fmtVal,
172 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
174 BBI = BB->getInstList().insert(BBI, GEP)+1;
176 // Insert the first print instruction to print the string flag:
177 vector<Value*> PrintArgs;
178 PrintArgs.push_back(GEP);
179 if (V) PrintArgs.push_back(V);
180 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
181 BBI = BB->getInstList().insert(BBI, I)+1;
185 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
186 BasicBlock::iterator &BBI,
187 const string &Message, Method *Printf) {
188 std::ostringstream OutStr;
189 if (V) WriteAsOperand(OutStr, V);
190 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
194 // Insert print instructions at the end of the basic block *bb
195 // for each value in valueVec[] that is live at the end of that basic block,
196 // or that is stored to memory in this basic block.
197 // If the value is stored to memory, we load it back before printing
198 // We also return all such loaded values in the vector valuesStoredInMethod
199 // for printing at the exit from the method. (Note that in each invocation
200 // of the method, this will only get the last value stored for each static
201 // store instruction).
202 // *bb must be the block in which the value is computed;
203 // this is not checked here.
205 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
206 vector<Instruction*> *valuesStoredInMethod) {
207 // Get an iterator to point to the insertion location, which is
208 // just before the terminator instruction.
210 BasicBlock::iterator InsertPos = BB->end()-1;
211 assert((*InsertPos)->isTerminator());
213 // If the terminator is a conditional branch, insert the trace code just
214 // before the instruction that computes the branch condition (just to
215 // avoid putting a call between the CC-setting instruction and the branch).
216 // Use laterInstrSet to mark instructions that come after the setCC instr
217 // because those cannot be traced at the location we choose.
219 Instruction *SetCC = 0;
220 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
221 if (!Branch->isUnconditional())
222 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
223 if (I->getParent() == BB) {
225 while (*InsertPos != SetCC)
226 --InsertPos; // Back up until we can insert before the setcc
229 // Copy all of the instructions into a vector to avoid problems with Setcc
230 const vector<Instruction*> Insts(BB->begin(), InsertPos);
232 std::ostringstream OutStr;
233 WriteAsOperand(OutStr, BB, false);
234 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
236 // Insert a print instruction for each value.
238 for (vector<Instruction*>::const_iterator II = Insts.begin(),
239 IE = Insts.end(); II != IE; ++II) {
240 Instruction *I = *II;
241 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
242 assert(valuesStoredInMethod &&
243 "Should not be printing a store instruction at method exit");
244 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
246 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
247 valuesStoredInMethod->push_back(LI);
249 if (ShouldTraceValue(I))
250 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
254 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
255 // Get an iterator to point to the insertion location
256 BasicBlock *BB = M->getEntryNode();
257 BasicBlock::iterator BBI = BB->begin();
259 std::ostringstream OutStr;
260 WriteAsOperand(OutStr, M, true);
261 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
263 // Now print all the incoming arguments
264 const Method::ArgumentListType &argList = M->getArgumentList();
266 for (Method::ArgumentListType::const_iterator
267 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
268 InsertVerbosePrintInst(*I, BB, BBI,
269 " Arg #" + utostr(ArgNo), Printf);
274 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
275 // Get an iterator to point to the insertion location
276 BasicBlock::iterator BBI = BB->end()-1;
277 ReturnInst *Ret = cast<ReturnInst>(*BBI);
279 std::ostringstream OutStr;
280 WriteAsOperand(OutStr, BB->getParent(), true);
281 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
283 // print the return value, if any
284 if (BB->getParent()->getReturnType() != Type::VoidTy)
285 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
289 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
290 bool traceMethodEvents, Method *Printf) {
291 if (!traceBasicBlockExits && !traceMethodEvents)
294 vector<Instruction*> valuesStoredInMethod;
295 vector<BasicBlock*> exitBlocks;
297 if (traceMethodEvents)
298 InsertCodeToShowMethodEntry(M, Printf);
300 for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
301 BasicBlock *BB = *BI;
302 if (isa<ReturnInst>(BB->getTerminator()))
303 exitBlocks.push_back(BB); // record this as an exit block
305 if (traceBasicBlockExits)
306 TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
309 if (traceMethodEvents)
310 for (unsigned i=0; i < exitBlocks.size(); ++i) {
312 TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
313 /*indent*/ 0, /*isMethodExit*/ true,
314 /*valuesStoredInMethod*/ NULL);
316 InsertCodeToShowMethodExit(exitBlocks[i], Printf);