使用LLVM opt与TSan Passes插装IR出现部分缺失的问题求助
Let me break down why your manual opt-based TSan instrumentation is missing key calls, and how to fix it to match what clang -fsanitize=thread produces.
The Root Cause
The issue boils down to two critical gaps in your workflow:
- Your initial LLVM IR (generated with
clang -S -emit-llvm tiny_race.c) lacks ThreadSanitizer-specific attributes and metadata. Without these, thetsanandtsan-modulepasses only run minimal instrumentation (function entry/exit calls) instead of full memory access and thread operation tracking. - You didn't explicitly tell
optto enable ThreadSanitizer mode, so the passes don't trigger their full logic for intercepting reads/writes and thread lifecycle operations.
When you use clang -fsanitize=thread, it automatically adds the sanitize_thread attribute to all functions and injects module-level metadata that signals the TSan passes to perform complete instrumentation. Your hand-generated IR doesn't have these, so the passes take a "lite" approach.
Fixes to Get Full TSan Instrumentation
You have two straightforward ways to fix this:
Option 1: Generate IR with TSan Metadata (Then Run Opt)
First, create an IR file that includes all the TSan required attributes but doesn't run the instrumentation passes yet:
clang -S -emit-llvm -fsanitize=thread -Xclang -disable-llvm-passes tiny_race.c -o tiny_race_tsan.ll
The -Xclang -disable-llvm-passes flag stops clang from automatically running the TSan passes, but keeps all necessary attributes (like sanitize_thread on functions) and metadata that the passes need.
Then run your original opt command on this prepared IR:
opt -passes='tsan-module,tsan' tiny_race_tsan.ll -S -o myInstrumented.ll
Option 2: Enable TSan Mode Directly in Opt
If you want to stick with your original unmodified IR, just add the -sanitize=thread flag to your opt command to force the passes into full TSan mode:
opt -sanitize=thread -passes='tsan-module,tsan' tiny_race.ll -S -o myInstrumented.ll
Verification
Either approach will produce an IR file that matches the output of clang -fsanitize=thread -S:
Thread1will get full instrumentation (including__tsan_func_entry,__tsan_write4, and__tsan_func_exit)- Memory accesses to
Globalinmainwill have__tsan_write4/__tsan_read4calls - Thread operations like
pthread_create/pthread_joinwill be properly tracked
内容的提问来源于stack exchange,提问作者Farzam

