I want to modify the AST by clang LibTooling. How can I clone an AST node or add a new one, e.g. I'd like to create a BinaryOperator
with ADD opcode
相关问题
- CMakeList file to generate LLVM bitcode file from
- AddressSanitizer blacklist in c++ not working
-
Apple Clang and numeric_limits
::max() is - Why clang missing default argument on parameter pa
- LLVM OPT not giving optimised file as output.
相关文章
- How do I generate an AST from a string of C++ usin
- clang error: non-type template argument refers to
- Swift and Objective-c framework exposes its intern
- Compiling a .C file: Undefined symbols for archite
- (Optimization?) Bug regarding GCC std::thread
- What does Clang's 'type_visibility' at
- How to clone or create an AST Stmt node of clang?
- Unable to use f2py to link large PETSc/SLEPc Fortr
Creating new AST nodes is quite cumbersome in Clang, and it's not the recommended way to use libTooling. Rather, you should "read" the AST and emit back code, or code changes (rewritings, replacements, etc).
See this article and other articles (and code samples) linked from it for more information on the right way to do this.
Some of the clang's AST nodes (classes) have a static Create method that is used to allocate an instance of that node whose memory is managed by the ASTContext instance passed to it. For these classes you may use this method for instantiation purposes. Check clang::DeclRefExpr class for instance.
Other classes miss this method but have public constructor that you may be used to instantiate the object. However, the vanilla new and delete operators are purposely hidden so you cannot use them to instantiate the objects on the heap. Instead, you must use placement new/delete operators providing ASTContext instance as an argument.
Personally, I prefer to allocate all clang related objects using ASTContext instance and let it manage the memory internally so I don't have to bother with it (all memory will get released when ASTContext instance gets destroyed).
Here is a simple class that allocates the memory for the clang object using the placement new operator and ASTContext instance:
Regarding the AST modifications, probably the best way to accomplish this is to inherit the TreeTransform class and override its Rebuild methods that are invoked to produce new statements for various AST nodes.
If all you require is to replace one AST node with another, very simple way to achieve this is to find its immediate parent statement and then use std::replace on its children. For example: