1.在github页面下载最新的llvm工程,现在最新的版本应该对应着是llvm13
cmake生成xcode工程

cd llvm-project
cmake -S llvm -B build -G Xcode -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi"

-S 指定llvm文件夹为源

2.在llvm-project/llvm/lib/Transforms文件夹新建自定义的pass文件夹

cd llvm-project/llvm/lib/Transforms

mkdir MyPass

在MyPass文件夹下新建一个CMakeLists.txt

image.png
写入

add_llvm_library( MYPass MODULE
  MYPass.cpp

  DEPENDS
  intrinsics_gen
  PLUGIN_TOOL
  opt
  )

3.在llvm-project/llvm/lib/Transforms/CmakeLists.txt中添加文件夹目录

add_subdirectory(MYPass)

image.png

4.编写Pass

#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

using namespace llvm;

#define DEBUG_TYPE "hello"

STATISTIC(HelloCounter, "Counts number of functions greeted");

namespace {
  // Hello - The first implementation, without getAnalysisUsage.
struct Hello : public FunctionPass {
    static char ID; // Pass identification, replacement for typeid
    Hello() : FunctionPass(ID) {}
    
    bool runOnFunction(Function &F) override {
        ++HelloCounter;
        errs() << "Hello: ";
        errs().write_escaped(F.getName()) << '\n';
        return false;
    }
    void getAnalysisUsage(AnalysisUsage &AU) const override {
        AU.setPreservesAll();
    }
    
    void releaseMemory() override {
        errs() << "releaseMemory";
    }

};
}

char Hello::ID = 0;
static RegisterPass<Hello> X("hello", "Hello World Pass",false,false);

static RegisterStandardPasses Y2(PassManagerBuilder::EP_EarlyAsPossible,[](const PassManagerBuilder &Builder,legacy::PassManagerBase &PM) {
    PM.add(new Hello());
     
});

5.构建和编译pass

cd /yourPath/llvm-project

cmake -S llvm -B build -G Xcode -DLLVM_ENABLE_PROJECTS="clang;libcxx;libcxxabi"

在xcode里选择sechme:MYPass,开始编译
编译完成后,可在llvm-project/build/Debug/bin目录下找到编译后的可执行文件,以及llvm-project/build/Debug/lib目录下找到LLVM pass的动态库
5.opt使用MYPass.dylib,这里官方文档有误,需要通过-enable-new-pm=0指定用legacy pass manager

./opt -load ../lib/LLVMHello.dylib -hello -enable-new-pm=0 < hello.bc >/dev/null

6.clang使用MYPass.dylib,这里官方文档有误,需要通过-flegacy-pass-manager指定用legacy pass manager
hello.mm只有c/c++基本库女人

./clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.2.sdk -Xclang -load -Xclang ../lib/LLVMHello.dylib -flegacy-pass-manager hello.mm

-isysroot指定系统sdk版本
如果有用到oc的库编译还需指定-framework Foundation

./clang -framework Foundation -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.2.sdk -Xclang -load -Xclang ../lib/LLVMHello.dylib -flegacy-pass-manager hello.m

hello.m源码

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
int main(){
    NSLog(@"songxuhua");
  return 0;
}

宋冬野
32 声望4 粉丝

引用和评论

0 条评论