### Example header B.h includes A.h Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Header file B.h includes A.h. Part of the prebuilt modules example setup. ```c /* B.h */ #include "A.h" ``` -------------------------------- ### cxxDeductionGuideDecl matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for cxxDeductionGuideDecl matcher. It matches the deduction guide 'X(int) -> X'. ```cpp Matches user-defined and implicitly generated deduction guide. Example matches the deduction guide. template class X { X(int) }; X(int) -> X; ``` -------------------------------- ### caseStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the caseStmt matcher. ```cpp switch(a) { case 42: break; default: break; } ``` -------------------------------- ### Export-as example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example showing that MyFrameworkCore is re-exported via the module MyFramework. ```plaintext module MyFrameworkCore { export_as MyFramework } ``` -------------------------------- ### forEachConstructorInitializer example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for forEachConstructorInitializer matcher, binding each field initializer. ```cpp class A { A() : i(42), j(42) {} int i; int j; }; cxxConstructorDecl(forEachConstructorInitializer( forField(decl().bind("x")) )) ``` -------------------------------- ### continueStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the continueStmt matcher. ```cpp while (true) { continue; } ``` -------------------------------- ### Getting Started: BankAccount class with GUARDED_BY Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ThreadSafetyAnalysis.html Shows a minimal C++ class using the Thread Safety Analysis annotations. The example declares a Mutex member and a balance field guarded by it; the depositImpl method triggers a warning because it writes balance without locking mu. Use this as the starting point for annotating your own classes. ```cpp #include "mutex.h" class BankAccount { private: Mutex mu; int balance GUARDED_BY(mu); void depositImpl(int amount) { balance += amount; // WARNING! Cannot write balance without locking mu. } }; ``` -------------------------------- ### Generated aarch64 assembly with -O2 Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ShadowCallStack.html Output of compiling the example with -O2. Shows the stack frame setup and call to bar. ```assembly stp x29, x30, [sp, #-16]! mov x29, sp bl bar add w0, w0, #1 ldp x29, x30, [sp], #16 ret ``` -------------------------------- ### cStyleCastExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cStyleCastExpr matcher. ```cpp int i = (int) 2.2f; ``` -------------------------------- ### coreturnStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the coreturnStmt matcher. ```cpp while (true) { co_return; } ``` -------------------------------- ### cxxBoolLiteral example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxBoolLiteral matcher. ```cpp true ``` -------------------------------- ### compoundStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the compoundStmt matcher. ```cpp for (;;) {{}} ``` -------------------------------- ### BreakBeforeBraces GNU example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Example for the BreakBeforeBraces style option with configuration value GNU. Braces are always broken and control statements get an extra indentation level. ```cpp namespace N { enum E { E1, E2, }; class C { public: C(); }; bool baz(int i) { try { do { switch (i) { case 1: { foobar(); break; } default: { break; } } } while (--i); return true; } catch (...) { handleError(); return false; } } void foo(bool b) { if (b) { baz(2); } else { baz(5); } } void bar() { foo(true); } } // namespace N ``` -------------------------------- ### hasAnyConstructorInitializer example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasAnyConstructorInitializer matcher, matching a constructor initializer. ```cpp struct Foo { Foo() : foo_(1) { } int foo_; }; cxxRecordDecl(has(cxxConstructorDecl( hasAnyConstructorInitializer(anything()) ))) ``` -------------------------------- ### cxxConstCastExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxConstCastExpr matcher. ```cpp int n = 42; const int &r(n); int* p = const_cast(&r); ``` -------------------------------- ### Install Ninja and CMake Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersTutorial.html Build and install Ninja and CMake, which are required to build Clang. ```bash cd ~/clang-llvm git clone https://github.com/martine/ninja.git cd ninja git checkout release ./bootstrap.py sudo cp ninja /usr/bin/ cd ~/clang-llvm git clone git://cmake.org/stage/cmake.git cd cmake git checkout next ./bootstrap make sudo make install ``` -------------------------------- ### constantExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the constantExpr matcher. ```cpp switch (a) { case 37: break; } ``` -------------------------------- ### binaryOperator example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the binaryOperator matcher (GNU extension). ```cpp (a ?: b) + 42; ``` -------------------------------- ### coyieldExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the coyieldExpr matcher. ```cpp co_yield 1; ``` -------------------------------- ### cxxCatchStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxCatchStmt matcher. ```cpp try {} catch(int i) {} ``` -------------------------------- ### cxxConstructExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxConstructExpr matcher. ```cpp void f(const string &a, const string &b); char *ptr; int n; f(string(ptr, n), ptr); ``` -------------------------------- ### castExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the castExpr matcher. ```cpp (int) 3; const_cast(SubExpr); char c = 0; ``` -------------------------------- ### binaryOperator example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the binaryOperator matcher. ```cpp !(a || b) ``` -------------------------------- ### matchesName matcher examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows matchesName matching. First example matches X with regexp == "::X". Second example matches X with regexp one of "::X", "^foo::.*X", among others. ```cpp class X; ``` ```cpp namespace foo { namespace bar { class X; } } ``` -------------------------------- ### breakStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the breakStmt matcher. ```cpp while (true) { break; } ``` -------------------------------- ### callExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the callExpr matcher. ```cpp X x; x.y(); y(); ``` -------------------------------- ### Example source file use.c Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Source file use.c includes B.h and calls a() if ENABLE_A is defined. Used in the prebuilt modules examples. ```c /* use.c */ #include "B.h" void use() { #ifdef ENABLE_A a(); #endif } ``` -------------------------------- ### ForEachMacros configuration example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Shows how to configure ForEachMacros in the .clang-format configuration file. ```yaml ForEachMacros: ['RANGES_FOR', 'FOREACH'] ``` -------------------------------- ### blockExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the blockExpr matcher. ```cpp void f() { ^{}(); } ``` -------------------------------- ### forField example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for forField matcher, matching the field declaration of a constructor initializer. ```cpp struct Foo { Foo() : foo_(1) { } int foo_; }; cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( forField(hasName("foo_")))))) ``` -------------------------------- ### Compile and run commands for trace-pc-guard example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SanitizerCoverage.html Compile the example with -fsanitize-coverage=trace-pc-guard, link with the callback object and AddressSanitizer, then run with ASAN_OPTIONS to strip the path prefix. ```bash clang++ -g -fsanitize-coverage=trace-pc-guard trace-pc-guard-example.cc -c clang++ trace-pc-guard-cb.cc trace-pc-guard-example.o -fsanitize=address ASAN_OPTIONS=strip_path_prefix=`pwd`/ ./a.out ``` -------------------------------- ### isExplicit matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the isExplicit matcher. Shows a template struct with constructors, conversion functions, and deduction guides, some marked explicit. The matcher matches only those with explicit specifier resolved to true. ```cpp template struct S { S(int); // #1 explicit S(double); // #2 operator int(); // #3 explicit operator bool(); // #4 explicit(false) S(bool) // # 7 explicit(true) S(char) // # 8 explicit(b) S(S) // # 9 }; S(int) -> S // #5 explicit S(double) -> S // #6 ``` -------------------------------- ### Install Ninja binary to /usr/local/bin Source: https://releases.llvm.org/13.0.0/tools/clang/docs/HowToSetupToolingForLLVM.html Copies the built Ninja binary to /usr/local/bin and makes it executable. Ninja does not require installation and can be placed anywhere in $PATH. ```shell $ sudo cp ninja /usr/local/bin/ $ sudo chmod a+rx /usr/local/bin/ninja ``` -------------------------------- ### ShortNamespaceLines comparison example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Shows how ShortNamespaceLines affects whether FixNamespaceComments adds end comments. With a value of 1, short namespaces (like namespace a) do not get an end comment; with 0, they do. Longer namespaces (like namespace b) always get the comment. ```cpp ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0 namespace a { namespace a { int foo; int foo; } } // namespace a ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0 namespace b { namespace b { int foo; int foo; int bar; int bar; } // namespace b } // namespace b ``` -------------------------------- ### cxxRecordDecl matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for cxxRecordDecl matcher. It matches the class declarations X and Z. ```cpp Matches C++ class declarations. Example matches X, Z class X; template class Z {}; ``` -------------------------------- ### isVirtual examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Two examples for isVirtual: one showing a virtual method and one showing virtual inheritance, with the matcher matching the virtual method and the virtual base classes. ```cpp class A { public: virtual void x(); // matches x }; ``` ```cpp class Base {}; class DirectlyDerived : virtual Base {}; // matches Base class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base ``` -------------------------------- ### Example output with -fdiagnostics-print-source-range-info Source: https://releases.llvm.org/13.0.0/tools/clang/docs/UsersManual.html Shows the machine-parseable source range information printed after the file/line/column. The ranges are brace-enclosed and list start and end locations. Column numbers count bytes from the beginning of the line. ```text exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expression ('int *' and '_Complex float') P = (P-42) + Gamma*4; ~~~~~~ ^ ~~~~~~~ ``` -------------------------------- ### BreakBeforeOperators All example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Example for the BreakBeforeOperators style option with configuration value All. Shows how operators are placed at the beginning of continuation lines. ```cpp LooooooooooongType loooooooooooooooooooooongVariable = someLooooooooooooooooongFunction(); bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa > ccccccccccccccccccccccccccccccccccccccccc; ``` -------------------------------- ### Input for begin() replacement Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example input code with a const container and a range-based for loop. ```cpp void foo() { const Container c; c.begin(); for (auto i : c) { } } ``` -------------------------------- ### SpacesInLineCommentPrefix examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Shows the effect of SpacesInLineCommentPrefix with different Minimum and Maximum values. Minimum = 1 Maximum = -1 forces one space but allows more; Minimum = 0 Maximum = 0 forces comments to start directly after the slashes. ```cpp Minimum = 1 Maximum = -1 // One space is forced // but more spaces are possible Minimum = 0 Maximum = 0 //Forces to start every comment directly after the slashes ``` -------------------------------- ### cxxCtorInitializer matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for cxxCtorInitializer matcher. It matches the initializer 'i(42)' in the constructor of class C. ```cpp Matches constructor initializers. Examples matches i(42). class C { C() : i(42) {} int i; }; ``` -------------------------------- ### Pointer dangling example with gsl::Owner and gsl::Pointer Source: https://releases.llvm.org/13.0.0/tools/clang/docs/AttributeReference.html Shows how the analysis treats a Pointer constructed from an Owner: the Pointer is considered to point inside the Owner, and becomes dangling when the Owner's lifetime ends. The final call to get() is an error. ```cpp int f() { IntPointer P; if (true) { IntOwner O(7); P = IntPointer(O); // P "points into" O } // P is dangling return P.get(); // error: Using a dangling Pointer. } ``` -------------------------------- ### BraceWrapping: example configuration Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Shows how to configure BraceWrapping when BreakBeforeBraces is set to Custom. ```yaml # Example of usage: BreakBeforeBraces: Custom BraceWrapping: AfterEnum: true AfterStruct: false SplitEmptyFunction: false ``` -------------------------------- ### hasExternalFormalLinkage examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows examples for hasExternalFormalLinkage. First example matches only z with varDecl(hasExternalFormalLinkage()). Second example matches f() because it has external formal linkage despite being unique to the translation unit. ```cpp void f() { int x; static int y; } int z; ``` ```cpp namespace { void f() {} } ``` -------------------------------- ### Enable all extensions except double support on R600 using -cl-ext Source: https://releases.llvm.org/13.0.0/tools/clang/docs/OpenCLSupport.html Use -cl-ext=-all,+cl_khr_fp16 to enable all known extensions except double support, while explicitly enabling the fp16 extension for the R600 target. ```bash $ clang -cc1 -triple r600-unknown-unknown -cl-ext=-all,+cl_khr_fp16 test.cl ``` -------------------------------- ### cxxDefaultArgExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxDefaultArgExpr matcher. ```cpp void f(int x, int y = 0); f(42); ``` -------------------------------- ### builtinType example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example code for builtinType matcher, showing builtin type declarations. ```cpp struct A {}; A a; int b; float c; bool d; ``` -------------------------------- ### Example module.modulemap defining modules A and B Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Module map file defining modules A and B, with B exporting all its submodules. Used in the prebuilt modules examples. ```c /* module.modulemap */ module A { header "A.h" } module B { header "B.h" export * } ``` -------------------------------- ### usingDecl matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Matches using declarations. The example shows a namespace with a variable and a using declaration that the matcher matches. ```cpp namespace X { int x; } using X::x; usingDecl() matches using X::x ``` -------------------------------- ### isExpansionInSystemHeader matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the `isExpansionInSystemHeader` matcher. It matches `Y` but not `X` when using `cxxRecordDecl(isExpansionInSystemHeader())`. ```cpp #include class X {}; ``` ```cpp SystemHeader.h: class Y {}; ``` -------------------------------- ### Conflict-declaration example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example of a conflict-declaration. Importing both modules A and B triggers a warning under -Wmodule-conflict. ```plaintext module Conflicts { explicit module A { header "conflict_a.h" conflict B, "we just don't like B" } module B { header "conflict_b.h" } } ``` -------------------------------- ### compile_flags.txt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/JSONCompilationDatabase.html Example of a compile_flags.txt file for simple projects. Each line is one argument; here -I and libwidget/include are separate lines because they are two arguments. Paths are relative to the directory containing the file. ```text -xc++ -I libwidget/include/ ``` -------------------------------- ### isTemplateInstantiation() matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Demonstrates isTemplateInstantiation() matching template instantiations but not explicit specializations, with examples for implicit, explicit, and extern template declarations. ```cpp Matches template instantiations of function, class, or static member variable template instantiations. Given template class X {}; class A {}; X x; or template class X {}; class A {}; template class X; or template class X {}; class A {}; extern template class X; cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) matches the template instantiation of X. But given template class X {}; class A {}; template <> class X {}; X x; cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) does not match, as X is an explicit template specialization. ``` -------------------------------- ### objcImplementationDecl matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Matches Objective-C implementation declarations. The example shows that objcImplementationDecl() matches the implementation. ```objc @implementation Foo @end ``` -------------------------------- ### Run with UBSAN_OPTIONS=print_stacktrace=1 Source: https://releases.llvm.org/13.0.0/tools/clang/docs/UndefinedBehaviorSanitizer.html Run your program with the environment variable `UBSAN_OPTIONS=print_stacktrace=1` to enable symbolized stack traces. Requires `llvm-symbolizer` in `PATH`. ```text UBSAN_OPTIONS=print_stacktrace=1 ``` -------------------------------- ### Run with argument 'with-foo' Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SanitizerCoverage.html Command to run the example with an argument, which triggers the call to foo(). ```bash ASAN_OPTIONS=strip_path_prefix=`pwd`/ ./a.out with-foo ``` -------------------------------- ### cxxBindTemporaryExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cxxBindTemporaryExpr matcher. ```cpp FunctionTakesString(GetStringByValue()); FunctionTakesStringByPointer(GetStringPointer()); ``` -------------------------------- ### Example header A.h with conditional function Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Header file A.h defines function a() only when ENABLE_A is defined. Used in the prebuilt modules examples. ```c /* A.h */ #ifdef ENABLE_A void a() {} #endif ``` -------------------------------- ### cudaKernelCallExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the cudaKernelCallExpr matcher. ```cpp kernel<<>>(); ``` -------------------------------- ### unaryExprOrTypeTraitExpr example input Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example input for the unaryExprOrTypeTraitExpr matcher, showing sizeof and alignof expressions. ```cpp Foo x = bar; int y = sizeof(x) + alignof(x); ``` -------------------------------- ### Output without arguments Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SanitizerCoverage.html Output when running the example without arguments, showing initialization and guard hits in main. ```text INIT: 0x71bcd0 0x71bce0 guard: 0x71bcd4 2 PC 0x4ecd5b in main trace-pc-guard-example.cc:2 guard: 0x71bcd8 3 PC 0x4ecd9e in main trace-pc-guard-example.cc:3:7 ``` -------------------------------- ### MacroBlockBegin and MacroBlockEnd example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Shows how to configure MacroBlockBegin and MacroBlockEnd to treat macros as block delimiters. The example demonstrates the difference with and without the configuration, affecting indentation of code inside macro blocks. ```cpp # With: MacroBlockBegin: "^NS_MAP_BEGIN|\ NS_TABLE_HEAD$" MacroBlockEnd: "^\ NS_MAP_END|\ NS_TABLE_.*_END$" NS_MAP_BEGIN foo(); NS_MAP_END NS_TABLE_HEAD bar(); NS_TABLE_FOO_END # Without: NS_MAP_BEGIN foo(); NS_MAP_END NS_TABLE_HEAD bar(); NS_TABLE_FOO_END ``` -------------------------------- ### isPure example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows a pure virtual method and the matcher matching A::x. ```cpp class A { public: virtual void x() = 0; }; matches A::x ``` -------------------------------- ### Export declaration example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example showing that importing MyLib.Derived also provides the API for MyLib.Base via the export declaration. ```plaintext module MyLib { module Base { header "Base.h" } module Derived { header "Derived.h" export Base } } ``` -------------------------------- ### conditionalOperator example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the conditionalOperator matcher. ```cpp (a ? b : c) + 42 ``` -------------------------------- ### isArray example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows an array new expression and the matcher that matches it. ```cpp MyClass *p1 = new MyClass[10]; cxxNewExpr(isArray()) matches the expression 'new MyClass[10]'. ``` -------------------------------- ### templateName example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example code for templateName matcher, showing the template name 'X' in X. ```cpp template class X { }; X xi; ``` -------------------------------- ### Example profile with inlined calls Source: https://releases.llvm.org/13.0.0/tools/clang/docs/UsersManual.html Example profile for a program with call chain main -> foo -> bar, showing inlined calls and sample counts at each line. ```text main:35504:0 1: _Z3foov:35504 2: _Z32bari:31977 1.1: 31977 2: 0 ``` -------------------------------- ### compoundLiteralExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the compoundLiteralExpr matcher. ```cpp int array[4] = {1}; vector int myvec = (vector int)(1, 2); ``` -------------------------------- ### PowerPC __builtin_dcbf example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LanguageExtensions.html Example of using __builtin_dcbf to flush a data cache block for a variable. ```cpp int a = 1; __builtin_dcbf (&a); ``` -------------------------------- ### coawaitExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the coawaitExpr matcher. ```cpp co_await 1; ``` -------------------------------- ### Prebuild all modules with -fdisable-module-hash Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Generate implicit modules for all required modules in one command using -fdisable-module-hash, then list the resulting .pcm files. ```bash rm -rf prebuilt ; mkdir prebuilt clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fmodules-cache-path=prebuilt -fdisable-module-hash ls prebuilt/*.pcm # prebuilt/A.pcm prebuilt/B.pcm ``` -------------------------------- ### hasBitWidth example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the hasBitWidth matcher. fieldDecl(hasBitWidth(2)) matches 'int a;' and 'int c;' but not 'int b;'. ```cpp class C { int a : 2; int b : 4; int c : 2; }; ``` -------------------------------- ### characterLiteral example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the characterLiteral matcher. ```cpp char ch = 'a'; wchar_t chw = L'a'; ``` -------------------------------- ### Build Clang with CMake and Ninja Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersTutorial.html Configure and build Clang with tests enabled, then run the test suites and install. ```bash cd ~/clang-llvm mkdir build && cd build cmake -G Ninja ../llvm -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra" -DLLVM_BUILD_TESTS=ON # Enable tests; default is off. ninja ninja check # Test LLVM only. ninja clang-test # Test Clang only. ninja install ``` -------------------------------- ### Wildcard export example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example using wildcard export to re-export everything Derived.h includes, providing transitive inclusion behavior. ```plaintext module MyLib { module Base { header "Base.h" } module Derived { header "Derived.h" export * } } ``` -------------------------------- ### Origin tracking example with dfsan_set_label and dfsan_print_origin_trace Source: https://releases.llvm.org/13.0.0/tools/clang/docs/DataFlowSanitizer.html Enables origin tracking with -mllvm -dfsan-track-origins=1. The example sets a label on variable i, computes j = i + 1, then prints the origin trace for j. Compile with clang++ using -fsanitize=dataflow and the origin-tracking flag; the output shows the taint value, origin value, and stack traces for the store and creation sites. ```text % cat test.cc #include #include int main(int argc, char** argv) { int i = 0; dfsan_set_label(i_label, &i, sizeof(i)); int j = i + 1; dfsan_print_origin_trace(&j, "A flow from i to j"); return 0; } ``` ```text % clang++ -fsanitize=dataflow -mllvm -dfsan-track-origins=1 -fno-omit-frame-pointer -g -O2 test.cc % ./a.out Taint value 0x1 (at 0x7ffd42bf415c) origin tracking (A flow from i to j) Origin value: 0x13900001, Taint value was stored to memory at #0 0x55676db85a62 in main test.cc:7:7 #1 0x7f0083611bbc in __libc_start_main libc-start.c:285 Origin value: 0x9e00001, Taint value was created at #0 0x55676db85a08 in main test.cc:6:3 #1 0x7f0083611bbc in __libc_start_main libc-start.c:285 ``` -------------------------------- ### clang-format help output Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormat.html Shows the output of running `clang-format -help`. It lists the tool's usage, options, and behavior when formatting files or standard input. ```text $ clang-format -help OVERVIEW: A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code. If no arguments are specified, it formats the code from standard input and writes the result to the standard output. If s are given, it reformats the files. If -i is specified together with s, the files are edited in-place. Otherwise, the result is written to the standard output. USAGE: clang-format [options] [ ...] OPTIONS: Clang-format options: --Werror - If set, changes formatting warnings to errors --Wno-error= - If set don't error out on the specified warning type. =unknown - If set, unknown format options are only warned about. This can be used to enable formatting, even if the configuration contains unknown (newer) options. Use with caution, as this might lead to dramatically differing format depending on an option being supported or not. --assume-filename= - Override filename used to determine the language. When reading from stdin, clang-format assumes the file name to be used to determine the language. ``` -------------------------------- ### hasAnyCapture with anything example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the hasAnyCapture matcher with any capture. The lambda captures variable x, so lambdaExpr(hasAnyCapture(anything())) matches it. ```cpp void foo() { int x; auto f = [x](){}; } lambdaExpr(hasAnyCapture(anything())) matches [x](){}; ``` -------------------------------- ### Create loop-convert directory and register with CMake Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersTutorial.html Shell commands to create the tool directory and register it in the parent CMakeLists.txt so the build system picks it up. ```shell cd ~/clang-llvm mkdir clang-tools-extra/loop-convert echo 'add_subdirectory(loop-convert)' >> clang-tools-extra/CMakeLists.txt vim clang-tools-extra/loop-convert/CMakeLists.txt ``` -------------------------------- ### isOverride example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows a base class with a virtual method and a derived class overriding it, with the matcher matching B::x. ```cpp class A { public: virtual void x(); }; class B : public A { public: virtual void x(); }; matches B::x ``` -------------------------------- ### isAssignmentOperator examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Two examples for isAssignmentOperator: one matching a += b with binaryOperator and one matching s1 = s2 with cxxOperatorCallExpr. ```cpp if (a == b) a += b; ``` ```cpp struct S { S& operator=(const S&); }; void x() { S s1, s2; s1 = s2; } ``` -------------------------------- ### Generate .clang-format with clang-format -dump-config Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormat.html Creates a .clang-format file in the project directory using the LLVM style as a starting point. Run this command in the project root before customizing the style. ```bash clang-format -style=llvm -dump-config > .clang-format ``` -------------------------------- ### whileStmt example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example while statement that matches whileStmt(). ```cpp while (true) {} ``` -------------------------------- ### Use-declaration example with undeclared use Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example showing that use of A from C is not declared, so it will trigger a warning when -fmodules-decluse is enabled. ```plaintext module A { header "a.h" } module B { header "b.h" } module C { header "c.h" use B } ``` -------------------------------- ### Example program to instrument Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SanitizerCoverage.html A simple program with a conditional call to foo() that will be instrumented with trace-pc-guard. ```cpp // trace-pc-guard-example.cc void foo() { } int main(int argc, char **argv) { if (argc > 1) foo(); } ``` -------------------------------- ### asm attribute: specifying symbol names Source: https://releases.llvm.org/13.0.0/tools/clang/docs/AttributeReference.html Shows how to use the asm attribute to specify the symbol name for variables and functions. On some targets, C symbols are prefixed with an underscore by default, but the asm attribute does not add this prefix, so programmers must compensate. The example demonstrates that var1 and func1 use the specified names 'altvar' and 'altfunc', while var2 and func2 get the default prefixed names. ```c int var1 asm("altvar") = 1; // "altvar" in symbol table. int var2 = 1; // "_var2" in symbol table. void func1(void) asm("altfunc"); void func1(void) {} // "altfunc" in symbol table. void func2(void) {} // "_func2" in symbol table. ``` -------------------------------- ### userDefinedLiteral example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example of a user-defined literal that matches userDefinedLiteral(). ```cpp "foo"_suffix ``` -------------------------------- ### Using -fprebuilt-module-path and -fimplicit-module-maps Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Prebuild modules and compile use.c using -fprebuilt-module-path instead of manual -fmodule-file mappings. Also uses -fimplicit-module-maps instead of -fmodule-map-file. ```bash rm -rf prebuilt; mkdir prebuilt clang -cc1 -emit-module -o prebuilt/A.pcm -fmodules module.modulemap -fmodule-name=A clang -cc1 -emit-module -o prebuilt/B.pcm -fmodules module.modulemap -fmodule-name=B -fprebuilt-module-path=prebuilt clang -cc1 -emit-obj use.c -fmodules -fimplicit-module-maps -fprebuilt-module-path=prebuilt ``` -------------------------------- ### Config-macros example with exhaustive NDEBUG Source: https://releases.llvm.org/13.0.0/tools/clang/docs/Modules.html Example of a config-macros-declaration with the exhaustive attribute, showing a logging library that varies its API based on NDEBUG. ```plaintext module MyLogger { umbrella header "MyLogger.h" config_macros [exhaustive] NDEBUG } ``` -------------------------------- ### castExpr non-matching example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the castExpr matcher (non-matching). ```cpp int i = (0); int k = 0; ``` -------------------------------- ### Example profile remapping file Source: https://releases.llvm.org/13.0.0/tools/clang/docs/UsersManual.html Example remapping file that treats absl::string_view as equivalent to std::string_view and maps std to its libc++ or libstdc++ variants. Use with -fprofile-remapping-file=. ```text # absl::string_view is considered equivalent to std::string_view type N4absl11string_viewE St17basic_string_viewIcSt11char_traitsIcEE # std:: might be std::__1:: in libc++ or std::__cxx11:: in libstdc++ name 3std St3__1 name 3std St7__cxx11 ``` -------------------------------- ### Input for member initializer prefix Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example input with a constructor initializer for member i. ```cpp struct Simple {}; struct Record { Record() : i(42) {} private: int i; Simple s; }; ``` -------------------------------- ### Creating coverage reports Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SourceBasedCodeCoverage.html Use llvm-profdata to merge the raw profile and llvm-cov to generate a report. The `report` subcommand prints a summary, and `show` produces a line-by-line annotated source listing. ```text $ llvm-profdata merge -sparse mycode.profraw -o mycode.profdata ``` ```text $ llvm-cov report ./mycode -instr-profile=mycode.profdata ``` ```text $ llvm-cov show ./mycode -instr-profile=mycode.profdata ``` -------------------------------- ### Optimization record output file examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/UsersManual.html Shows the output file naming schemes for -fsave-optimization-record. The first two examples illustrate the default scheme for -c and -S, while the third shows the Darwin-only behavior for linked binaries with bitstream format. ```text clang -fsave-optimization-record -c in.c -o out.o ``` ```text clang -fsave-optimization-record -c in.c ``` ```text clang -fsave-optimization-record=bitstream in.c -o out ``` -------------------------------- ### hasAnyArgument callExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasAnyArgument matcher on call expressions. ```cpp void x(int, int, int) { int y; x(1, y, 42); } callExpr(hasAnyArgument(declRefExpr())) matches x(1, y, 42) with hasAnyArgument(...) matching y ``` -------------------------------- ### Label propagation example with dfsan_set_label and dfsan_get_label Source: https://releases.llvm.org/13.0.0/tools/clang/docs/DataFlowSanitizer.html Shows how to assign labels to variables and verify propagation. The program sets distinct labels on three integers, computes a label for the sum of two, and asserts the resulting union label contains the expected base labels. It also demonstrates the equivalent dfsan_has_label check. ```c #include #include int main(void) { int i = 100; int j = 200; int k = 300; dfsan_label i_label = 1; dfsan_label j_label = 2; dfsan_label k_label = 4; dfsan_set_label(i_label, &i, sizeof(i)); dfsan_set_label(j_label, &j, sizeof(j)); dfsan_set_label(k_label, &k, sizeof(k)); dfsan_label ij_label = dfsan_get_label(i + j); assert(ij_label & i_label); // ij_label has i_label assert(ij_label & j_label); // ij_label has j_label assert(!(ij_label & k_label)); // ij_label doesn't have k_label assert(ij_label == 3); // Verifies all of the above // Or, equivalently: assert(dfsan_has_label(ij_label, i_label)); assert(dfsan_has_label(ij_label, j_label)); assert(!dfsan_has_label(ij_label, k_label)); return 0; } ``` -------------------------------- ### hasTypeLoc declaratorDecl example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasTypeLoc matcher matching a declarator declaration. ```cpp int x; declaratorDecl(hasTypeLoc(loc(asString("int")))) ``` -------------------------------- ### BreakBeforeBraces Allman example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html Example for the BreakBeforeBraces style option with configuration value Allman. Braces are always placed on a new line. ```cpp namespace N { enum E { E1, E2, }; class C { public: C(); }; bool baz(int i) { try { do { switch (i) { case 1: { foobar(); break; } default: { break; } } } while (--i); return true; } catch (...) { handleError(); return false; } } void foo(bool b) { if (b) { baz(2); } else { baz(5); } } void bar() { foo(true); } } // namespace N ``` -------------------------------- ### forEachArgumentWithParam matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows how to use forEachArgumentWithParam to match all arguments and their corresponding ParmVarDecl. The example matches the call f(y) and identifies the argument y and parameter i. ```cpp void f(int i); int y; f(y); callExpr( forEachArgumentWithParam( declRefExpr(to(varDecl(hasName("y")))), parmVarDecl(hasType(isInteger())) )) matches f(y); with declRefExpr(...) matching int y and parmVarDecl(...) matching int i ``` -------------------------------- ### Example: ignorelist file and clang invocation Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SanitizerSpecialCaseList.html Shows a complete workflow: create foo.c with a memory error, create ignorelist.txt that ignores reports from bad_foo, then compile with -fsanitize=address and run. The ignorelist suppresses reports from the bad_foo function. ```bash $ cat foo.c #include void bad_foo() { int *a = (int*)malloc(40); a[10] = 1; } int main() { bad_foo(); } $ cat ignorelist.txt # Ignore reports from bad_foo function. fun:bad_foo $ clang -fsanitize=address foo.c ; ./a.out ``` -------------------------------- ### hasUnqualifiedDesugaredType example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for matching the underlying desugared type using hasUnqualifiedDesugaredType. ```cpp varDecl(hasType(hasUnqualifiedDesugaredType( recordType(hasDeclaration(decl()))))) ``` -------------------------------- ### hasAnyArgument objcMessageExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasAnyArgument matcher on Objective-C message expressions. ```objc @interface I - (void) f:(int) y; @end void foo(I *i) { [i f:12]; } objcMessageExpr(hasAnyArgument(integerLiteral(equals(12)))) matches [i f:12] ``` -------------------------------- ### isVirtualAsWritten example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows a virtual method and an override without the virtual keyword, with the matcher matching only A::x. ```cpp class A { public: virtual void x(); }; class B : public A { public: void x(); }; matches A::x but not B::x ``` -------------------------------- ### clang_analyzer_explain usage example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/analyzer/developer-docs/DebugChecks.html Shows how to declare and use clang_analyzer_explain with overrides for different types, including a suffix variant for C code. The expected warnings appear as comments in the source. ```cpp void clang_analyzer_explain(int); void clang_analyzer_explain(void *); // Useful in C code void clang_analyzer_explain_int(int); void foo(int param, void *ptr) { clang_analyzer_explain(param); // expected-warning{{argument 'param'}} clang_analyzer_explain_int(param); // expected-warning{{argument 'param'}} if (!ptr) clang_analyzer_explain(ptr); // expected-warning{{memory address '0'}} } ``` -------------------------------- ### isTypeDependent example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the isTypeDependent matcher. The expressions 'x' and 'x + y' are type-dependent, but 'y' is not. ```cpp template void add(T x, int y) { x + y; } ``` -------------------------------- ### decltypeType example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example code for decltypeType matcher, showing a decltype expression. ```cpp short i = 1; int j = 42; decltype(i + j) result = i + j; ``` -------------------------------- ### autoType example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example code for autoType matcher, showing auto variables. ```cpp auto n = 4; int v[] = { 2, 3 } for (auto i : v) { } ``` -------------------------------- ### Example: Compile and run a tiny race program with ThreadSanitizer Source: https://releases.llvm.org/13.0.0/tools/clang/docs/ThreadSanitizer.html Shows a C program with a data race and the commands to compile and run it with ThreadSanitizer. The program creates a thread that writes to a global variable while the main thread also writes to it. Compile with -fsanitize=thread -g -O1. The output shows the data race report. ```c #include int Global; void *Thread1(void *x) { Global = 42; return x; } int main() { pthread_t t; pthread_create(&t, NULL, Thread1, NULL); Global = 43; pthread_join(t, NULL); return Global; } ``` ```bash $ clang -fsanitize=thread -g -O1 tiny_race.c ``` ```bash % ./a.out WARNING: ThreadSanitizer: data race (pid=19219) Write of size 4 at 0x7fcf47b21bc0 by thread T1: #0 Thread1 tiny_race.c:4 (exe+0x00000000a360) Previous write of size 4 at 0x7fcf47b21bc0 by main thread: #0 main tiny_race.c:10 (exe+0x00000000a3b4) Thread T1 (running) created at: #0 pthread_create tsan_interceptors.cc:705 (exe+0x00000000c790) #1 main tiny_race.c:9 (exe+0x00000000a3a4) ``` -------------------------------- ### hasTypeLoc cxxFunctionalCastExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasTypeLoc matcher matching a functional cast expression. ```cpp struct Foo { Foo(int, int); }; auto x = Foo(1, 2); cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo")))) ``` -------------------------------- ### hasName matcher examples Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Shows hasName matching. First example matches X with Name == "X". Second example matches X with Name one of "::a::b::X", "a::b::X", "b::X", "X". ```cpp class X; ``` ```cpp namespace a { namespace b { class X; } } ``` -------------------------------- ### Running the instrumented program Source: https://releases.llvm.org/13.0.0/tools/clang/docs/SourceBasedCodeCoverage.html Run the program with the `LLVM_PROFILE_FILE` environment variable set to specify where to write the raw profile data. The default is `default.profraw` in the current directory. ```text $ LLVM_PROFILE_FILE=mycode.profraw ./mycode ``` -------------------------------- ### hasTypeLoc cxxTemporaryObjectExpr example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasTypeLoc matcher matching a temporary object expression. ```cpp auto x = int(3); cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int")))) ``` -------------------------------- ### Enable OpenCL extensions with -cl-ext Source: https://releases.llvm.org/13.0.0/tools/clang/docs/OpenCLSupport.html Command-line option to enable all OpenCL extensions for a compilation unit. ```bash -cl-ext=-all ``` -------------------------------- ### hasArgument example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for hasArgument matcher matching the n'th argument of a call expression. ```cpp void x(int) { int y; x(y); } callExpr(hasArgument(0, declRefExpr())) ``` -------------------------------- ### booleanType matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the `booleanType` matcher. The matcher matches `bool func();`. ```cpp struct S { bool func(); }; ``` ```cpp functionDecl(returns(booleanType())) ``` -------------------------------- ### templateArgumentCountIs matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the `templateArgumentCountIs` matcher. The matcher matches `C`. ```cpp template struct C {}; C c; ``` ```cpp classTemplateSpecializationDecl(templateArgumentCountIs(1)) ``` -------------------------------- ### isEnum matcher example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the `isEnum` matcher. It matches `E` but not `C`, `S`, or `U`. ```cpp struct S {}; class C {}; union U {}; enum E {}; ``` -------------------------------- ### isScoped example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example for the isScoped matcher. enumDecl(isScoped()) matches only the scoped enum 'Y'. ```cpp enum X {}; enum class Y {}; ``` -------------------------------- ### dependentSizedArrayType example Source: https://releases.llvm.org/13.0.0/tools/clang/docs/LibASTMatchersReference.html Example code for dependentSizedArrayType matcher, showing an array with a dependent size. ```cpp template class array { T data[Size]; }; ```