Search code examples
cgccmap-files

How to count how many times a global variable was used (read and write)?


I'm trying to optimize a C code project.

I would like to count how many times a global variable was used (read or write) in order to place it at the most suitable memory type.
For example, to store commonly used variables at the fast access memory type.

Data cache is disabled for determenistic reasons.

Is there a way to count how many times a variable was used without inserting counters or adding extra code? for example, using the assembly code?

The code is written in C.

In my possession:

A) (.map) file, generated by the GCC compiler from which I extracts the global variables names, addresses and sizes.

B) The assembly code of the project generated using the GCC compiler -S flag.

Thanks a lot,


Solution

  • GDB has something called watchpoints: https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html

    Set a watchpoint for an expression. GDB will break when the expression expr is written into by the program and its value changes. The simplest (and the most popular) use of this command is to watch the value of a single variable:

    (gdb) watch foo

    awatch [-l|-location] expr [thread thread-id] [mask maskvalue]

    Set a watchpoint that will break when expr is either read from or written into by the program.

    Commands can be attached to watchpoints: https://sourceware.org/gdb/onlinedocs/gdb/Break-Commands.html#Break-Commands

    You can give any breakpoint (or watchpoint or catchpoint) a series of commands to execute when your program stops due to that breakpoint… For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive.

    break foo if x>0 
    commands 
    silent 
    printf "x is %d\n",x 
    cont 
    end
    

    The command should typically increment a variable or print "read/write" to a file, but you can really add other stuff too such as a backtrace. Unsure about the best way for outward communication using gdb. Maybe it is good enough for you to run it in interactive mode.