Summary of clang15 plugin (c++ source code modification plugin) (non-llvm plugin)

clang 15 plugin, the input is c++ source code.

The clang plugin is not an LLVM plugin.
The input to the LLVM plugin is an intermediate representation.
The c++ source code is converted into an intermediate representation, and various readable symbols in the source code are difficult to obtain at this time.
Although in theory the LLVM plug-in can obtain symbols from debugging information libraries such as dwarf when facing the intermediate representation, it is not easy and not direct.

Clang15 plugin (c++ source code modification plugin) summary:

1. Sharing the Rewriter, causing the later write to overwrite the previous write, and the previous write to be lost

  • Therefore, the correct way of writing is that this plug-in can only have one Rewriter object globally.

2. A simple Rewriter object will not crash in the early stage (in Act), but will crash in the late stage (Visitor). You should use the so-called smart pointer const std::shared_ptr

  • Simple Rewriter objects Rewriter rewriter;are used as Act member fields. In the early stage (in the CreateASTConsumer method of Act), there will be no Segmentation fault, and in the late stage (Visitor), there will be Segmentation fault.
  • After the simple object is changed const std::shared_ptr<Rewriter> mRewriter_ptr, it is normal and no longer Segmentation fault.

3. Running the plugin independently is not the same as running the plugin loaded by clang

  • The pure Rewriter object Rewriter rewriter;will not cause Segmentation fault when the plugin is running independently, but it will cause Segmentation fault when the plugin is loaded and run by clang.

It can be seen that the correct way to write Rewriter is as follows:

/Act中(早期)的Rewriter样子:(Act是Rewriter源头、是Rewriter的创建者。)
class XxxAstAct : public PluginASTAction {
   
    
    
public:
    std::unique_ptr<ASTConsumer>
    CreateASTConsumer(CompilerInstance &CI,
                      llvm::StringRef inFile) override {
   
    
    
      SourceManager &SM = CI.getSourceManager();
      LangOptions &langOptions = CI.getLangOpts();
      ASTContext &astContext = CI.getASTContext();
      mRewriter_ptr->setSourceMgr(SM, langOptions);//Rewriter对象设置
      return std::make_unique<XxxAstConsumer>(CI,mRewriter_ptr, &astContext, SM, langOptions);//Consumer进一步把Rewriter
    }

    PluginASTAction::ActionType getActionType() override {
   
    
    
      //本插件自动运行:  在MainAction后运行本插件
      return AddAfterMainAction;
    }

private:
    const std::shared_ptr<Rewriter

Guess you like

Origin blog.csdn.net/hfcaoguilin/article/details/131892551