Search code examples
linuxcpu-architectureinstructionsintel-pin

How to generate a listing of branches with Intel Pin tool?


I am relatively new to using the Intel Pin tool for code instrumentation and I am attempting to study Branch Prediction. Specifically, I would like to generate a listing of all the branches, their branch targets, and whether they are taken/not taken. I know there are pintools in the SimpleExamples for generating memory address traces such as the "pinatrace.cpp" tool, but I don't see any that suit my needs for listing branches.

Is there an existing pintool somewhere in the examples that I can use, or will I need to write a new pintool?

I am using pin-2.14 on a Linux computer.

Thanks!


Solution

  • I am not sure that there is a example pintool that does this, but this can be done relatively simply.

    If I understand you correctly, you want 3 things:

    1. Address of all conditional branches

    2. Targets

    3. Taken/Not taken decision

    1/2. This can be accomplished by using instruction level instrumentation. Use the INS_AddInstrumentFunction(Instruction, 0) in order to allow the function Instruction(INS ins, VOID *v) to be called every time a new instruction is about to be executed. Then within that Instruction() function, you can use if(INS_IsBranch(ins) && INS_HasFallThrough(ins)) expression to determine if the current instruction is a conditional branch. If it is, store its address INS_Address(ins) along with it's target INS_DirectBranchOrCallTargetAddress(ins). Perhaps you can print its disassembly for debugging purposes INS_Disassemble(ins).

    3.In order to print out the decision, you have to insert an analysis routine before every conditional branch. Using the Instruction function above, within the if(INS_IsBranch(ins) && INS_HasFallThrough(ins)), use this API call:

    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)<YOUR FUNCTION NAME>, IARG_INST_PTR, IARG_BRANCH_TAKEN, IARG_END)

    Using this, you can create an analysis routine that will run every time a conditional branch is dynamically executed. From there using the IARG_BRANCH_TAKEN argument, you can do a simple check to determine if the branch was taken or not. Store the decision in a map or something like a map so that later you can print it out. WARNING: Don't print anything out in an analysis routine (it's never a good idea to print out a dynamic trace of instructions). Also note that a conditional branch may run more than once with different taken/not taken decision so you may have to keep track of more than one decision.

    Hope this helps.

    CHEERS,

    Danny