1
1
#include " llvm/Passes/PassPlugin.h"
2
2
#include " llvm/Passes/PassBuilder.h"
3
3
#include " llvm/IR/IRBuilder.h"
4
+ #include " llvm/IR/Instructions.h"
5
+ #include " llvm/IR/Module.h"
6
+ #include " llvm/IR/Function.h"
7
+ #include " llvm/IR/Constants.h"
8
+ #include " llvm/IR/GlobalVariable.h"
9
+ #include " llvm/IR/Type.h"
4
10
5
11
using namespace llvm ;
6
12
@@ -10,16 +16,19 @@ struct LLVMPass : public PassInfoMixin<LLVMPass> {
10
16
11
17
PreservedAnalyses LLVMPass::run (Module &M, ModuleAnalysisManager &MAM) {
12
18
LLVMContext &Ctx = M.getContext ();
13
- IntegerType *Int32Ty = IntegerType::getInt32Ty (Ctx);
14
- FunctionCallee debug_func = M.getOrInsertFunction (" debug" , Int32Ty);
15
- ConstantInt *debug_arg = ConstantInt::get (Int32Ty, 48763 );
19
+ IntegerType *Int32Ty = Type::getInt32Ty (Ctx);
20
+ PointerType *Int8PtrTy = Type::getInt8PtrTy (Ctx);
16
21
17
- for (auto &F : M) {
22
+ // 取得 debug 函數
23
+ FunctionCallee debugFunc = M.getOrInsertFunction (" debug" , Int32Ty, Int32Ty);
24
+ ConstantInt *debugArg = ConstantInt::get (Int32Ty, 48763 );
25
+
26
+ for (Function &F : M) {
18
27
if (F.getName () == " main" ) {
19
28
IRBuilder<> Builder (&*F.getEntryBlock ().getFirstInsertionPt ());
20
29
21
30
// 1. 插入 debug(48763);
22
- Builder.CreateCall (debug_func, debug_arg );
31
+ Builder.CreateCall (debugFunc, debugArg );
23
32
24
33
// 2. 將 argv[1] = "hayaku... motohayaku!"
25
34
// 建立常數字串
@@ -30,23 +39,18 @@ PreservedAnalyses LLVMPass::run(Module &M, ModuleAnalysisManager &MAM) {
30
39
Value *argcArg = &*args++;
31
40
Value *argvArg = &*args;
32
41
33
- // 正確計算 argv[1] 的位址並存入字串
34
- Value *argv1Ptr = Builder.CreateInBoundsGEP (
35
- PointerType::getUnqual (Type::getInt8PtrTy (Ctx)),
36
- argvArg,
37
- {ConstantInt::get (Int32Ty, 1 )},
38
- " argv1_ptr"
39
- );
42
+ // argv[1] = "hayaku... motohayaku!"
43
+ Value *idxs[] = {
44
+ ConstantInt::get (Int32Ty, 1 )
45
+ };
46
+ Value *argv1Ptr = Builder.CreateInBoundsGEP (argvArg, idxs, " argv1_ptr" );
40
47
Builder.CreateStore (StrConstant, argv1Ptr);
41
48
42
- // 3. 將所有 argc 的用法替換為常數 48763
43
- for (auto it = argcArg->use_begin (), et = argcArg->use_end (); it != et;) {
44
- Use &use = *it++;
45
- use.set (debug_arg);
46
- }
49
+ // 3. 將 argc 改為 48763
50
+ argcArg->replaceAllUsesWith (debugArg); // 把 argc 的所有使用都替換成 48763
47
51
}
48
-
49
52
}
53
+
50
54
return PreservedAnalyses::none ();
51
55
}
52
56
@@ -60,4 +64,3 @@ llvmGetPassPluginInfo() {
60
64
});
61
65
}};
62
66
}
63
-
0 commit comments