LibASTMatchersTutorial.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. ===============================================================
  2. Tutorial for building tools using LibTooling and LibASTMatchers
  3. ===============================================================
  4. This document is intended to show how to build a useful source-to-source
  5. translation tool based on Clang's `LibTooling <LibTooling.html>`_. It is
  6. explicitly aimed at people who are new to Clang, so all you should need
  7. is a working knowledge of C++ and the command line.
  8. In order to work on the compiler, you need some basic knowledge of the
  9. abstract syntax tree (AST). To this end, the reader is incouraged to
  10. skim the :doc:`Introduction to the Clang
  11. AST <IntroductionToTheClangAST>`
  12. Step 0: Obtaining Clang
  13. =======================
  14. As Clang is part of the LLVM project, you'll need to download LLVM's
  15. source code first. Both Clang and LLVM are in the same git repository,
  16. under different directories. For further information, see the `getting
  17. started guide <https://llvm.org/docs/GettingStarted.html>`_.
  18. .. code-block:: console
  19. cd ~/clang-llvm
  20. git clone https://github.com/llvm/llvm-project.git
  21. Next you need to obtain the CMake build system and Ninja build tool.
  22. .. code-block:: console
  23. cd ~/clang-llvm
  24. git clone https://github.com/martine/ninja.git
  25. cd ninja
  26. git checkout release
  27. ./bootstrap.py
  28. sudo cp ninja /usr/bin/
  29. cd ~/clang-llvm
  30. git clone git://cmake.org/stage/cmake.git
  31. cd cmake
  32. git checkout next
  33. ./bootstrap
  34. make
  35. sudo make install
  36. Okay. Now we'll build Clang!
  37. .. code-block:: console
  38. cd ~/clang-llvm
  39. mkdir build && cd build
  40. cmake -G Ninja ../llvm -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra" -DLLVM_BUILD_TESTS=ON # Enable tests; default is off.
  41. ninja
  42. ninja check # Test LLVM only.
  43. ninja clang-test # Test Clang only.
  44. ninja install
  45. And we're live.
  46. All of the tests should pass.
  47. Finally, we want to set Clang as its own compiler.
  48. .. code-block:: console
  49. cd ~/clang-llvm/build
  50. ccmake ../llvm
  51. The second command will bring up a GUI for configuring Clang. You need
  52. to set the entry for ``CMAKE_CXX_COMPILER``. Press ``'t'`` to turn on
  53. advanced mode. Scroll down to ``CMAKE_CXX_COMPILER``, and set it to
  54. ``/usr/bin/clang++``, or wherever you installed it. Press ``'c'`` to
  55. configure, then ``'g'`` to generate CMake's files.
  56. Finally, run ninja one last time, and you're done.
  57. Step 1: Create a ClangTool
  58. ==========================
  59. Now that we have enough background knowledge, it's time to create the
  60. simplest productive ClangTool in existence: a syntax checker. While this
  61. already exists as ``clang-check``, it's important to understand what's
  62. going on.
  63. First, we'll need to create a new directory for our tool and tell CMake
  64. that it exists. As this is not going to be a core clang tool, it will
  65. live in the ``clang-tools-extra`` repository.
  66. .. code-block:: console
  67. cd ~/clang-llvm
  68. mkdir clang-tools-extra/loop-convert
  69. echo 'add_subdirectory(loop-convert)' >> clang-tools-extra/CMakeLists.txt
  70. vim clang-tools-extra/loop-convert/CMakeLists.txt
  71. CMakeLists.txt should have the following contents:
  72. ::
  73. set(LLVM_LINK_COMPONENTS support)
  74. add_clang_executable(loop-convert
  75. LoopConvert.cpp
  76. )
  77. target_link_libraries(loop-convert
  78. PRIVATE
  79. clangTooling
  80. clangBasic
  81. clangASTMatchers
  82. )
  83. With that done, Ninja will be able to compile our tool. Let's give it
  84. something to compile! Put the following into
  85. ``clang-tools-extra/loop-convert/LoopConvert.cpp``. A detailed explanation of
  86. why the different parts are needed can be found in the `LibTooling
  87. documentation <LibTooling.html>`_.
  88. .. code-block:: c++
  89. // Declares clang::SyntaxOnlyAction.
  90. #include "clang/Frontend/FrontendActions.h"
  91. #include "clang/Tooling/CommonOptionsParser.h"
  92. #include "clang/Tooling/Tooling.h"
  93. // Declares llvm::cl::extrahelp.
  94. #include "llvm/Support/CommandLine.h"
  95. using namespace clang::tooling;
  96. using namespace llvm;
  97. // Apply a custom category to all command-line options so that they are the
  98. // only ones displayed.
  99. static llvm::cl::OptionCategory MyToolCategory("my-tool options");
  100. // CommonOptionsParser declares HelpMessage with a description of the common
  101. // command-line options related to the compilation database and input files.
  102. // It's nice to have this help message in all tools.
  103. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  104. // A help message for this specific tool can be added afterwards.
  105. static cl::extrahelp MoreHelp("\nMore help text...\n");
  106. int main(int argc, const char **argv) {
  107. CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
  108. ClangTool Tool(OptionsParser.getCompilations(),
  109. OptionsParser.getSourcePathList());
  110. return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
  111. }
  112. And that's it! You can compile our new tool by running ninja from the
  113. ``build`` directory.
  114. .. code-block:: console
  115. cd ~/clang-llvm/build
  116. ninja
  117. You should now be able to run the syntax checker, which is located in
  118. ``~/clang-llvm/build/bin``, on any source file. Try it!
  119. .. code-block:: console
  120. echo "int main() { return 0; }" > test.cpp
  121. bin/loop-convert test.cpp --
  122. Note the two dashes after we specify the source file. The additional
  123. options for the compiler are passed after the dashes rather than loading
  124. them from a compilation database - there just aren't any options needed
  125. right now.
  126. Intermezzo: Learn AST matcher basics
  127. ====================================
  128. Clang recently introduced the :doc:`ASTMatcher
  129. library <LibASTMatchers>` to provide a simple, powerful, and
  130. concise way to describe specific patterns in the AST. Implemented as a
  131. DSL powered by macros and templates (see
  132. `ASTMatchers.h <../doxygen/ASTMatchers_8h_source.html>`_ if you're
  133. curious), matchers offer the feel of algebraic data types common to
  134. functional programming languages.
  135. For example, suppose you wanted to examine only binary operators. There
  136. is a matcher to do exactly that, conveniently named ``binaryOperator``.
  137. I'll give you one guess what this matcher does:
  138. .. code-block:: c++
  139. binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))))
  140. Shockingly, it will match against addition expressions whose left hand
  141. side is exactly the literal 0. It will not match against other forms of
  142. 0, such as ``'\0'`` or ``NULL``, but it will match against macros that
  143. expand to 0. The matcher will also not match against calls to the
  144. overloaded operator ``'+'``, as there is a separate ``operatorCallExpr``
  145. matcher to handle overloaded operators.
  146. There are AST matchers to match all the different nodes of the AST,
  147. narrowing matchers to only match AST nodes fulfilling specific criteria,
  148. and traversal matchers to get from one kind of AST node to another. For
  149. a complete list of AST matchers, take a look at the `AST Matcher
  150. References <LibASTMatchersReference.html>`_
  151. All matcher that are nouns describe entities in the AST and can be
  152. bound, so that they can be referred to whenever a match is found. To do
  153. so, simply call the method ``bind`` on these matchers, e.g.:
  154. .. code-block:: c++
  155. variable(hasType(isInteger())).bind("intvar")
  156. Step 2: Using AST matchers
  157. ==========================
  158. Okay, on to using matchers for real. Let's start by defining a matcher
  159. which will capture all ``for`` statements that define a new variable
  160. initialized to zero. Let's start with matching all ``for`` loops:
  161. .. code-block:: c++
  162. forStmt()
  163. Next, we want to specify that a single variable is declared in the first
  164. portion of the loop, so we can extend the matcher to
  165. .. code-block:: c++
  166. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl()))))
  167. Finally, we can add the condition that the variable is initialized to
  168. zero.
  169. .. code-block:: c++
  170. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  171. hasInitializer(integerLiteral(equals(0))))))))
  172. It is fairly easy to read and understand the matcher definition ("match
  173. loops whose init portion declares a single variable which is initialized
  174. to the integer literal 0"), but deciding that every piece is necessary
  175. is more difficult. Note that this matcher will not match loops whose
  176. variables are initialized to ``'\0'``, ``0.0``, ``NULL``, or any form of
  177. zero besides the integer 0.
  178. The last step is giving the matcher a name and binding the ``ForStmt``
  179. as we will want to do something with it:
  180. .. code-block:: c++
  181. StatementMatcher LoopMatcher =
  182. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  183. hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
  184. Once you have defined your matchers, you will need to add a little more
  185. scaffolding in order to run them. Matchers are paired with a
  186. ``MatchCallback`` and registered with a ``MatchFinder`` object, then run
  187. from a ``ClangTool``. More code!
  188. Add the following to ``LoopConvert.cpp``:
  189. .. code-block:: c++
  190. #include "clang/ASTMatchers/ASTMatchers.h"
  191. #include "clang/ASTMatchers/ASTMatchFinder.h"
  192. using namespace clang;
  193. using namespace clang::ast_matchers;
  194. StatementMatcher LoopMatcher =
  195. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  196. hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
  197. class LoopPrinter : public MatchFinder::MatchCallback {
  198. public :
  199. virtual void run(const MatchFinder::MatchResult &Result) {
  200. if (const ForStmt *FS = Result.Nodes.getNodeAs<clang::ForStmt>("forLoop"))
  201. FS->dump();
  202. }
  203. };
  204. And change ``main()`` to:
  205. .. code-block:: c++
  206. int main(int argc, const char **argv) {
  207. CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
  208. ClangTool Tool(OptionsParser.getCompilations(),
  209. OptionsParser.getSourcePathList());
  210. LoopPrinter Printer;
  211. MatchFinder Finder;
  212. Finder.addMatcher(LoopMatcher, &Printer);
  213. return Tool.run(newFrontendActionFactory(&Finder).get());
  214. }
  215. Now, you should be able to recompile and run the code to discover for
  216. loops. Create a new file with a few examples, and test out our new
  217. handiwork:
  218. .. code-block:: console
  219. cd ~/clang-llvm/llvm/llvm_build/
  220. ninja loop-convert
  221. vim ~/test-files/simple-loops.cc
  222. bin/loop-convert ~/test-files/simple-loops.cc
  223. Step 3.5: More Complicated Matchers
  224. ===================================
  225. Our simple matcher is capable of discovering for loops, but we would
  226. still need to filter out many more ourselves. We can do a good portion
  227. of the remaining work with some cleverly chosen matchers, but first we
  228. need to decide exactly which properties we want to allow.
  229. How can we characterize for loops over arrays which would be eligible
  230. for translation to range-based syntax? Range based loops over arrays of
  231. size ``N`` that:
  232. - start at index ``0``
  233. - iterate consecutively
  234. - end at index ``N-1``
  235. We already check for (1), so all we need to add is a check to the loop's
  236. condition to ensure that the loop's index variable is compared against
  237. ``N`` and another check to ensure that the increment step just
  238. increments this same variable. The matcher for (2) is straightforward:
  239. require a pre- or post-increment of the same variable declared in the
  240. init portion.
  241. Unfortunately, such a matcher is impossible to write. Matchers contain
  242. no logic for comparing two arbitrary AST nodes and determining whether
  243. or not they are equal, so the best we can do is matching more than we
  244. would like to allow, and punting extra comparisons to the callback.
  245. In any case, we can start building this sub-matcher. We can require that
  246. the increment step be a unary increment like this:
  247. .. code-block:: c++
  248. hasIncrement(unaryOperator(hasOperatorName("++")))
  249. Specifying what is incremented introduces another quirk of Clang's AST:
  250. Usages of variables are represented as ``DeclRefExpr``'s ("declaration
  251. reference expressions") because they are expressions which refer to
  252. variable declarations. To find a ``unaryOperator`` that refers to a
  253. specific declaration, we can simply add a second condition to it:
  254. .. code-block:: c++
  255. hasIncrement(unaryOperator(
  256. hasOperatorName("++"),
  257. hasUnaryOperand(declRefExpr())))
  258. Furthermore, we can restrict our matcher to only match if the
  259. incremented variable is an integer:
  260. .. code-block:: c++
  261. hasIncrement(unaryOperator(
  262. hasOperatorName("++"),
  263. hasUnaryOperand(declRefExpr(to(varDecl(hasType(isInteger())))))))
  264. And the last step will be to attach an identifier to this variable, so
  265. that we can retrieve it in the callback:
  266. .. code-block:: c++
  267. hasIncrement(unaryOperator(
  268. hasOperatorName("++"),
  269. hasUnaryOperand(declRefExpr(to(
  270. varDecl(hasType(isInteger())).bind("incrementVariable"))))))
  271. We can add this code to the definition of ``LoopMatcher`` and make sure
  272. that our program, outfitted with the new matcher, only prints out loops
  273. that declare a single variable initialized to zero and have an increment
  274. step consisting of a unary increment of some variable.
  275. Now, we just need to add a matcher to check if the condition part of the
  276. ``for`` loop compares a variable against the size of the array. There is
  277. only one problem - we don't know which array we're iterating over
  278. without looking at the body of the loop! We are again restricted to
  279. approximating the result we want with matchers, filling in the details
  280. in the callback. So we start with:
  281. .. code-block:: c++
  282. hasCondition(binaryOperator(hasOperatorName("<"))
  283. It makes sense to ensure that the left-hand side is a reference to a
  284. variable, and that the right-hand side has integer type.
  285. .. code-block:: c++
  286. hasCondition(binaryOperator(
  287. hasOperatorName("<"),
  288. hasLHS(declRefExpr(to(varDecl(hasType(isInteger()))))),
  289. hasRHS(expr(hasType(isInteger())))))
  290. Why? Because it doesn't work. Of the three loops provided in
  291. ``test-files/simple.cpp``, zero of them have a matching condition. A
  292. quick look at the AST dump of the first for loop, produced by the
  293. previous iteration of loop-convert, shows us the answer:
  294. ::
  295. (ForStmt 0x173b240
  296. (DeclStmt 0x173afc8
  297. 0x173af50 "int i =
  298. (IntegerLiteral 0x173afa8 'int' 0)")
  299. <<>>
  300. (BinaryOperator 0x173b060 '_Bool' '<'
  301. (ImplicitCastExpr 0x173b030 'int'
  302. (DeclRefExpr 0x173afe0 'int' lvalue Var 0x173af50 'i' 'int'))
  303. (ImplicitCastExpr 0x173b048 'int'
  304. (DeclRefExpr 0x173b008 'const int' lvalue Var 0x170fa80 'N' 'const int')))
  305. (UnaryOperator 0x173b0b0 'int' lvalue prefix '++'
  306. (DeclRefExpr 0x173b088 'int' lvalue Var 0x173af50 'i' 'int'))
  307. (CompoundStatement ...
  308. We already know that the declaration and increments both match, or this
  309. loop wouldn't have been dumped. The culprit lies in the implicit cast
  310. applied to the first operand (i.e. the LHS) of the less-than operator,
  311. an L-value to R-value conversion applied to the expression referencing
  312. ``i``. Thankfully, the matcher library offers a solution to this problem
  313. in the form of ``ignoringParenImpCasts``, which instructs the matcher to
  314. ignore implicit casts and parentheses before continuing to match.
  315. Adjusting the condition operator will restore the desired match.
  316. .. code-block:: c++
  317. hasCondition(binaryOperator(
  318. hasOperatorName("<"),
  319. hasLHS(ignoringParenImpCasts(declRefExpr(
  320. to(varDecl(hasType(isInteger())))))),
  321. hasRHS(expr(hasType(isInteger())))))
  322. After adding binds to the expressions we wished to capture and
  323. extracting the identifier strings into variables, we have array-step-2
  324. completed.
  325. Step 4: Retrieving Matched Nodes
  326. ================================
  327. So far, the matcher callback isn't very interesting: it just dumps the
  328. loop's AST. At some point, we will need to make changes to the input
  329. source code. Next, we'll work on using the nodes we bound in the
  330. previous step.
  331. The ``MatchFinder::run()`` callback takes a
  332. ``MatchFinder::MatchResult&`` as its parameter. We're most interested in
  333. its ``Context`` and ``Nodes`` members. Clang uses the ``ASTContext``
  334. class to represent contextual information about the AST, as the name
  335. implies, though the most functionally important detail is that several
  336. operations require an ``ASTContext*`` parameter. More immediately useful
  337. is the set of matched nodes, and how we retrieve them.
  338. Since we bind three variables (identified by ConditionVarName,
  339. InitVarName, and IncrementVarName), we can obtain the matched nodes by
  340. using the ``getNodeAs()`` member function.
  341. In ``LoopConvert.cpp`` add
  342. .. code-block:: c++
  343. #include "clang/AST/ASTContext.h"
  344. Change ``LoopMatcher`` to
  345. .. code-block:: c++
  346. StatementMatcher LoopMatcher =
  347. forStmt(hasLoopInit(declStmt(
  348. hasSingleDecl(varDecl(hasInitializer(integerLiteral(equals(0))))
  349. .bind("initVarName")))),
  350. hasIncrement(unaryOperator(
  351. hasOperatorName("++"),
  352. hasUnaryOperand(declRefExpr(
  353. to(varDecl(hasType(isInteger())).bind("incVarName")))))),
  354. hasCondition(binaryOperator(
  355. hasOperatorName("<"),
  356. hasLHS(ignoringParenImpCasts(declRefExpr(
  357. to(varDecl(hasType(isInteger())).bind("condVarName"))))),
  358. hasRHS(expr(hasType(isInteger())))))).bind("forLoop");
  359. And change ``LoopPrinter::run`` to
  360. .. code-block:: c++
  361. void LoopPrinter::run(const MatchFinder::MatchResult &Result) {
  362. ASTContext *Context = Result.Context;
  363. const ForStmt *FS = Result.Nodes.getNodeAs<ForStmt>("forLoop");
  364. // We do not want to convert header files!
  365. if (!FS || !Context->getSourceManager().isWrittenInMainFile(FS->getForLoc()))
  366. return;
  367. const VarDecl *IncVar = Result.Nodes.getNodeAs<VarDecl>("incVarName");
  368. const VarDecl *CondVar = Result.Nodes.getNodeAs<VarDecl>("condVarName");
  369. const VarDecl *InitVar = Result.Nodes.getNodeAs<VarDecl>("initVarName");
  370. if (!areSameVariable(IncVar, CondVar) || !areSameVariable(IncVar, InitVar))
  371. return;
  372. llvm::outs() << "Potential array-based loop discovered.\n";
  373. }
  374. Clang associates a ``VarDecl`` with each variable to represent the variable's
  375. declaration. Since the "canonical" form of each declaration is unique by
  376. address, all we need to do is make sure neither ``ValueDecl`` (base class of
  377. ``VarDecl``) is ``NULL`` and compare the canonical Decls.
  378. .. code-block:: c++
  379. static bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
  380. return First && Second &&
  381. First->getCanonicalDecl() == Second->getCanonicalDecl();
  382. }
  383. If execution reaches the end of ``LoopPrinter::run()``, we know that the
  384. loop shell that looks like
  385. .. code-block:: c++
  386. for (int i= 0; i < expr(); ++i) { ... }
  387. For now, we will just print a message explaining that we found a loop.
  388. The next section will deal with recursively traversing the AST to
  389. discover all changes needed.
  390. As a side note, it's not as trivial to test if two expressions are the same,
  391. though Clang has already done the hard work for us by providing a way to
  392. canonicalize expressions:
  393. .. code-block:: c++
  394. static bool areSameExpr(ASTContext *Context, const Expr *First,
  395. const Expr *Second) {
  396. if (!First || !Second)
  397. return false;
  398. llvm::FoldingSetNodeID FirstID, SecondID;
  399. First->Profile(FirstID, *Context, true);
  400. Second->Profile(SecondID, *Context, true);
  401. return FirstID == SecondID;
  402. }
  403. This code relies on the comparison between two
  404. ``llvm::FoldingSetNodeIDs``. As the documentation for
  405. ``Stmt::Profile()`` indicates, the ``Profile()`` member function builds
  406. a description of a node in the AST, based on its properties, along with
  407. those of its children. ``FoldingSetNodeID`` then serves as a hash we can
  408. use to compare expressions. We will need ``areSameExpr`` later. Before
  409. you run the new code on the additional loops added to
  410. test-files/simple.cpp, try to figure out which ones will be considered
  411. potentially convertible.