Since MIR can be accessed from rustc_driver, such as run_compiler. We can just link our algorithm as a callback function. This method is only suitable when we analyze a single file.
However, I want to do some analysis on MIR from a project. Specifically, can we access MIR after cargo build?
If we generate MIR from --emit mir, we must recover MIR data structure from .mir file. How to do that?
I prefer to access MIR directly from API. But I do not figure out how to do that. Use cargo API?
If you compile all dependencies with -Zalways-encode-mir (for the standard library this requires -Zbuild-std), you can get not just the MIR for the current crate, but also for all dependencies through the rustc_driver api. --emit mir is a lossy debug representation of MIR. It is not meant to be parsed and in fact misses a lot of details like type definitions.
Thanks. I have figured out how to do that with cargo according to the rupta. Besides wrapping our program as a callback function for rustc, it also wraps our program as a compiler. Via cargo option RUSTC_WRAPPER, our program acts as a compile that cargo invokes. Thus, our program can easily communicate with cargo.