diff options
Diffstat (limited to 'docs')
-rw-r--r-- | docs/AddressSanitizer.html | 57 | ||||
-rw-r--r-- | docs/AutomaticReferenceCounting.html | 4 | ||||
-rw-r--r-- | docs/ClangPlugins.html | 170 | ||||
-rw-r--r-- | docs/ClangTools.html | 118 | ||||
-rw-r--r-- | docs/HowToSetupToolingForLLVM.html | 186 | ||||
-rw-r--r-- | docs/InternalsManual.html | 32 | ||||
-rw-r--r-- | docs/IntroductionToTheClangAST.html | 139 | ||||
-rw-r--r-- | docs/JSONCompilationDatabase.html | 89 | ||||
-rw-r--r-- | docs/LanguageExtensions.html | 120 | ||||
-rw-r--r-- | docs/LibTooling.html | 229 | ||||
-rw-r--r-- | docs/ObjectiveCLiterals.html | 199 | ||||
-rw-r--r-- | docs/RAVFrontendAction.html | 224 | ||||
-rw-r--r-- | docs/ReleaseNotes.html | 273 | ||||
-rw-r--r-- | docs/ThreadSanitizer.html | 125 | ||||
-rw-r--r-- | docs/Tooling.html | 120 | ||||
-rw-r--r-- | docs/UsersManual.html | 202 | ||||
-rw-r--r-- | docs/tools/clang.pod | 8 |
17 files changed, 2082 insertions, 213 deletions
diff --git a/docs/AddressSanitizer.html b/docs/AddressSanitizer.html index c1dc91b..98ea934 100644 --- a/docs/AddressSanitizer.html +++ b/docs/AddressSanitizer.html @@ -21,14 +21,16 @@ <h1>AddressSanitizer</h1> <ul> - <li> <a href="intro">Introduction</a> - <li> <a href="howtobuild">How to Build</a> - <li> <a href="usage">Usage</a> - <ul><li> <a href="has_feature">__has_feature(address_sanitizer)</a></ul> - <li> <a href="platforms">Supported Platforms</a> - <li> <a href="limitations">Limitations</a> - <li> <a href="status">Current Status</a> - <li> <a href="moreinfo">More Information</a> + <li> <a href="#intro">Introduction</a> + <li> <a href="#howtobuild">How to Build</a> + <li> <a href="#usage">Usage</a> + <ul><li> <a href="#has_feature">__has_feature(address_sanitizer)</a></ul> + <ul><li> <a href="#no_address_safety_analysis"> + __attribute__((no_address_safety_analysis))</a></ul> + <li> <a href="#platforms">Supported Platforms</a> + <li> <a href="#limitations">Limitations</a> + <li> <a href="#status">Current Status</a> + <li> <a href="#moreinfo">More Information</a> </ul> <h2 id="intro">Introduction</h2> @@ -97,36 +99,47 @@ AddressSanitizer is enabled. <a href="LanguageExtensions.html#__has_feature_extension">__has_feature</a> can be used for this purpose. <pre> -#if defined(__has_feature) && __has_feature(address_sanitizer) - code that runs only under AddressSanitizer -#else - code that does not run under AddressSanitizer +#if defined(__has_feature) +# if __has_feature(address_sanitizer) + code that builds only under AddressSanitizer +# endif #endif </pre> +<h3 id="no_address_safety_analysis">__attribute__((no_address_safety_analysis))</h3> +Some code should not be instrumentated by AddressSanitizer. +One may use the function attribute +<a href="LanguageExtensions.html#address_sanitizer"> + <tt>no_address_safety_analysis</tt></a> +to disable instrumentation of a particular function. +This attribute may not be supported by other compilers, so we suggest to +use it together with <tt>__has_feature(address_sanitizer)</tt>. +Note: currently, this attribute will be lost if the function is inlined. + <h2 id="platforms">Supported Platforms</h2> AddressSanitizer is supported on <ul><li>Linux x86_64 (tested on Ubuntu 10.04). -<li>MacOS 10.6 i386/x86_64. +<li>MacOS 10.6 and 10.7 (i386/x86_64). </ul> -Support for Linux i386/ARM and MacOS 10.7 is in progress +Support for Linux i386/ARM is in progress (it may work, but is not guaranteed too). <h2 id="limitations">Limitations</h2> <ul> - <li> AddressSanitizer uses more real memory than a native run. - How much -- depends on the allocations sizes. The smaller the - allocations you make the bigger the overhead. - <li> On 64-bit platforms AddressSanitizer maps (but not reserves) - 16+ Terabytes of virtual address space. - This means that tools like <tt>ulimit</tt> may not work as usually expected. - <li> Static linking is not supported. +<li> AddressSanitizer uses more real memory than a native run. +How much -- depends on the allocations sizes. The smaller the +allocations you make the bigger the overhead. +<li> AddressSanitizer uses more stack memory. We have seen up to 3x increase. +<li> On 64-bit platforms AddressSanitizer maps (but not reserves) +16+ Terabytes of virtual address space. +This means that tools like <tt>ulimit</tt> may not work as usually expected. +<li> Static linking is not supported. </ul> <h2 id="status">Current Status</h2> -AddressSanitizer is fully functional on supported platforms in LLVM head. +AddressSanitizer is fully functional on supported platforms starting from LLVM 3.1. However, the test suite is not fully integrated yet and we lack the testing process (buildbots). diff --git a/docs/AutomaticReferenceCounting.html b/docs/AutomaticReferenceCounting.html index 1416df5..3f1ccaf 100644 --- a/docs/AutomaticReferenceCounting.html +++ b/docs/AutomaticReferenceCounting.html @@ -313,7 +313,7 @@ interoperation:</p> <ul> <li>The type system must reliably identify which objects are to be managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed -array, or it might be a interior pointer to such an array, or it might +array, or it might be an interior pointer to such an array, or it might point to some field or local variable. In contrast, values of the retainable object pointer types are never interior.</li> <li>The type system must reliably indicate how to @@ -1863,7 +1863,7 @@ of these annotations. A program is ill-formed if it annotates the same function with both <tt>cf_audited_transfer</tt> and <tt>cf_unknown_transfer</tt>.</p> -<p>A pragma is provided to faciliate the mass annotation of interfaces:</p> +<p>A pragma is provided to facilitate the mass annotation of interfaces:</p> <pre>#pragma arc_cf_code_audited begin ... diff --git a/docs/ClangPlugins.html b/docs/ClangPlugins.html new file mode 100644 index 0000000..ed560fe --- /dev/null +++ b/docs/ClangPlugins.html @@ -0,0 +1,170 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>Clang Plugins</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>Clang Plugins</h1> +<p>Clang Plugins make it possible to run extra user defined actions during +a compilation. This document will provide a basic walkthrough of how to write +and run a Clang Plugin.</p> + +<!-- ======================================================================= --> +<h2 id="intro">Introduction</h2> +<!-- ======================================================================= --> + +<p>Clang Plugins run FrontendActions over code. See the +<a href="RAVFrontendAction.html">FrontendAction tutorial</a> on how to write a +FrontendAction using the RecursiveASTVisitor. In this tutorial, we'll +demonstrate how to write a simple clang plugin. +</p> + +<!-- ======================================================================= --> +<h2 id="pluginactions">Writing a PluginASTAction</h2> +<!-- ======================================================================= --> + +<p>The main difference from writing normal FrontendActions is that you can +handle plugin command line options. The +PluginASTAction base class declares a ParseArgs method which you have to +implement in your plugin. +</p> +<pre> + bool ParseArgs(const CompilerInstance &CI, + const std::vector<std::string>& args) { + for (unsigned i = 0, e = args.size(); i != e; ++i) { + if (args[i] == "-some-arg") { + // Handle the command line argument. + } + } + return true; + } +</pre> + +<!-- ======================================================================= --> +<h2 id="registerplugin">Registering a plugin</h2> +<!-- ======================================================================= --> + +<p>A plugin is loaded from a dynamic library at runtime by the compiler. To register +a plugin in a library, use FrontendPluginRegistry::Add:</p> +<pre> + static FrontendPluginRegistry::Add<MyPlugin> X("my-plugin-name", "my plugin description"); +</pre> + +<!-- ======================================================================= --> +<h2 id="example">Putting it all together</h2> +<!-- ======================================================================= --> + +<p>Let's look at an example plugin that prints top-level function names. +This example is also checked into the clang repository; please also take a look +at the latest <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/examples/PrintFunctionNames/PrintFunctionNames.cpp?view=markup">checked in version of PrintFunctionNames.cpp</a>.</p> +<pre> +#include "clang/Frontend/FrontendPluginRegistry.h" +#include "clang/AST/ASTConsumer.h" +#include "clang/AST/AST.h" +#include "clang/Frontend/CompilerInstance.h" +#include "llvm/Support/raw_ostream.h" +using namespace clang; + +namespace { + +class PrintFunctionsConsumer : public ASTConsumer { +public: + virtual bool HandleTopLevelDecl(DeclGroupRef DG) { + for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) { + const Decl *D = *i; + if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) + llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n"; + } + + return true; + } +}; + +class PrintFunctionNamesAction : public PluginASTAction { +protected: + ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) { + return new PrintFunctionsConsumer(); + } + + bool ParseArgs(const CompilerInstance &CI, + const std::vector<std::string>& args) { + for (unsigned i = 0, e = args.size(); i != e; ++i) { + llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n"; + + // Example error handling. + if (args[i] == "-an-error") { + DiagnosticsEngine &D = CI.getDiagnostics(); + unsigned DiagID = D.getCustomDiagID( + DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'"); + D.Report(DiagID); + return false; + } + } + if (args.size() && args[0] == "help") + PrintHelp(llvm::errs()); + + return true; + } + void PrintHelp(llvm::raw_ostream& ros) { + ros << "Help for PrintFunctionNames plugin goes here\n"; + } + +}; + +} + +static FrontendPluginRegistry::Add<PrintFunctionNamesAction> +X("print-fns", "print function names"); +</pre> + +<!-- ======================================================================= --> +<h2 id="running">Running the plugin</h2> +<!-- ======================================================================= --> + +<p>To run a plugin, the dynamic library containing the plugin registry must be +loaded via the -load command line option. This will load all plugins that are +registered, and you can select the plugins to run by specifying the -plugin +option. Additional parameters for the plugins can be passed with -plugin-arg-<plugin-name>.</p> + +<p>Note that those options must reach clang's cc1 process. There are two +ways to do so:</p> +<ul> +<li> +Directly call the parsing process by using the -cc1 option; this has the +downside of not configuring the default header search paths, so you'll need to +specify the full system path configuration on the command line. +</li> +<li> +Use clang as usual, but prefix all arguments to the cc1 process with -Xclang. +</li> +</ul> +<p>For example, to run the print-function-names plugin over a source file in clang, +first build the plugin, and then call clang with the plugin from the source tree:</p> +<pre> + $ export BD=/path/to/build/directory + $ (cd $BD && make PrintFunctionNames ) + $ clang++ -D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS \ + -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D_GNU_SOURCE \ + -I$BD/tools/clang/include -Itools/clang/include -I$BD/include -Iinclude \ + tools/clang/tools/clang-check/ClangCheck.cpp -fsyntax-only \ + -Xclang -load -Xclang $BD/lib/PrintFunctionNames.so -Xclang \ + -plugin -Xclang print-fns +</pre> + +<p>Also see the print-function-name plugin example's +<a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/examples/PrintFunctionNames/README.txt?view=markup">README</a></p> + + + +</div> +</body> +</html> + diff --git a/docs/ClangTools.html b/docs/ClangTools.html new file mode 100644 index 0000000..0dfdc6a --- /dev/null +++ b/docs/ClangTools.html @@ -0,0 +1,118 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>Clang Tools</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>Clang Tools</h1> +<p>Clang Tools are standalone command line (and potentially GUI) tools design +for use by C++ developers who are already using and enjoying Clang as their +compiler. These tools provide developer-oriented functionality such as fast +syntax checking, automatic formatting, refactoring, etc.</p> + +<p>Only a couple of the most basic and fundamental tools are kept in the primary +Clang Subversion project. The rest of the tools are kept in a side-project so +that developers who don't want or need to build them don't. If you want to get +access to the extra Clang Tools repository, simply check it out into the tools +tree of your Clang checkout and follow the usual process for building and +working with a combined LLVM/Clang checkout:</p> +<ul> + <li>With Subversion: + <ul> + <li><tt>cd llvm/tools/clang/tools</tt></li> + <li><tt>svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk + extra</tt></li> + </ul> + </li> + <li>Or with Git: + <ul> + <li><tt>cd llvm/tools/clang/tools</tt></li> + <li><tt>git clone http://llvm.org/git/clang-tools-extra.git extra</tt></li> + </ul> + </li> +</ul> + +<p>This document describes a high-level overview of the organization of Clang +Tools within the project as well as giving an introduction to some of the more +important tools. However, it should be noted that this document is currently +focused on Clang and Clang Tool developers, not on end users of these tools.</p> + +<!-- ======================================================================= --> +<h2 id="org">Clang Tools Organization</h2> +<!-- ======================================================================= --> + +<p>Clang Tools are CLI or GUI programs that are intended to be directly used by +C++ developers. That is they are <em>not</em> primarily for use by Clang +developers, although they are hopefully useful to C++ developers who happen to +work on Clang, and we try to actively dogfood their functionality. They are +developed in three components: the underlying infrastructure for building +a standalone tool based on Clang, core shared logic used by many different tools +in the form of refactoring and rewriting libraries, and the tools +themselves.</p> + +<p>The underlying infrastructure for Clang Tools is the +<a href="LibTooling.html">LibTooling</a> platform. See its documentation for +much more detailed information about how this infrastructure works. The common +refactoring and rewriting toolkit-style library is also part of LibTooling +organizationally.</p> + +<p>A few Clang Tools are developed along side the core Clang libraries as +examples and test cases of fundamental functionality. However, most of the tools +are developed in a side repository to provide easy separation from the core +libraries. We intentionally do not support public libraries in the side +repository, as we want to carefully review and find good APIs for libraries as +they are lifted out of a few tools and into the core Clang library set.</p> + +<p>Regardless of which repository Clang Tools' code resides in, the development +process and practices for all Clang Tools are exactly those of Clang itself. +They are entirely within the Clang <em>project</em>, regardless of the version +control scheme.</p> + + +<!-- ======================================================================= --> +<h2 id="coretools">Core Clang Tools</h2> +<!-- ======================================================================= --> + +<p>The core set of Clang tools that are within the main repository are tools +that very specifically compliment, and allow use and testing of <em>Clang</em> +specific functionality.</p> + +<h3 id="clang-check"><tt>clang-check</tt></h3> +<p>This tool combines the LibTooling framework for running a Clang tool with the +basic Clang diagnostics by syntax checking specific files in a fast, command line +interface. It can also accept flags to re-display the diagnostics in different +formats with different flags, suitable for use driving an IDE or editor.</p> + +<p>FIXME: Link to user-oriented clang-check documentation.</p> + +<h3 id="clang-fixit"><tt>clang-fixit</tt> (Not yet implemented!)</h3> +<p>A tool which specifically applies the Clang fix-it hint diagnostic technology +on top of a dedicated tool. It is designed to explore alternative interfaces for +applying fix-it hints, including automatic application, prompting users with +options for different fixes, etc.</p> + +<p><b>NB:</b> The clang-fixit tool is planned, but not yet implemented.</p> + +<p>FIXME: Link to user-oriented clang-fixit documentation.</p> + +<!-- ======================================================================= --> +<h2 id="registerplugin">Extra Clang Tools</h2> +<!-- ======================================================================= --> + +<p>As various categories of Clang Tools are added to the extra repository, +they'll be tracked here. The focus of this documentation is on the scope and +features of the tools for other tool developers; each tool should provide its +own user-focused documentation.</p> + +</div> +</body> +</html> + diff --git a/docs/HowToSetupToolingForLLVM.html b/docs/HowToSetupToolingForLLVM.html new file mode 100644 index 0000000..493c882 --- /dev/null +++ b/docs/HowToSetupToolingForLLVM.html @@ -0,0 +1,186 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>How To Setup Clang Tooling For LLVM</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>How To Setup Clang Tooling For LLVM</h1> +<p>Clang Tooling provides infrastructure to write tools that need syntactic and +semantic infomation about a program. This term also relates to a set of specific +tools using this infrastructure (e.g. <code>clang-check</code>). This document +provides information on how to set up and use Clang Tooling for the LLVM source +code.</p> + + +<!-- ======================================================================= --> +<h2><a name="introduction">Introduction</a></h2> +<!-- ======================================================================= --> + +<p>Clang Tooling needs a compilation database to figure out specific build +options for each file. Currently it can create a compilation database from the +<code>compilation_commands.json</code> file, generated by CMake. When invoking +clang tools, you can either specify a path to a build directory using a command +line parameter <code>-p</code> or let Clang Tooling find this file in your +source tree. In either case you need to configure your build using CMake to use +clang tools.</p> + +<!-- ======================================================================= --> +<h2><a name="using-make">Setup Clang Tooling Using CMake and Make</a></h2> +<!-- ======================================================================= --> + +<p>If you intend to use make to build LLVM, you should have CMake 2.8.6 or later +installed (can be found <a href="http://cmake.org">here</a>).</p> +<p>First, you need to generate Makefiles for LLVM with CMake. You need to make +a build directory and run CMake from it:</p> +<pre> + mkdir your/build/directory + cd your/build/directory + cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources +</pre> + +<p>If you want to use clang instead of GCC, you can add +<code>-DCMAKE_C_COMPILER=/path/to/clang + -DCMAKE_CXX_COMPILER=/path/to/clang++</code>. +You can also use ccmake, which provides a curses interface to configure CMake +variables for lazy people.</p> + +<p>As a result, the new <code>compile_commands.json</code> file should appear in +the current directory. You should link it to the LLVM source tree so that Clang +Tooling is able to use it:</p> +<pre> + ln -s $PWD/compile_commands.json path/to/llvm/source/ +</pre> + +<p>Now you are ready to build and test LLVM using make:</p> +<pre> + make check-all +</pre> + +<!-- ======================================================================= --> +<h2><a name="using-tools">Using Clang Tools</a></h2> +<!-- ======================================================================= --> + +<p>After you completed the previous steps, you are ready to run clang tools. If +you have a recent clang installed, you should have <code>clang-check</code> in +$PATH. Try to run it on any .cpp file inside the LLVM source tree:</p> +<pre> + clang-check tools/clang/lib/Tooling/CompilationDatabase.cpp +</pre> +<p>If you're using vim, it's convenient to have clang-check integrated. Put this +into your .vimrc:</p> +<pre> + set makeprg=clang-check\ % + map <F5> :make<CR><CR> +</pre> + +<p>When editing C++ code, hit F5 to reparse the current buffer. The output will +go into the error window, which you can enable with <code>:cope</code>.</p> + +<p>Other <code>clang-check</code> options that can be useful when working with +clang AST:</p> +<ul> + <li><code>-ast-print</code> - Build ASTs and then pretty-print them.</li> + <li><code>-ast-dump</code> - Build ASTs and then debug dump them.</li> + <li><code>-ast-dump-filter=<string></code> - Use with + <code>-ast-dump</code> or <code>-ast-print</code> to dump/print + only AST declaration nodes having a certain substring in a qualified name. + Use <code>-ast-list</code> to list all filterable declaration node + names.</li> + <li><code>-ast-list</code> - Build ASTs and print the list of declaration + node qualified names.</li> +</ul> +<p>Examples:</p> +<pre> +<b>$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-dump -ast-dump-filter ActionFactory::newASTConsumer</b> +Processing: tools/clang/tools/clang-check/ClangCheck.cpp. +Dumping <anonymous namespace>::ActionFactory::newASTConsumer: +clang::ASTConsumer *newASTConsumer() (CompoundStmt 0x44da290 </home/alexfh/local/llvm/tools/clang/tools/clang-check/ClangCheck.cpp:64:40, line:72:3> + (IfStmt 0x44d97c8 <line:65:5, line:66:45> + <<<NULL>>> + (ImplicitCastExpr 0x44d96d0 <line:65:9> '_Bool':'_Bool' <UserDefinedConversion> +... +<b>$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-print -ast-dump-filter ActionFactory::newASTConsumer</b> +Processing: tools/clang/tools/clang-check/ClangCheck.cpp. +Printing <anonymous namespace>::ActionFactory::newASTConsumer: +clang::ASTConsumer *newASTConsumer() { + if (this->ASTList.operator _Bool()) + return clang::CreateASTDeclNodeLister(); + if (this->ASTDump.operator _Bool()) + return clang::CreateASTDumper(this->ASTDumpFilter); + if (this->ASTPrint.operator _Bool()) + return clang::CreateASTPrinter(&llvm::outs(), this->ASTDumpFilter); + return new clang::ASTConsumer(); +} +</pre> + +<!-- ======================================================================= --> +<h2><a name="using-ninja">(Experimental) Using Ninja Build System</a></h2> +<!-- ======================================================================= --> + +<p>Optionally you can use the <a + href="https://github.com/martine/ninja">Ninja</a> build system instead of +make. It is aimed at making your builds faster. Currently this step will require +building Ninja from sources and using a development version of CMake.</p> +<p>To take advantage of using Clang Tools along with Ninja build you need at +least CMake 2.8.9. At the moment CMake 2.8.9 is still under development, so you +can get latest development sources and build it yourself:</p> +<pre> + git clone git://cmake.org/cmake.git + cd cmake + ./bootstrap + make + sudo make install +</pre> + +<p>Having the correct version of CMake, you can clone the Ninja git repository +and build Ninja from sources:</p> +<pre> + git clone git://github.com/martine/ninja.git + cd ninja/ + ./bootstrap.py +</pre> +<p>This will result in a single binary <code>ninja</code> in the current +directory. It doesn't require installation and can just be copied to any +location inside <code>$PATH</code>, say <code>/usr/local/bin/</code>:</p> +<pre> + sudo cp ninja /usr/local/bin/ + sudo chmod a+rx /usr/local/bin/ninja +</pre> +<p>After doing all of this, you'll need to generate Ninja build files for LLVM +with CMake. You need to make a build directory and run CMake from it:</p> +<pre> + mkdir your/build/directory + cd your/build/directory + cmake -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources +</pre> + +<p>If you want to use clang instead of GCC, you can add +<code>-DCMAKE_C_COMPILER=/path/to/clang + -DCMAKE_CXX_COMPILER=/path/to/clang++</code>. +You can also use ccmake, which provides a curses interface to configure CMake +variables in an interactive manner.</p> + +<p>As a result, the new <code>compile_commands.json</code> file should appear in +the current directory. You should link it to the LLVM source tree so that Clang +Tooling is able to use it:</p> +<pre> + ln -s $PWD/compile_commands.json path/to/llvm/source/ +</pre> + +<p>Now you are ready to build and test LLVM using Ninja:</p> +<pre> + ninja check-all +</pre> +<p>Other target names can be used in the same way as with make.</p> +</div> +</body> +</html> + diff --git a/docs/InternalsManual.html b/docs/InternalsManual.html index bd6af8d..3f3e124 100644 --- a/docs/InternalsManual.html +++ b/docs/InternalsManual.html @@ -357,6 +357,12 @@ Clang:</p> <tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr> <tr><td>Class:</td><td>NamedDecl*</td></tr> <tr><td>Description</td><td><p>This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".</p></td></tr> + +<tr><td colspan="2"><b>"diff" format</b></td></tr> +<tr><td>Example:</td><td><tt>"no known conversion %diff{from | to | }1,2"</tt></td></tr> +<tr><td>Class:</td><td>QualType</td></tr> +<tr><td>Description</td><td><p>This formatter takes two QualTypes and attempts to print a template difference between the two. If tree printing is off, the text inside the braces before the pipe is printed, with the formatted text replacing the $. If tree printing is on, the text after the pipe is printed and a type tree is printed after the diagnostic message. +</p></td></tr> </table> @@ -441,6 +447,18 @@ href="#DiagnosticClient">Other diagnostic clients</a> might choose to render the code differently (e.g., as markup inline) or even give the user the ability to automatically fix the problem.</p> +<p>Fix-it hints on errors and warnings need to obey these rules:</p> + +<ul> +<li>Since they are automatically applied if <code>-Xclang -fixit</code> +is passed to the driver, they should only be used when it's very likely they +match the user's intent.</li> +<li>Clang must recover from errors as if the fix-it had been applied.</li> +</ul> + +<p>If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on +notes are not applied automatically.</p> + <p>All fix-it hints are described by the <code>FixItHint</code> class, instances of which should be attached to the diagnostic using the << operator in the same way that highlighted source ranges and @@ -1686,7 +1704,7 @@ interacts with constant evaluation:</p> <li><b><tt>__extension__</tt></b>: The expression form of this extension causes any evaluatable subexpression to be accepted as an integer constant expression.</li> -<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer +<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as an integer constant expression) if the operand evaluates to either a numeric value (that is, not a pointer cast to integral type) of integral, enumeration, floating or complex type, or if it evaluates to the address of the first @@ -1751,18 +1769,6 @@ then <tt>__attribute__((myattribute("Hello", 3)))</tt> will be a valid use.</p> <h4>Boilerplate</h4> -<p>Add an element to the <tt>AttributeList::Kind</tt> enum in <a -href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/AttributeList.h?view=markup">include/clang/Sema/AttributeList.h</a> -named <tt>AT_lower_with_underscores</tt>. That is, a CamelCased -<tt>AttributeName</tt> in <tt>Attr.td</tt> name should become -<tt>AT_attribute_name</tt>.</p> - -<p>Add a case to the <tt>StringSwitch</tt> in <tt>AttributeList::getKind()</tt> -in <a -href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AttributeList.cpp?view=markup">lib/Sema/AttributeList.cpp</a> -for each spelling of your attribute. Less common attributes should come toward -the end of that list.</p> - <p>Write a new <tt>HandleYourAttr()</tt> function in <a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?view=markup">lib/Sema/SemaDeclAttr.cpp</a>, and add a case to the switch in <tt>ProcessNonInheritableDeclAttr()</tt> or diff --git a/docs/IntroductionToTheClangAST.html b/docs/IntroductionToTheClangAST.html new file mode 100644 index 0000000..28175dd --- /dev/null +++ b/docs/IntroductionToTheClangAST.html @@ -0,0 +1,139 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>Introduction to the Clang AST</title> +<link type="text/css" rel="stylesheet" href="../menu.css" /> +<link type="text/css" rel="stylesheet" href="../content.css" /> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>Introduction to the Clang AST</h1> +<p>This document gives a gentle introduction to the mysteries of the Clang AST. +It is targeted at developers who either want to contribute to Clang, or use +tools that work based on Clang's AST, like the AST matchers.</p> +<!-- FIXME: Add link once we have an AST matcher document --> + +<!-- ======================================================================= --> +<h2 id="intro">Introduction</h2> +<!-- ======================================================================= --> + +<p>Clang's AST is different from ASTs produced by some other compilers in that it closely +resembles both the written C++ code and the C++ standard. For example, +parenthesis expressions and compile time constants are available in an unreduced +form in the AST. This makes Clang's AST a good fit for refactoring tools.</p> + +<p>Documentation for all Clang AST nodes is available via the generated +<a href="http://clang.llvm.org/doxygen">Doxygen</a>. The doxygen online +documentation is also indexed by your favorite search engine, which will make +a search for clang and the AST node's class name usually turn up the doxygen +of the class you're looking for (for example, search for: clang ParenExpr).</p> + +<!-- ======================================================================= --> +<h2 id="examine">Examining the AST</h2> +<!-- ======================================================================= --> + +<p>A good way to familarize yourself with the Clang AST is to actually look +at it on some simple example code. Clang has a builtin AST-dump modes, which +can be enabled with the flags -ast-dump and -ast-dump-xml. Note that -ast-dump-xml +currently only works with debug-builds of clang.</p> + +<p>Let's look at a simple example AST:</p> +<pre> +# cat test.cc +int f(int x) { + int result = (x / 42); + return result; +} + +# Clang by default is a frontend for many tools; -cc1 tells it to directly +# use the C++ compiler mode. -undef leaves out some internal declarations. +$ clang -cc1 -undef -ast-dump-xml test.cc +... cutting out internal declarations of clang ... +<TranslationUnit ptr="0x4871160"> + <Function ptr="0x48a5800" name="f" prototype="true"> + <FunctionProtoType ptr="0x4871de0" canonical="0x4871de0"> + <BuiltinType ptr="0x4871250" canonical="0x4871250"/> + <parameters> + <BuiltinType ptr="0x4871250" canonical="0x4871250"/> + </parameters> + </FunctionProtoType> + <ParmVar ptr="0x4871d80" name="x" initstyle="c"> + <BuiltinType ptr="0x4871250" canonical="0x4871250"/> + </ParmVar> + <Stmt> +(CompoundStmt 0x48a5a38 <t2.cc:1:14, line:4:1> + (DeclStmt 0x48a59c0 <line:2:3, col:24> + 0x48a58c0 "int result = + (ParenExpr 0x48a59a0 <col:16, col:23> 'int' + (BinaryOperator 0x48a5978 <col:17, col:21> 'int' '/' + (ImplicitCastExpr 0x48a5960 <col:17> 'int' <LValueToRValue> + (DeclRefExpr 0x48a5918 <col:17> 'int' lvalue ParmVar 0x4871d80 'x' 'int')) + (IntegerLiteral 0x48a5940 <col:21> 'int' 42)))") + (ReturnStmt 0x48a5a18 <line:3:3, col:10> + (ImplicitCastExpr 0x48a5a00 <col:10> 'int' <LValueToRValue> + (DeclRefExpr 0x48a59d8 <col:10> 'int' lvalue Var 0x48a58c0 'result' 'int')))) + + </Stmt> + </Function> +</TranslationUnit> +</pre> +<p>In general, -ast-dump-xml dumps declarations in an XML-style format and +statements in an S-expression-style format. +The toplevel declaration in a translation unit is always the +<a href="http://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html">translation unit declaration</a>. +In this example, our first user written declaration is the +<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">function declaration</a> +of 'f'. The body of 'f' is a <a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html">compound statement</a>, +whose child nodes are a <a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">declaration statement</a> +that declares our result variable, and the +<a href="http://clang.llvm.org/doxygen/classclang_1_1ReturnStmt.html">return statement</a>.</p> + +<!-- ======================================================================= --> +<h2 id="context">AST Context</h2> +<!-- ======================================================================= --> + +<p>All information about the AST for a translation unit is bundled up in the class +<a href="http://clang.llvm.org/doxygen/classclang_1_1ASTContext.html">ASTContext</a>. +It allows traversal of the whole translation unit starting from +<a href="http://clang.llvm.org/doxygen/classclang_1_1ASTContext.html#abd909fb01ef10cfd0244832a67b1dd64">getTranslationUnitDecl</a>, +or to access Clang's <a href="http://clang.llvm.org/doxygen/classclang_1_1ASTContext.html#a4f95adb9958e22fbe55212ae6482feb4">table of identifiers</a> +for the parsed translation unit.</p> + +<!-- ======================================================================= --> +<h2 id="nodes">AST Nodes</h2> +<!-- ======================================================================= --> + +<p>Clang's AST nodes are modeled on a class hierarchy that does not have a common +ancestor. Instead, there are multiple larger hierarchies for basic node types like +<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a> and +<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>. Many +important AST nodes derive from <a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>, +<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>, +<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclContext.html">DeclContext</a> or +<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>, +with some classes deriving from both Decl and DeclContext.</p> +<p>There are also a multitude of nodes in the AST that are not part of a +larger hierarchy, and are only reachable from specific other nodes, +like <a href="http://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html">CXXBaseSpecifier</a>. +</p> + +<p>Thus, to traverse the full AST, one starts from the <a href="http://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html">TranslationUnitDecl</a> +and then recursively traverses everything that can be reached from that node +- this information has to be encoded for each specific node type. This algorithm +is encoded in the <a href="http://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html">RecursiveASTVisitor</a>. +See the <a href="http://clang.llvm.org/docs/RAVFrontendAction.html">RecursiveASTVisitor tutorial</a>.</p> + +<p>The two most basic nodes in the Clang AST are statements (<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>) +and declarations (<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>). +Note that expressions (<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>) +are also statements in Clang's AST.</p> + +</div> +</body> +</html> + diff --git a/docs/JSONCompilationDatabase.html b/docs/JSONCompilationDatabase.html new file mode 100644 index 0000000..2907194 --- /dev/null +++ b/docs/JSONCompilationDatabase.html @@ -0,0 +1,89 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>JSON Compilation Database Format Specification</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>JSON Compilation Database Format Specification</h1> +<p>This document describes a format for specifying how to replay +single compilations independently of the build system.</p> + +<h2>Background</h2> +<p>Tools based on the C++ Abstract Syntax Tree need full information how to +parse a translation unit. Usually this information is implicitly +available in the build system, but running tools as part of +the build system is not necessarily the best solution: +<ul> +<li>Build systems are inherently change driven, so running multiple +tools over the same code base without changing the code does not fit +into the architecture of many build systems.</li> +<li>Figuring out whether things have changed is often an IO bound +process; this makes it hard to build low latency end user tools based +on the build system.</li> +<li>Build systems are inherently sequential in the build graph, for example +due to generated source code. While tools that run independently of the +build still need the generated source code to exist, running tools multiple +times over unchanging source does not require serialization of the runs +according to the build dependency graph.</li> +</ul> +</p> + +<h2>Supported Systems</h2> +<p>Currently <a href="http://cmake.org">CMake</a> (since 2.8.5) supports generation of compilation +databases for Unix Makefile builds (Ninja builds in the works) with the option +CMAKE_EXPORT_COMPILE_COMMANDS.</p> +<p>Clang's tooling interface supports reading compilation databases; see +the <a href="LibTooling.html">LibTooling documentation</a>. libclang and its +python bindings also support this (since clang 3.2); see +<a href="/doxygen/group__COMPILATIONDB.html">CXCompilationDatabase.h</a>.</p> + +<h2>Format</h2> +<p>A compilation database is a JSON file, which consist of an array of +"command objects", where each command object specifies one way a translation unit +is compiled in the project.</p> +<p>Each command object contains the translation unit's main file, the working +directory of the compile run and the actual compile command.</p> +<p>Example: +<pre> +[ + { "directory": "/home/user/llvm/build", + "command": "/usr/bin/clang++ -Irelative -DSOMEDEF='\"With spaces and quotes.\"' -c -o file.o file.cc", + "file": "file.cc" }, + ... +] +</pre> +The contracts for each field in the command object are: +<ul> +<li><b>directory:</b> The working directory of the compilation. All paths specified +in the <b>command</b> or <b>file</b> fields must be either absolute or relative to +this directory.</li> +<li><b>file:</b> The main translation unit source processed by this compilation step. +This is used by tools as the key into the compilation database. There can be multiple +command objects for the same file, for example if the same source file is +compiled with different configurations.</li> +<li><b>command:</b> The compile command executed. After JSON unescaping, this must +be a valid command to rerun the exact compilation step for the translation unit in +the environment the build system uses. Parameters use shell quoting and shell escaping +of quotes, with '"' and '\' being the only special characters. Shell expansion is +not supported.</li> +</ul> +</p> + +<h2>Build System Integration</h2> +<p>The convention is to name the file compile_commands.json and put it at the top +of the build directory. Clang tools are pointed to the top of the build directory +to detect the file and use the compilation database to parse C++ code in the source +tree.</p> + +</div> +</body> +</html> + diff --git a/docs/LanguageExtensions.html b/docs/LanguageExtensions.html index 68f0afc..eac3c69 100644 --- a/docs/LanguageExtensions.html +++ b/docs/LanguageExtensions.html @@ -91,18 +91,24 @@ <li><a href="#objc_arc">Automatic reference counting</a></li> <li><a href="#objc_fixed_enum">Enumerations with a fixed underlying type</a></li> <li><a href="#objc_lambdas">Interoperability with C++11 lambdas</a></li> - <li><a href="#object-literals-subscripting">Object Literals and Subscripting</a></li> + <li><a href="#objc_object_literals_subscripting">Object Literals and Subscripting</a></li> </ul> </li> <li><a href="#overloading-in-c">Function Overloading in C</a></li> <li><a href="#complex-list-init">Initializer lists for complex numbers in C</a></li> <li><a href="#builtins">Builtin Functions</a> <ul> + <li><a href="#__builtin_readcyclecounter">__builtin_readcyclecounter</a></li> <li><a href="#__builtin_shufflevector">__builtin_shufflevector</a></li> <li><a href="#__builtin_unreachable">__builtin_unreachable</a></li> <li><a href="#__sync_swap">__sync_swap</a></li> </ul> </li> +<li><a href="#non-standard-attributes">Non-standard C++11 Attributes</a> +<ul> + <li><a href="#clang__fallthrough">The <tt>clang::fallthrough</tt> attribute</a></li> +</ul> +</li> <li><a href="#targetspecific">Target-Specific Extensions</a> <ul> <li><a href="#x86-specific">X86/X86-64 Language Extensions</a></li> @@ -655,7 +661,7 @@ framework search path. For consistency, we recommend that such files never be included in installed versions of the framework.</p> <!-- ======================================================================= --> -<h2 id="availability">Availability attribute</h2 +<h2 id="availability">Availability attribute</h2> <!-- ======================================================================= --> <p>Clang introduces the <code>availability</code> attribute, which can @@ -937,8 +943,8 @@ is enabled.</p> <p>Use <tt>__has_feature(c_atomic)</tt> or <tt>__has_extension(c_atomic)</tt> to determine if support for atomic types using <tt>_Atomic</tt> is enabled. Clang also provides <a href="#__c11_atomic">a set of builtins</a> which can be -used to implement the <tt><stdatomic.h></tt> operations on _Atomic -types.</p> +used to implement the <tt><stdatomic.h></tt> operations on +<tt>_Atomic</tt> types.</p> <h4 id="c_generic_selections">C11 generic selections</h4> @@ -1183,10 +1189,28 @@ in Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory management (autorelease).</p> <!-- ======================================================================= --> -<h2 id="object-literals-subscripting">Object Literals and Subscripting</h2> +<h2 id="objc_object_literals_subscripting">Object Literals and Subscripting</h2> +<!-- ======================================================================= --> + +<p>Clang provides support for <a href="ObjectiveCLiterals.html">Object Literals +and Subscripting</a> in Objective-C, which simplifies common Objective-C +programming patterns, makes programs more concise, and improves the safety of +container creation. There are several feature macros associated with object +literals and subscripting: <code>__has_feature(objc_array_literals)</code> +tests the availability of array literals; +<code>__has_feature(objc_dictionary_literals)</code> tests the availability of +dictionary literals; <code>__has_feature(objc_subscripting)</code> tests the +availability of object subscripting.</p> + +<!-- ======================================================================= --> +<h2 id="objc_default_synthesize_properties">Objective-C Autosynthesis of Properties</h2> <!-- ======================================================================= --> -<p>Clang provides support for <a href="ObjectiveCLiterals.html">Object Literals and Subscripting</a> in Objective-C, which simplifies common Objective-C programming patterns, makes programs more concise, and improves the safety of container creation. There are several feature macros associated with object literals and subscripting: <code>__has_feature(objc_array_literals)</code> tests the availability of array literals; <code>__has_feature(objc_dictionary_literals)</code> tests the availability of dictionary literals; <code>__has_feature(objc_subscripting)</code> tests the availability of object subscripting.</p> +<p> Clang provides support for autosynthesis of declared properties. Using this +feature, clang provides default synthesis of those properties not declared @dynamic +and not having user provided backing getter and setter methods. +<code>__has_feature(objc_default_synthesize_properties)</code> checks for availability +of this feature in version of clang being used.</p> <!-- ======================================================================= --> <h2 id="overloading-in-c">Function Overloading in C</h2> @@ -1344,6 +1368,42 @@ vector support</a> instead of builtins, in order to reduce the number of builtins that we need to implement.</p> <!-- ======================================================================= --> +<h3><a name="__builtin_readcyclecounter">__builtin_readcyclecounter</a></h3> +<!-- ======================================================================= --> + +<p><tt>__builtin_readcyclecounter</tt> is used to access the cycle counter +register (or a similar low-latency, high-accuracy clock) on those targets that +support it. +</p> + +<p><b>Syntax:</b></p> + +<pre> +__builtin_readcyclecounter() +</pre> + +<p><b>Example of Use:</b></p> + +<pre> +unsigned long long t0 = __builtin_readcyclecounter(); +do_something(); +unsigned long long t1 = __builtin_readcyclecounter(); +unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow +</pre> + +<p><b>Description:</b></p> + +<p>The __builtin_readcyclecounter() builtin returns the cycle counter value, +which may be either global or process/thread-specific depending on the target. +As the backing counters often overflow quickly (on the order of +seconds) this should only be used for timing small intervals. When not +supported by the target, the return value is always zero. This builtin +takes no arguments and produces an unsigned long long result. +</p> + +<p>Query for this feature with __has_builtin(__builtin_readcyclecounter).</p> + +<!-- ======================================================================= --> <h3><a name="__builtin_shufflevector">__builtin_shufflevector</a></h3> <!-- ======================================================================= --> @@ -1489,6 +1549,54 @@ with a <tt>__c11_</tt> prefix. The supported operations are:</p> <li><tt>__c11_atomic_fetch_xor</tt></li> </ul> +<!-- ======================================================================= --> +<h2 id="non-standard-attributes">Non-standard C++11 Attributes</h2> +<!-- ======================================================================= --> + +<p>Clang supports one non-standard C++11 attribute. It resides in the +<tt>clang</tt> attribute namespace.</p> + +<!-- ======================================================================= --> +<h3 id="clang__fallthrough">The <tt>clang::fallthrough</tt> attribute</h3> +<!-- ======================================================================= --> + +<p>The <tt>clang::fallthrough</tt> attribute is used along with the +<tt>-Wimplicit-fallthrough</tt> argument to annotate intentional fall-through +between switch labels. It can only be applied to a null statement placed at a +point of execution between any statement and the next switch label. It is common +to mark these places with a specific comment, but this attribute is meant to +replace comments with a more strict annotation, which can be checked by the +compiler. This attribute doesn't change semantics of the code and can be used +wherever an intended fall-through occurs. It is designed to mimic +control-flow statements like <tt>break;</tt>, so it can be placed in most places +where <tt>break;</tt> can, but only if there are no statements on the execution +path between it and the next switch label.</p> +<p>Here is an example:</p> +<pre> +// compile with -Wimplicit-fallthrough +switch (n) { +case 33: + f(); +case 44: // warning: unannotated fall-through + g(); + <b>[[clang::fallthrough]];</b> +case 55: // no warning + if (x) { + h(); + break; + } + else { + i(); + <b>[[clang::fallthrough]];</b> + } +case 66: // no warning + p(); + <b>[[clang::fallthrough]];</b> // warning: fallthrough annotation does not directly precede case label + q(); +case 77: // warning: unannotated fall-through + r(); +} +</pre> <!-- ======================================================================= --> <h2 id="targetspecific">Target-Specific Extensions</h2> diff --git a/docs/LibTooling.html b/docs/LibTooling.html new file mode 100644 index 0000000..ed0ad45 --- /dev/null +++ b/docs/LibTooling.html @@ -0,0 +1,229 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>LibTooling</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>LibTooling</h1> +<p>LibTooling is a library to support writing standalone tools based on +Clang. This document will provide a basic walkthrough of how to write +a tool using LibTooling.</p> + +<!-- ======================================================================= --> +<h2 id="intro">Introduction</h2> +<!-- ======================================================================= --> + +<p>Tools built with LibTooling, like Clang Plugins, run FrontendActions over +code. <!-- See FIXME for a tutorial on how to write FrontendActions. --> +In this tutorial, we'll demonstrate the different ways of running clang's +SyntaxOnlyAction, which runs a quick syntax check, over a bunch of +code.</p> + +<!-- ======================================================================= --> +<h2 id="runoncode">Parsing a code snippet in memory.</h2> +<!-- ======================================================================= --> + +<p>If you ever wanted to run a FrontendAction over some sample code, for example +to unit test parts of the Clang AST, runToolOnCode is what you looked for. Let +me give you an example: +<pre> + #include "clang/Tooling/Tooling.h" + + TEST(runToolOnCode, CanSyntaxCheckCode) { + // runToolOnCode returns whether the action was correctly run over the + // given code. + EXPECT_TRUE(runToolOnCode(new clang::SyntaxOnlyAction, "class X {};")); + } +</pre> + +<!-- ======================================================================= --> +<h2 id="standalonetool">Writing a standalone tool.</h2> +<!-- ======================================================================= --> + +<p>Once you unit tested your FrontendAction to the point where it cannot +possibly break, it's time to create a standalone tool. For a standalone tool +to run clang, it first needs to figure out what command line arguments to use +for a specified file. To that end we create a CompilationDatabase.</p> + +<h3 id="compilationdb">Creating a compilation database.</h3> +<p>CompilationDatabase provides static factory functions to help with parsing +compile commands from a build directory or the command line. The following code +allows for both explicit specification of a compile command line, as well as +retrieving the compile commands lines from a database. +<pre> +int main(int argc, const char **argv) { + // First, try to create a fixed compile command database from the command line + // arguments. + llvm::OwningPtr<CompilationDatabase> Compilations( + FixedCompilationDatabase::loadFromCommandLine(argc, argv)); + + // Next, use normal llvm command line parsing to get the tool specific + // parameters. + cl::ParseCommandLineOptions(argc, argv); + + if (!Compilations) { + // In case the user did not specify the compile command line via positional + // command line arguments after "--", try to load the compile commands from + // a database in the specified build directory or auto-detect it from a + // source file. + std::string ErrorMessage; + if (!BuildPath.empty()) { + Compilations.reset( + CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage)); + } else { + Compilations.reset(CompilationDatabase::autoDetectFromSource( + SourcePaths[0], ErrorMessage)); + } + // If there is still no valid compile command database, we don't know how + // to run the tool. + if (!Compilations) + llvm::report_fatal_error(ErrorMessage); + } +} +</pre> +</p> + +<h3 id="tool">Creating and running a ClangTool.</h3> +<p>Once we have a CompilationDatabase, we can create a ClangTool and run our +FrontendAction over some code. For example, to run the SyntaxOnlyAction over +the files "a.cc" and "b.cc" one would write: +<pre> + // A clang tool can run over a number of sources in the same process... + std::vector<std::string> Sources; + Sources.push_back("a.cc"); + Sources.push_back("b.cc"); + + // We hand the CompilationDatabase we created and the sources to run over into + // the tool constructor. + ClangTool Tool(*Compilations, Sources); + + // The ClangTool needs a new FrontendAction for each translation unit we run + // on. Thus, it takes a FrontendActionFactory as parameter. To create a + // FrontendActionFactory from a given FrontendAction type, we call + // newFrontendActionFactory<clang::SyntaxOnlyAction>(). + int result = Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>()); +</pre> +</p> + +<h3 id="main">Putting it together - the first tool.</h3> +<p>Now we combine the two previous steps into our first real tool. This example +tool is also checked into the clang tree at tools/clang-check/ClangCheck.cpp. +<pre> +#include "llvm/Support/CommandLine.h" +#include "clang/Frontend/FrontendActions.h" +#include "clang/Tooling/CompilationDatabase.h" +#include "clang/Tooling/Tooling.h" + +using namespace clang::tooling; +using namespace llvm; + +cl::opt<std::string> BuildPath( + "p", + cl::desc("<build-path>"), + cl::Optional); + +cl::list<std::string> SourcePaths( + cl::Positional, + cl::desc("<source0> [... <sourceN>]"), + cl::OneOrMore); + +int main(int argc, const char **argv) { + llvm::OwningPtr<CompilationDatabase> Compilations( + FixedCompilationDatabase::loadFromCommandLine(argc, argv)); + cl::ParseCommandLineOptions(argc, argv); + if (!Compilations) { + std::string ErrorMessage; + Compilations.reset( + !BuildPath.empty() ? + CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage) : + CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage) + ); + if (!Compilations) + llvm::report_fatal_error(ErrorMessage); + } + ClangTool Tool(*Compilations, SourcePaths); + return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>()); +} +</pre> +</p> + +<h3 id="running">Running the tool on some code.</h3> +<p>When you check out and build clang, clang-check is already built and +available to you in bin/clang-check inside your build directory.</p> +<p>You can run clang-check on a file in the llvm repository by specifying +all the needed parameters after a "--" separator: +<pre> + $ cd /path/to/source/llvm + $ export BD=/path/to/build/llvm + $ $BD/bin/clang-check tools/clang/tools/clang-check/ClangCheck.cpp -- \ + clang++ -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS \ + -Itools/clang/include -I$BD/include -Iinclude -Itools/clang/lib/Headers -c +</pre> +</p> + +<p>As an alternative, you can also configure cmake to output a compile command +database into its build directory: +<pre> + # Alternatively to calling cmake, use ccmake, toggle to advanced mode and + # set the parameter CMAKE_EXPORT_COMPILE_COMMANDS from the UI. + $ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON . +</pre> +</p> +<p> +This creates a file called compile_commands.json in the build directory. Now +you can run clang-check over files in the project by specifying the build path +as first argument and some source files as further positional arguments: +<pre> + $ cd /path/to/source/llvm + $ export BD=/path/to/build/llvm + $ $BD/bin/clang-check -p $BD tools/clang/tools/clang-check/ClangCheck.cpp +</pre> +</p> + +<h3 id="builtin">Builtin includes.</h3> +<p>Clang tools need their builtin headers and search for them the same way clang +does. Thus, the default location to look for builtin headers is in a path +$(dirname /path/to/tool)/../lib/clang/3.2/include relative to the tool +binary. This works out-of-the-box for tools running from llvm's toplevel +binary directory after building clang-headers, or if the tool is running +from the binary directory of a clang install next to the clang binary.</p> + +<p>Tips: if your tool fails to find stddef.h or similar headers, call +the tool with -v and look at the search paths it looks through.</p> + +<h3 id="linking">Linking.</h3> +<p>Please note that this presents the linking requirements at the time of this +writing. For the most up-to-date information, look at one of the tools' +Makefiles (for example +<a href="http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-check/Makefile?view=markup">clang-check/Makefile</a>). +</p> + +<p>To link a binary using the tooling infrastructure, link in the following +libraries: +<ul> +<li>Tooling</li> +<li>Frontend</li> +<li>Driver</li> +<li>Serialization</li> +<li>Parse</li> +<li>Sema</li> +<li>Analysis</li> +<li>Edit</li> +<li>AST</li> +<li>Lex</li> +<li>Basic</li> +</ul> +</p> + +</div> +</body> +</html> + diff --git a/docs/ObjectiveCLiterals.html b/docs/ObjectiveCLiterals.html index 63b523c..11751a6 100644 --- a/docs/ObjectiveCLiterals.html +++ b/docs/ObjectiveCLiterals.html @@ -4,7 +4,7 @@ <html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF8"> - <title>Clang Language Extensions</title> + <title>Objective-C Literals</title> <link type="text/css" rel="stylesheet" href="../menu.css"> <link type="text/css" rel="stylesheet" href="../content.css"> <style type="text/css"> @@ -24,21 +24,21 @@ <h2>Introduction</h2> -Three new features were introduced into clang at the same time: <i>NSNumber Literals</i> provide a syntax for creating <code>NSNumber</code> from scalar literal expressions; <i>Collection Literals</i> provide a short-hand for creating arrays and dictionaries; <i>Object Subscripting</i> provides a way to use subscripting with Objective-C objects. Users of Apple compiler releases can use these features starting with the Apple LLVM Compiler 4.0. Users of open-source LLVM.org compiler releases can use these features starting with clang v3.1.<p> +<p>Three new features were introduced into clang at the same time: <i>NSNumber Literals</i> provide a syntax for creating <code>NSNumber</code> from scalar literal expressions; <i>Collection Literals</i> provide a short-hand for creating arrays and dictionaries; <i>Object Subscripting</i> provides a way to use subscripting with Objective-C objects. Users of Apple compiler releases can use these features starting with the Apple LLVM Compiler 4.0. Users of open-source LLVM.org compiler releases can use these features starting with clang v3.1.</p> -These language additions simplify common Objective-C programming patterns, make programs more concise, and improve the safety of container creation.<p> +<p>These language additions simplify common Objective-C programming patterns, make programs more concise, and improve the safety of container creation.</p> -This document describes how the features are implemented in clang, and how to use them in your own programs.<p> +<p>This document describes how the features are implemented in clang, and how to use them in your own programs.</p> <h2>NSNumber Literals</h2> -The framework class <code>NSNumber</code> is used to wrap scalar values inside objects: signed and unsigned integers (<code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>), floating point numbers (<code>float</code>, <code>double</code>), and boolean values (<code>BOOL</code>, C++ <code>bool</code>). Scalar values wrapped in objects are also known as <i>boxed</i> values.<p> +<p>The framework class <code>NSNumber</code> is used to wrap scalar values inside objects: signed and unsigned integers (<code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>long long</code>), floating point numbers (<code>float</code>, <code>double</code>), and boolean values (<code>BOOL</code>, C++ <code>bool</code>). Scalar values wrapped in objects are also known as <i>boxed</i> values.</p> -In Objective-C, any character, numeric or boolean literal prefixed with the <code>'@'</code> character will evaluate to a pointer to an <code>NSNumber</code> object initialized with that value. C's type suffixes may be used to control the size of numeric literals. +<p>In Objective-C, any character, numeric or boolean literal prefixed with the <code>'@'</code> character will evaluate to a pointer to an <code>NSNumber</code> object initialized with that value. C's type suffixes may be used to control the size of numeric literals.</p> <h3>Examples</h3> -The following program illustrates the rules for <code>NSNumber</code> literals:<p> +<p>The following program illustrates the rules for <code>NSNumber</code> literals:</p> <pre> void main(int argc, const char *argv[]) { @@ -68,18 +68,19 @@ void main(int argc, const char *argv[]) { <h3>Discussion</h3> -NSNumber literals only support literal scalar values after the '@'. Consequently, @INT_MAX works, but @INT_MIN does not, because they are defined like this:<p> +<p>NSNumber literals only support literal scalar values after the <code>'@'</code>. Consequently, <code>@INT_MAX</code> works, but <code>@INT_MIN</code> does not, because they are defined like this:</p> <pre> #define INT_MAX 2147483647 /* max value for an int */ #define INT_MIN (-2147483647-1) /* min value for an int */ </pre> -The definition of INT_MIN is not a simple literal, but a parenthesized expression. This is by design, but may be improved in subsequent compiler releases.<p> +<p>The definition of <code>INT_MIN</code> is not a simple literal, but a parenthesized expression. Parenthesized +expressions are supported using the <a href="#objc_boxed_expressions">boxed expression</a> syntax, which is described in the next section.</p> -Because <code>NSNumber</code> does not currently support wrapping <code>long double</code> values, the use of a <code>long double NSNumber</code> literal (e.g. <code>@123.23L</code>) will be rejected by the compiler.<p> +<p>Because <code>NSNumber</code> does not currently support wrapping <code>long double</code> values, the use of a <code>long double NSNumber</code> literal (e.g. <code>@123.23L</code>) will be rejected by the compiler.</p> -Previously, the <code>BOOL</code> type was simply a typedef for <code>signed char</code>, and <code>YES</code> and <code>NO</code> were macros that expand to <code>(BOOL)1</code> and <code>(BOOL)0</code> respectively. To support <code>@YES</code> and <code>@NO</code> expressions, these macros are now defined using new language keywords in <code><objc/objc.h></code>:<p> +<p>Previously, the <code>BOOL</code> type was simply a typedef for <code>signed char</code>, and <code>YES</code> and <code>NO</code> were macros that expand to <code>(BOOL)1</code> and <code>(BOOL)0</code> respectively. To support <code>@YES</code> and <code>@NO</code> expressions, these macros are now defined using new language keywords in <code><objc/objc.h></code>:</p> <pre> #if __has_feature(objc_bool) @@ -91,26 +92,126 @@ Previously, the <code>BOOL</code> type was simply a typedef for <code>signed cha #endif </pre> -The compiler implicitly converts <code>__objc_yes</code> and <code>__objc_no</code> to <code>(BOOL)1</code> and <code>(BOOL)0</code>. The keywords are used to disambiguate <code>BOOL</code> and integer literals.<p> +<p>The compiler implicitly converts <code>__objc_yes</code> and <code>__objc_no</code> to <code>(BOOL)1</code> and <code>(BOOL)0</code>. The keywords are used to disambiguate <code>BOOL</code> and integer literals.</p> -Objective-C++ also supports <code>@true</code> and <code>@false</code> expressions, which are equivalent to <code>@YES</code> and <code>@NO</code>. +<p>Objective-C++ also supports <code>@true</code> and <code>@false</code> expressions, which are equivalent to <code>@YES</code> and <code>@NO</code>.</p> +<!-- ======================================================================= --> +<h2 id="objc_boxed_expressions">Boxed Expressions</h2> +<!-- ======================================================================= --> + +<p>Objective-C provides a new syntax for boxing C expressions:</p> + +<pre> +<code>@( <em>expression</em> )</code> +</pre> + +<p>Expressions of scalar (numeric, enumerated, BOOL) and C string pointer types +are supported:</p> + +<pre> +// numbers. +NSNumber *smallestInt = @(-INT_MAX - 1); // [NSNumber numberWithInt:(-INT_MAX - 1)] +NSNumber *piOverTwo = @(M_PI / 2); // [NSNumber numberWithDouble:(M_PI / 2)] + +// enumerated types. +typedef enum { Red, Green, Blue } Color; +NSNumber *favoriteColor = @(Green); // [NSNumber numberWithInt:((int)Green)] + +// strings. +NSString *path = @(getenv("PATH")); // [NSString stringWithUTF8String:(getenv("PATH"))] +NSArray *pathComponents = [path componentsSeparatedByString:@":"]; +</pre> + +<h3>Boxed Enums</h3> + +<p> +Cocoa frameworks frequently define constant values using <em>enums.</em> Although enum values are integral, they may not be used directly as boxed literals (this avoids conflicts with future <code>'@'</code>-prefixed Objective-C keywords). Instead, an enum value must be placed inside a boxed expression. The following example demonstrates configuring an <code>AVAudioRecorder</code> using a dictionary that contains a boxed enumeration value: +</p> + +<pre> +enum { + AVAudioQualityMin = 0, + AVAudioQualityLow = 0x20, + AVAudioQualityMedium = 0x40, + AVAudioQualityHigh = 0x60, + AVAudioQualityMax = 0x7F +}; + +- (AVAudioRecorder *)recordToFile:(NSURL *)fileURL { + NSDictionary *settings = @{ AVEncoderAudioQualityKey : @(AVAudioQualityMax) }; + return [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:NULL]; +} +</pre> + +<p> +The expression <code>@(AVAudioQualityMax)</code> converts <code>AVAudioQualityMax</code> to an integer type, and boxes the value accordingly. If the enum has a <a href="http://clang.llvm.org/docs/LanguageExtensions.html#objc_fixed_enum">fixed underlying type</a> as in: +</p> + +<pre> +typedef enum : unsigned char { Red, Green, Blue } Color; +NSNumber *red = @(Red), *green = @(Green), *blue = @(Blue); // => [NSNumber numberWithUnsignedChar:] +</pre> + +<p> +then the fixed underlying type will be used to select the correct <code>NSNumber</code> creation method. +</p> + +<p> +Boxing a value of enum type will result in a <code>NSNumber</code> pointer with a creation method according to the underlying type of the enum, +which can be a <a href="http://clang.llvm.org/docs/LanguageExtensions.html#objc_fixed_enum">fixed underlying type</a> or a compiler-defined +integer type capable of representing the values of all the members of the enumeration: +</p> + +<pre> +typedef enum : unsigned char { Red, Green, Blue } Color; +Color col = Red; +NSNumber *nsCol = @(col); // => [NSNumber numberWithUnsignedChar:] +</pre> + +<h3>Boxed C Strings</h3> + +<p> +A C string literal prefixed by the <code>'@'</code> token denotes an <code>NSString</code> literal in the same way a numeric literal prefixed by the <code>'@'</code> token denotes an <code>NSNumber</code> literal. When the type of the parenthesized expression is <code>(char *)</code> or <code>(const char *)</code>, the result of the boxed expression is a pointer to an <code>NSString</code> object containing equivalent character data, which is assumed to be '\0'-terminated and UTF-8 encoded. The following example converts C-style command line arguments into <code>NSString</code> objects. +</p> + +<pre> +// Partition command line arguments into positional and option arguments. +NSMutableArray *args = [NSMutableArray new]; +NSMutableDictionary *options = [NSMutableArray new]; +while (--argc) { + const char *arg = *++argv; + if (strncmp(arg, "--", 2) == 0) { + options[@(arg + 2)] = @(*++argv); // --key value + } else { + [args addObject:@(arg)]; // positional argument + } +} +</pre> + +<p> +As with all C pointers, character pointer expressions can involve arbitrary pointer arithmetic, therefore programmers must ensure that the character data is valid. Passing <code>NULL</code> as the character pointer will raise an exception at runtime. When possible, the compiler will reject <code>NULL</code> character pointers used in boxed expressions. +</p> + +<h3>Availability</h3> + +<p>Boxed expressions will be available in clang 3.2. It is not currently available in any Apple compiler.</p> <h2>Container Literals</h2> -Objective-C now supports a new expression syntax for creating immutable array and dictionary container objects. +<p>Objective-C now supports a new expression syntax for creating immutable array and dictionary container objects.</p> <h3>Examples</h3> -Immutable array expression:<p> +<p>Immutable array expression:</p> - <pre> +<pre> NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ]; </pre> -This creates an <code>NSArray</code> with 3 elements. The comma-separated sub-expressions of an array literal can be any Objective-C object pointer typed expression.<p> +<p>This creates an <code>NSArray</code> with 3 elements. The comma-separated sub-expressions of an array literal can be any Objective-C object pointer typed expression.</p> -Immutable dictionary expression:<p> +<p>Immutable dictionary expression:</p> <pre> NSDictionary *dictionary = @{ @@ -120,21 +221,21 @@ NSDictionary *dictionary = @{ }; </pre> -This creates an <code>NSDictionary</code> with 3 key/value pairs. Value sub-expressions of a dictionary literal must be Objective-C object pointer typed, as in array literals. Key sub-expressions must be of an Objective-C object pointer type that implements the <code><NSCopying></code> protocol.<p> +<p>This creates an <code>NSDictionary</code> with 3 key/value pairs. Value sub-expressions of a dictionary literal must be Objective-C object pointer typed, as in array literals. Key sub-expressions must be of an Objective-C object pointer type that implements the <code><NSCopying></code> protocol.</p> <h3>Discussion</h3> -Neither keys nor values can have the value <code>nil</code> in containers. If the compiler can prove that a key or value is <code>nil</code> at compile time, then a warning will be emitted. Otherwise, a runtime error will occur.<p> +<p>Neither keys nor values can have the value <code>nil</code> in containers. If the compiler can prove that a key or value is <code>nil</code> at compile time, then a warning will be emitted. Otherwise, a runtime error will occur.</p> -Using array and dictionary literals is safer than the variadic creation forms commonly in use today. Array literal expressions expand to calls to <code>+[NSArray arrayWithObjects:count:]</code>, which validates that all objects are non-<code>nil</code>. The variadic form, <code>+[NSArray arrayWithObjects:]</code> uses <code>nil</code> as an argument list terminator, which can lead to malformed array objects. Dictionary literals are similarly created with <code>+[NSDictionary dictionaryWithObjects:forKeys:count:]</code> which validates all objects and keys, unlike <code>+[NSDictionary dictionaryWithObjectsAndKeys:]</code> which also uses a <code>nil</code> parameter as an argument list terminator.<p> +<p>Using array and dictionary literals is safer than the variadic creation forms commonly in use today. Array literal expressions expand to calls to <code>+[NSArray arrayWithObjects:count:]</code>, which validates that all objects are non-<code>nil</code>. The variadic form, <code>+[NSArray arrayWithObjects:]</code> uses <code>nil</code> as an argument list terminator, which can lead to malformed array objects. Dictionary literals are similarly created with <code>+[NSDictionary dictionaryWithObjects:forKeys:count:]</code> which validates all objects and keys, unlike <code>+[NSDictionary dictionaryWithObjectsAndKeys:]</code> which also uses a <code>nil</code> parameter as an argument list terminator.</p> <h2>Object Subscripting</h2> -Objective-C object pointer values can now be used with C's subscripting operator.<p> +<p>Objective-C object pointer values can now be used with C's subscripting operator.</p> <h3>Examples</h3> -The following code demonstrates the use of object subscripting syntax with <code>NSMutableArray</code> and <code>NSMutableDictionary</code> objects:<p> +<p>The following code demonstrates the use of object subscripting syntax with <code>NSMutableArray</code> and <code>NSMutableDictionary</code> objects:</p> <pre> NSMutableArray *array = ...; @@ -149,87 +250,93 @@ oldObject = dictionary[key]; dictionary[key] = newObject; // replace oldObject with newObject </pre> -The next section explains how subscripting expressions map to accessor methods.<p> +<p>The next section explains how subscripting expressions map to accessor methods.</p> <h3>Subscripting Methods</h3> -Objective-C supports two kinds of subscript expressions: <i>array-style</i> subscript expressions use integer typed subscripts; <i>dictionary-style</i> subscript expressions use Objective-C object pointer typed subscripts. Each type of subscript expression is mapped to a message send using a predefined selector. The advantage of this design is flexibility: class designers are free to introduce subscripting by declaring methods or by adopting protocols. Moreover, because the method names are selected by the type of the subscript, an object can be subscripted using both array and dictionary styles. +<p>Objective-C supports two kinds of subscript expressions: <i>array-style</i> subscript expressions use integer typed subscripts; <i>dictionary-style</i> subscript expressions use Objective-C object pointer typed subscripts. Each type of subscript expression is mapped to a message send using a predefined selector. The advantage of this design is flexibility: class designers are free to introduce subscripting by declaring methods or by adopting protocols. Moreover, because the method names are selected by the type of the subscript, an object can be subscripted using both array and dictionary styles.</p> <h4>Array-Style Subscripting</h4> -When the subscript operand has an integral type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read or written. When an expression reads an element using an integral index, as in the following example:<p> +<p>When the subscript operand has an integral type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read or written. When an expression reads an element using an integral index, as in the following example:</p> <pre> NSUInteger idx = ...; id value = object[idx]; </pre> -it is translated into a call to <code>objectAtIndexedSubscript:</code><p> +<p>it is translated into a call to <code>objectAtIndexedSubscript:</code></p> <pre> id value = [object objectAtIndexedSubscript:idx]; </pre> -When an expression writes an element using an integral index:<p> +<p>When an expression writes an element using an integral index:</p> <pre> object[idx] = newValue; </pre> -it is translated to a call to <code>setObject:atIndexedSubscript:</code><p> +<p>it is translated to a call to <code>setObject:atIndexedSubscript:</code></p> <pre> [object setObject:newValue atIndexedSubscript:idx]; </pre> -These message sends are then type-checked and performed just like explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an argument of integral type and a return value of some Objective-C object pointer type. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.<p> +<p>These message sends are then type-checked and performed just like explicit message sends. The method used for objectAtIndexedSubscript: must be declared with an argument of integral type and a return value of some Objective-C object pointer type. The method used for setObject:atIndexedSubscript: must be declared with its first argument having some Objective-C pointer type and its second argument having integral type.</p> -The meaning of indexes is left up to the declaring class. The compiler will coerce the index to the appropriate argument type of the method it uses for type-checking. For an instance of <code>NSArray</code>, reading an element using an index outside the range <code>[0, array.count)</code> will raise an exception. For an instance of <code>NSMutableArray</code>, assigning to an element using an index within this range will replace that element, but assigning to an element using an index outside this range will raise an exception; no syntax is provided for inserting, appending, or removing elements for mutable arrays.<p> +<p>The meaning of indexes is left up to the declaring class. The compiler will coerce the index to the appropriate argument type of the method it uses for type-checking. For an instance of <code>NSArray</code>, reading an element using an index outside the range <code>[0, array.count)</code> will raise an exception. For an instance of <code>NSMutableArray</code>, assigning to an element using an index within this range will replace that element, but assigning to an element using an index outside this range will raise an exception; no syntax is provided for inserting, appending, or removing elements for mutable arrays.</p> -A class need not declare both methods in order to take advantage of this language feature. For example, the class <code>NSArray</code> declares only <code>objectAtIndexedSubscript:</code>, so that assignments to elements will fail to type-check; moreover, its subclass <code>NSMutableArray</code> declares <code>setObject:atIndexedSubscript:</code>. +<p>A class need not declare both methods in order to take advantage of this language feature. For example, the class <code>NSArray</code> declares only <code>objectAtIndexedSubscript:</code>, so that assignments to elements will fail to type-check; moreover, its subclass <code>NSMutableArray</code> declares <code>setObject:atIndexedSubscript:</code>.</p> <h4>Dictionary-Style Subscripting</h4> -When the subscript operand has an Objective-C object pointer type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read from or written to. When an expression reads an element using an Objective-C object pointer subscript operand, as in the following example:<p> +<p>When the subscript operand has an Objective-C object pointer type, the expression is rewritten to use one of two different selectors, depending on whether the element is being read from or written to. When an expression reads an element using an Objective-C object pointer subscript operand, as in the following example:</p> <pre> id key = ...; id value = object[key]; </pre> -it is translated into a call to the <code>objectForKeyedSubscript:</code> method:<p> +<p>it is translated into a call to the <code>objectForKeyedSubscript:</code> method:</p> <pre> id value = [object objectForKeyedSubscript:key]; </pre> -When an expression writes an element using an Objective-C object pointer subscript:<p> +<p>When an expression writes an element using an Objective-C object pointer subscript:</p> <pre> object[key] = newValue; </pre> -it is translated to a call to <code>setObject:forKeyedSubscript:</code> +<p>it is translated to a call to <code>setObject:forKeyedSubscript:</code></p> <pre> [object setObject:newValue forKeyedSubscript:key]; </pre> -The behavior of <code>setObject:forKeyedSubscript:</code> is class-specific; but in general it should replace an existing value if one is already associated with a key, otherwise it should add a new value for the key. No syntax is provided for removing elements from mutable dictionaries.<p> +<p>The behavior of <code>setObject:forKeyedSubscript:</code> is class-specific; but in general it should replace an existing value if one is already associated with a key, otherwise it should add a new value for the key. No syntax is provided for removing elements from mutable dictionaries.</p> <h3>Discussion</h3> -An Objective-C subscript expression occurs when the base operand of the C subscript operator has an Objective-C object pointer type. Since this potentially collides with pointer arithmetic on the value, these expressions are only supported under the modern Objective-C runtime, which categorically forbids such arithmetic.<p> +<p>An Objective-C subscript expression occurs when the base operand of the C subscript operator has an Objective-C object pointer type. Since this potentially collides with pointer arithmetic on the value, these expressions are only supported under the modern Objective-C runtime, which categorically forbids such arithmetic.</p> -Currently, only subscripts of integral or Objective-C object pointer type are supported. In C++, a class type can be used if it has a single conversion function to an integral or Objective-C pointer type, in which case that conversion is applied and analysis continues as appropriate. Otherwise, the expression is ill-formed.<p> +<p>Currently, only subscripts of integral or Objective-C object pointer type are supported. In C++, a class type can be used if it has a single conversion function to an integral or Objective-C pointer type, in which case that conversion is applied and analysis continues as appropriate. Otherwise, the expression is ill-formed.</p> -An Objective-C object subscript expression is always an l-value. If the expression appears on the left-hand side of a simple assignment operator (=), the element is written as described below. If the expression appears on the left-hand side of a compound assignment operator (e.g. +=), the program is ill-formed, because the result of reading an element is always an Objective-C object pointer and no binary operators are legal on such pointers. If the expression appears in any other position, the element is read as described below. It is an error to take the address of a subscript expression, or (in C++) to bind a reference to it.<p> +<p>An Objective-C object subscript expression is always an l-value. If the expression appears on the left-hand side of a simple assignment operator (=), the element is written as described below. If the expression appears on the left-hand side of a compound assignment operator (e.g. +=), the program is ill-formed, because the result of reading an element is always an Objective-C object pointer and no binary operators are legal on such pointers. If the expression appears in any other position, the element is read as described below. It is an error to take the address of a subscript expression, or (in C++) to bind a reference to it.</p> + +<p>Programs can use object subscripting with Objective-C object pointers of type <code>id</code>. Normal dynamic message send rules apply; the compiler must see <i>some</i> declaration of the subscripting methods, and will pick the declaration seen first.</p> + +<h2>Caveats</h2> -Programs can use object subscripting with Objective-C object pointers of type <code>id</code>. Normal dynamic message send rules apply; the compiler must see <i>some</i> declaration of the subscripting methods, and will pick the declaration seen first.<p> +<p>Objects created using the literal or boxed expression syntax are not guaranteed to be uniqued by the runtime, but nor are they guaranteed to be newly-allocated. As such, the result of performing direct comparisons against the location of an object literal (using <code>==</code>, <code>!=</code>, <code><</code>, <code><=</code>, <code>></code>, or <code>>=</code>) is not well-defined. This is usually a simple mistake in code that intended to call the <code>isEqual:</code> method (or the <code>compare:</code> method).</p> + +<p>This caveat applies to compile-time string literals as well. Historically, string literals (using the <code>@"..."</code> syntax) have been uniqued across translation units during linking. This is an implementation detail of the compiler and should not be relied upon. If you are using such code, please use global string constants instead (<code>NSString * const MyConst = @"..."</code>) or use <code>isEqual:</code>.</p> <h2>Grammar Additions</h2> -To support the new syntax described above, the Objective-C <code>@</code>-expression grammar has the following new productions:<p> +<p>To support the new syntax described above, the Objective-C <code>@</code>-expression grammar has the following new productions:</p> <pre> objc-at-expression : '@' (string-literal | encode-literal | selector-literal | protocol-literal | object-literal) @@ -263,11 +370,11 @@ key-value-pair : assignment-expression ':' assignment-expression ; </pre> -Note: <code>@true</code> and <code>@false</code> are only supported in Objective-C++.<p> +<p>Note: <code>@true</code> and <code>@false</code> are only supported in Objective-C++.</p> <h2>Availability Checks</h2> -Programs test for the new features by using clang's __has_feature checks. Here are examples of their use:<p> +<p>Programs test for the new features by using clang's __has_feature checks. Here are examples of their use:</p> <pre> #if __has_feature(objc_array_literals) @@ -307,7 +414,9 @@ Programs test for the new features by using clang's __has_feature checks. Here a #endif </pre> -Code can use also <code>__has_feature(objc_bool)</code> to check for the availability of numeric literals support. This checks for the new <code>__objc_yes / __objc_no</code> keywords, which enable the use of <code>@YES / @NO</code> literals.<p> +<p>Code can use also <code>__has_feature(objc_bool)</code> to check for the availability of numeric literals support. This checks for the new <code>__objc_yes / __objc_no</code> keywords, which enable the use of <code>@YES / @NO</code> literals.</p> + +<p>To check whether boxed expressions are supported, use <code>__has_feature(objc_boxed_expressions)</code> feature macro.</p> </div> </body> diff --git a/docs/RAVFrontendAction.html b/docs/RAVFrontendAction.html new file mode 100644 index 0000000..b30cd57 --- /dev/null +++ b/docs/RAVFrontendAction.html @@ -0,0 +1,224 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>How to write RecursiveASTVisitor based ASTFrontendActions.</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>How to write RecursiveASTVisitor based ASTFrontendActions.</h1> + +<!-- ======================================================================= --> +<h2 id="intro">Introduction</h2> +<!-- ======================================================================= --> + +In this tutorial you will learn how to create a FrontendAction that uses +a RecursiveASTVisitor to find CXXRecordDecl AST nodes with a specified name. + +<!-- ======================================================================= --> +<h2 id="action">Creating a FrontendAction</h2> +<!-- ======================================================================= --> + +<p>When writing a clang based tool like a Clang Plugin or a standalone tool +based on LibTooling, the common entry point is the FrontendAction. +FrontendAction is an interface that allows execution of user specific actions +as part of the compilation. To run tools over the AST clang provides the +convenience interface ASTFrontendAction, which takes care of executing the +action. The only part left is to implement the CreateASTConsumer method that +returns an ASTConsumer per translation unit.</p> +<pre> + class FindNamedClassAction : public clang::ASTFrontendAction { + public: + virtual clang::ASTConsumer *CreateASTConsumer( + clang::CompilerInstance &Compiler, llvm::StringRef InFile) { + return new FindNamedClassConsumer; + } + }; +</pre> + +<!-- ======================================================================= --> +<h2 id="consumer">Creating an ASTConsumer</h2> +<!-- ======================================================================= --> + +<p>ASTConsumer is an interface used to write generic actions on an AST, +regardless of how the AST was produced. ASTConsumer provides many different +entry points, but for our use case the only one needed is HandleTranslationUnit, +which is called with the ASTContext for the translation unit.</p> +<pre> + class FindNamedClassConsumer : public clang::ASTConsumer { + public: + virtual void HandleTranslationUnit(clang::ASTContext &Context) { + // Traversing the translation unit decl via a RecursiveASTVisitor + // will visit all nodes in the AST. + Visitor.TraverseDecl(Context.getTranslationUnitDecl()); + } + private: + // A RecursiveASTVisitor implementation. + FindNamedClassVisitor Visitor; + }; +</pre> + +<!-- ======================================================================= --> +<h2 id="rav">Using the RecursiveASTVisitor</h2> +<!-- ======================================================================= --> + +<p>Now that everything is hooked up, the next step is to implement a +RecursiveASTVisitor to extract the relevant information from the AST.</p> +<p>The RecursiveASTVisitor provides hooks of the form +bool VisitNodeType(NodeType *) for most AST nodes; the exception are TypeLoc +nodes, which are passed by-value. We only need to implement the methods for the +relevant node types. +</p> +<p>Let's start by writing a RecursiveASTVisitor that visits all CXXRecordDecl's. +<pre> + class FindNamedClassVisitor + : public RecursiveASTVisitor<FindNamedClassVisitor> { + public: + bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) { + // For debugging, dumping the AST nodes will show which nodes are already + // being visited. + Declaration->dump(); + + // The return value indicates whether we want the visitation to proceed. + // Return false to stop the traversal of the AST. + return true; + } + }; +</pre> +</p> +<p>In the methods of our RecursiveASTVisitor we can now use the full power of +the Clang AST to drill through to the parts that are interesting for us. For +example, to find all class declaration with a certain name, we can check for a +specific qualified name: +<pre> + bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) { + if (Declaration->getQualifiedNameAsString() == "n::m::C") + Declaration->dump(); + return true; + } +</pre> +</p> + +<!-- ======================================================================= --> +<h2 id="context">Accessing the SourceManager and ASTContext</h2> +<!-- ======================================================================= --> + +<p>Some of the information about the AST, like source locations and global +identifier information, are not stored in the AST nodes themselves, but in +the ASTContext and its associated source manager. To retrieve them we need to +hand the ASTContext into our RecursiveASTVisitor implementation.</p> +<p>The ASTContext is available from the CompilerInstance during the call +to CreateASTConsumer. We can thus extract it there and hand it into our +freshly created FindNamedClassConsumer:</p> +<pre> + virtual clang::ASTConsumer *CreateASTConsumer( + clang::CompilerInstance &Compiler, llvm::StringRef InFile) { + return new FindNamedClassConsumer(<b>&Compiler.getASTContext()</b>); + } +</pre> + +<p>Now that the ASTContext is available in the RecursiveASTVisitor, we can do +more interesting things with AST nodes, like looking up their source +locations:</p> +<pre> + bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) { + if (Declaration->getQualifiedNameAsString() == "n::m::C") { + // getFullLoc uses the ASTContext's SourceManager to resolve the source + // location and break it up into its line and column parts. + FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getLocStart()); + if (FullLocation.isValid()) + llvm::outs() << "Found declaration at " + << FullLocation.getSpellingLineNumber() << ":" + << FullLocation.getSpellingColumnNumber() << "\n"; + } + return true; + } +</pre> + +<!-- ======================================================================= --> +<h2 id="full">Putting it all together</h2> +<!-- ======================================================================= --> + +<p>Now we can combine all of the above into a small example program:</p> +<pre> + #include "clang/AST/ASTConsumer.h" + #include "clang/AST/RecursiveASTVisitor.h" + #include "clang/Frontend/CompilerInstance.h" + #include "clang/Frontend/FrontendAction.h" + #include "clang/Tooling/Tooling.h" + + using namespace clang; + + class FindNamedClassVisitor + : public RecursiveASTVisitor<FindNamedClassVisitor> { + public: + explicit FindNamedClassVisitor(ASTContext *Context) + : Context(Context) {} + + bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) { + if (Declaration->getQualifiedNameAsString() == "n::m::C") { + FullSourceLoc FullLocation = Context->getFullLoc(Declaration->getLocStart()); + if (FullLocation.isValid()) + llvm::outs() << "Found declaration at " + << FullLocation.getSpellingLineNumber() << ":" + << FullLocation.getSpellingColumnNumber() << "\n"; + } + return true; + } + + private: + ASTContext *Context; + }; + + class FindNamedClassConsumer : public clang::ASTConsumer { + public: + explicit FindNamedClassConsumer(ASTContext *Context) + : Visitor(Context) {} + + virtual void HandleTranslationUnit(clang::ASTContext &Context) { + Visitor.TraverseDecl(Context.getTranslationUnitDecl()); + } + private: + FindNamedClassVisitor Visitor; + }; + + class FindNamedClassAction : public clang::ASTFrontendAction { + public: + virtual clang::ASTConsumer *CreateASTConsumer( + clang::CompilerInstance &Compiler, llvm::StringRef InFile) { + return new FindNamedClassConsumer(&Compiler.getASTContext()); + } + }; + + int main(int argc, char **argv) { + if (argc > 1) { + clang::tooling::runToolOnCode(new FindNamedClassAction, argv[1]); + } + } +</pre> + +<p>We store this into a file called FindClassDecls.cpp and create the following +CMakeLists.txt to link it:</p> +<pre> +set(LLVM_USED_LIBS clangTooling) + +add_clang_executable(find-class-decls FindClassDecls.cpp) +</pre> + +<p>When running this tool over a small code snippet it will output all +declarations of a class n::m::C it found:</p> +<pre> + $ ./bin/find-class-decls "namespace n { namespace m { class C {}; } }" + Found declaration at 1:29 +</pre> + +</div> +</body> +</html> + diff --git a/docs/ReleaseNotes.html b/docs/ReleaseNotes.html index 8367b8a..2108909 100644 --- a/docs/ReleaseNotes.html +++ b/docs/ReleaseNotes.html @@ -2,7 +2,7 @@ "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> -<title>Clang 3.1 Release Notes</title> +<title>Clang 3.2 Release Notes</title> <link type="text/css" rel="stylesheet" href="../menu.css"> <link type="text/css" rel="stylesheet" href="../content.css"> <style type="text/css"> @@ -17,21 +17,25 @@ td { <div id="content"> -<h1>Clang 3.1 Release Notes</h1> +<h1>Clang 3.2 Release Notes</h1> <img style="float:right" src="http://llvm.org/img/DragonSmall.png" width="136" height="136" alt="LLVM Dragon Logo"> <ul> <li><a href="#intro">Introduction</a></li> - <li><a href="#whatsnew">What's New in Clang 3.1?</a> + <li><a href="#whatsnew">What's New in Clang 3.2?</a> <ul> + <li><a href="#majorfeatures">Major New Features</a></li> + <li><a href="#newflags">New Compiler Flags</a></li> <li><a href="#cchanges">C Language Changes</a></li> <li><a href="#cxxchanges">C++ Language Changes</a></li> <li><a href="#objcchanges">Objective-C Language Changes</a></li> + <li><a href="#apichanges">Internal API Changes</a></li> <li><a href="#pythonchanges">Python Binding Changes</a></li> </ul> </li> + <li><a href="#knownproblems">Known Problems</a></li> <li><a href="#additionalinfo">Additional Information</a></li> </ul> @@ -39,36 +43,166 @@ td { <p>Written by the <a href="http://llvm.org/">LLVM Team</a></p> </div> +<h1 style="color:red">These are in-progress notes for the upcoming Clang 3.2 +release.<br> +You may prefer the +<a href="http://llvm.org/releases/3.1/docs/ClangReleaseNotes.html">Clang 3.1 +Release Notes</a>.</h1> + <!-- ======================================================================= --> <h2 id="intro">Introduction</h2> <!-- ======================================================================= --> <p>This document contains the release notes for the Clang C/C++/Objective-C -frontend, part of the LLVM Compiler Infrastructure, release 3.1. Here we -describe the status of Clang in some detail, including major improvements from -the previous release and new feature work. For the general LLVM release notes, -see <a href="http://llvm.org/docs/ReleaseNotes.html">the LLVM - documentation</a>. All LLVM releases may be downloaded from the -<a href="http://llvm.org/releases/">LLVM releases web site</a>.</p> + frontend, part of the LLVM Compiler Infrastructure, release 3.2. Here we + describe the status of Clang in some detail, including major improvements + from the previous release and new feature work. For the general LLVM release + notes, see <a href="http://llvm.org/docs/ReleaseNotes.html">the LLVM + documentation</a>. All LLVM releases may be downloaded from the + <a href="http://llvm.org/releases/">LLVM releases web site</a>.</p> <p>For more information about Clang or LLVM, including information about the -latest release, please check out the main please see the -<a href="http://clang.llvm.org">Clang Web Site</a> or the -<a href="http://llvm.org">LLVM Web Site</a>. + latest release, please check out the main please see the + <a href="http://clang.llvm.org">Clang Web Site</a> or the + <a href="http://llvm.org">LLVM Web Site</a>. <p>Note that if you are reading this file from a Subversion checkout or the main -Clang web page, this document applies to the <i>next</i> release, not the -current one. To see the release notes for a specific release, please see the -<a href="http://llvm.org/releases/">releases page</a>.</p> + Clang web page, this document applies to the <i>next</i> release, not the + current one. To see the release notes for a specific release, please see the + <a href="http://llvm.org/releases/">releases page</a>.</p> <!-- ======================================================================= --> -<h2 id="whatsnew">What's New in Clang 3.1?</h2> +<h2 id="whatsnew">What's New in Clang 3.2?</h2> <!-- ======================================================================= --> <p>Some of the major new features and improvements to Clang are listed here. -Generic improvements to Clang as a whole or two its underlying infrastructure -are described first, followed by language-specific sections with improvements to -Clang's support for those languages.</p> + Generic improvements to Clang as a whole or to its underlying infrastructure + are described first, followed by language-specific sections with improvements + to Clang's support for those languages.</p> + +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> +<h3 id="majorfeatures">Major New Features</h3> +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> + +<h4 id="diagnostics">Improvements to Clang's diagnostics</h4> + +<p>Clang's diagnostics are constantly being improved to catch more issues, +explain them more clearly, and provide more accurate source information about +them. The improvements since the 3.1 release include:</p> + +<ul> + <li><tt>-Wuninitialized</tt> has been taught to recognise uninitialized uses + which always occur when an explicitly-written non-constant condition is either + <tt>true</tt> or <tt>false</tt>. For example: + +<pre> +int f(bool b) { + int n; + if (b) + n = 1; + return n; +} + +<b>sometimes-uninit.cpp:3:7: <span class="warning">warning:</span> variable 'n' is used uninitialized whenever 'if' condition is false [-Wsometimes-uninitialized]</b> + if (b) + <span class="caret">^</span> +<b>sometimes-uninit.cpp:5:10: <span class="note">note:</span></b> uninitialized use occurs here + return n; + <span class="caret">^</span> +<b>sometimes-uninit.cpp:3:3: <span class="note">note:</span></b> remove the 'if' if its condition is always true + if (b) + <span class="caret">^~~~~~</span> +<b>sometimes-uninit.cpp:2:8: <span class="note">note:</span></b> initialize the variable 'n' to silence this warning + int n; + <span class="caret">^</span> + <span class="caret"> = 0</span> +</pre> + + This functionality can be enabled or disabled separately from + <tt>-Wuninitialized</tt> with the <tt>-Wsometimes-uninitialized</tt> warning + flag.</li> + + <li>Template type diffing improves the display of diagnostics with templated + types in them. + +<pre> +int f(vector<map<int, double>>); +int x = f(vector<map<int, float>>()); +</pre> + The error message is the same, but the note is different based on the options selected. +<pre> +<b>template-diff.cpp:5:9: <span class="error">error:</span> no matching function for call to 'f'</b> +int x = f(vector<map<int, float>>()); + <span class="caret">^</span> +</pre> + Templated type diffing with type elision (default): +<pre> +<b>template-diff.cpp:4:5: <span class="note">note:</span></b> candidate function not viable: no known conversion from 'vector<map<[...], <span class="template-highlight">float</span>>>' to 'vector<map<[...], <span class="template-highlight">double</span>>>' for 1st argument; +int f(vector<map<int, double>>); + <span class="caret">^</span> +</pre> + Templated type diffing without type elision (-fno-elide-type): +<pre> +<b>template-diff.cpp:4:5: <span class="note">note:</span></b> candidate function not viable: no known conversion from 'vector<map<int, <span class="template-highlight">float</span>>>' to 'vector<map<int, <span class="template-highlight">double</span>>>' for 1st argument; +int f(vector<map<int, double>>); + <span class="caret">^</span> +</pre> + Templated tree printing with type elision (-fdiagnostics-show-template-tree): +<pre> +<b>template-diff.cpp:4:5: <span class="note">note:</span></b> candidate function not viable: no known conversion for 1st argument; + vector< + map< + [...], + [<span class="template-highlight">float</span> != <span class="template-highlight">double</span>]>> +int f(vector<map<int, double>>); + <span class="caret">^</span> +</pre> + Templated tree printing without type elision (-fdiagnostics-show-template-tree -fno-elide-type): +<pre> +<b>template-diff.cpp:4:5: <span class="note">note:</span></b> candidate function not viable: no known conversion for 1st argument; + vector< + map< + int, + [<span class="template-highlight">float</span> != <span class="template-highlight">double</span>]>> +int f(vector<map<int, double>>); + <span class="caret">^</span> +</pre> + + </li> + +</ul> + +<h4 id="tlsmodel">Support for <code>tls_model</code> attribute</h4> + +<p>Clang now supports the <code>tls_model</code> attribute, allowing code that +uses thread-local storage to explicitly select which model to use. The available +models are <code>"global-dynamic"</code>, <code>"local-dynamic"</code>, +<code>"initial-exec"</code> and <code>"local-exec"</code>. See +<a href="http://www.akkadia.org/drepper/tls.pdf">ELF Handling For Thread-Local + Storage</a> for more information.</p> + +<p>The compiler is free to choose a different model if the specified model is not +supported by the target, or if the compiler determines that a more specific +model can be used. +</p> + +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> +<h3 id="newflags">New Compiler Flags</h3> +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> +<ul> + <li><tt>-gline-tables-only</tt> controls the + <a href="http://clang.llvm.org/docs/UsersManual.html#debuginfosize">size of debug information</a>. + This flag tells Clang to emit debug info which is just enough to obtain stack traces with + function names, file names and line numbers (by such tools as gdb or addr2line). + Debug info for variables or function parameters is not produced, which reduces + the size of the resulting binary. + + <li><tt>-ftls-model</tt> controls which TLS model to use for thread-local + variables. This can be overridden per variable using the + <a href="#tlsmodel"><tt>tls_model</tt> attribute</a> mentioned above. + For more details, see the <a href="UsersManual.html#opt_ftls-model">User's + Manual</a>.</li> +</ul> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h3 id="cchanges">C Language Changes in Clang</h3> @@ -76,51 +210,33 @@ Clang's support for those languages.</p> <h4 id="c11changes">C11 Feature Support</h4> -<p>Clang 3.1 adds support for anonymous structs and anonymous unions, added in -the latest ISO C standard. Use <code>-std=c11</code> or <code>-std=gnu11</code> -to enable support for the new language standard. The new C11 features are -backwards-compatible and are available as an extension in all language -modes.</p> - -<p>All warning and language selection flags which previously accepted -<code>c1x</code> have been updated to accept <code>c11</code>. The old -<code>c1x</code> forms have been removed. +<p>...</p> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h3 id="cxxchanges">C++ Language Changes in Clang</h3> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h4 id="cxx11changes">C++11 Feature Support</h4> -<p>Clang 3.1 supports -<a href="http://clang.llvm.org/cxx_status.html#cxx11">most of the language -features</a> added in the latest ISO C++ standard, -<a href="http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372">C++ 2011</a>. -Use <code>-std=c++11</code> or <code>-std=gnu++11</code> to enable support for -these features. In addition to the features supported by Clang 3.0, the -following are now considered to be of production quality: -<ul> - <li>Generalized constant expressions</li> - <li>Lambda expressions</li> - <li>Generalized initializers</li> - <li>Unrestricted unions</li> - <li>User-defined literals</li> - <li>Forward-declared enumerations</li> - <li>Atomics (both libc++'s and libstdc++4.7's <tt><atomic></tt> are - supported)</li> -</ul> + +<p>...</p> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h3 id="objcchanges">Objective-C Language Changes in Clang</h3> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> -Clang 3.1 introduces several new Objective-C language features and improvements. -<h4 id="literals-subscripting">Objective-C literals and subscripting</h3> +<p>...</p> -<p>Objective-C now provides additional literal expressions, including numeric, array, and dictionary literals. Additionally, array and dictionary elements can be accesses via the subscripting operator. For more information about the new literals, see the <a href="ObjectiveCLiterals.html">documentation for Objective-C literals and subscripting</a>. +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> +<h3 id="apichanges">Internal API Changes</h3> +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> + +<p>These are major API changes that have happened since the 3.1 release of + Clang. If upgrading an external codebase that uses Clang as a library, this + section should help get you past the largest hurdles of upgrading.</p> -<h4 id="objcwformat">Format string checking for NSString literals</h4> +<h4 id="api1">API change 1</h4> -<code>-Wformat</code> now checks <code>@"NSString literals"</code>. +<p>...</p> <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h3 id="pythonchanges">Python Binding Changes</h3> @@ -128,49 +244,40 @@ Clang 3.1 introduces several new Objective-C language features and improvements. The following methods have been added: <ul> - <li>SourceLocation.from_position (static)</li> - <li>SourceLocation.__eq__ and SourceLocation.__ne__</li> - <li>SourceRange.__eq__ and SourceRange.__ne__</li> - <li>Diagnostic.category_number (property)</li> - <li>Diagnostic.category_name (property)</li> - <li>Diagnostic.option (property)</li> - <li>Diagnostic.disable_option (property)</li> - <li>CursorKind.is_translation_unit</li> - <li>CursorKind.is_preprocessing</li> - <li>CursorKind.is_unexposed</li> - <li>Cursor.from_location (static)</li> - <li>Cursor.underlying_typedef_type (property)</li> - <li>Cursor.enum_type (property)</li> - <li>Cursor.objc_type_encoding (property)</li> - <li>Cursor.hash</li> - <li>TypeKind.spelling</li> - <li>Type.argument_types</li> - <li>Type.element_type (property)</li> - <li>Type.element_count (property)</li> - <li>Type.is_function_variadic</li> - <li>Type.is_pod</li> - <li>Type.get_array_element_type</li> - <li>Type.get_array_size</li> - <li>Type.__eq__ and Type.__ne__</li> - <li>File.from_name (static)</li> - <li>File.__str__ and File.__repr__</li> + <li>...</li> </ul> <!-- ======================================================================= --> +<h2 id="knownproblems">Significant Known Problems</h2> +<!-- ======================================================================= --> + +<!-- ======================================================================= --> <h2 id="additionalinfo">Additional Information</h2> <!-- ======================================================================= --> <p>A wide variety of additional information is available on the -<a href="http://clang.llvm.org/">Clang web page</a>. The web page contains -versions of the API documentation which are up-to-date with the Subversion -version of the source code. You can access versions of these documents specific -to this release by going into the "<tt>clang/doc/</tt>" directory in the Clang -tree.</p> + <a href="http://clang.llvm.org/">Clang web page</a>. The web page contains + versions of the API documentation which are up-to-date with the Subversion + version of the source code. You can access versions of these documents + specific to this release by going into the "<tt>clang/doc/</tt>" directory in + the Clang tree.</p> <p>If you have any questions or comments about Clang, please feel free to -contact us via the <a href="http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev"> -mailing list</a>.</p> + contact us via + the <a href="http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev"> mailing + list</a>.</p> + +<!-- ======================================================================= --> +<!-- Likely 3.1 release notes --> +<!-- ======================================================================= --> +<!-- +This is just a section to hold things that have already gotten started and +should likely pick up proper release notes in 3.1. + +- C1X and C++11 atomics infrastructure and support +- CUDA support? +--> </div> </body> diff --git a/docs/ThreadSanitizer.html b/docs/ThreadSanitizer.html new file mode 100644 index 0000000..7a1d075 --- /dev/null +++ b/docs/ThreadSanitizer.html @@ -0,0 +1,125 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ --> +<html> +<head> + <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> + <title>ThreadSanitizer, a race detector</title> + <link type="text/css" rel="stylesheet" href="../menu.css"> + <link type="text/css" rel="stylesheet" href="../content.css"> + <style type="text/css"> + td { + vertical-align: top; + } + </style> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>ThreadSanitizer</h1> +<ul> + <li> <a href="#intro">Introduction</a> + <li> <a href="#howtobuild">How to Build</a> + <li> <a href="#platforms">Supported Platforms</a> + <li> <a href="#usage">Usage</a> + <li> <a href="#limitations">Limitations</a> + <li> <a href="#status">Current Status</a> + <li> <a href="#moreinfo">More Information</a> +</ul> + +<h2 id="intro">Introduction</h2> +ThreadSanitizer is a tool that detects data races. <BR> +It consists of a compiler instrumentation module and a run-time library. <BR> +Typical slowdown introduced by ThreadSanitizer is <b>5x-15x</b> (TODO: these numbers are +approximate so far). + +<h2 id="howtobuild">How to build</h2> +Follow the <a href="../get_started.html">clang build instructions</a>. <BR> +Note: CMake build does not work yet. +See <a href="http://llvm.org/bugs/show_bug.cgi?id=12272">bug 12272</a>. + +<h2 id="platforms">Supported Platforms</h2> +ThreadSanitizer is supported on Linux x86_64 (tested on Ubuntu 10.04). <BR> +Support for MacOS 10.7 (64-bit only) is planned for late 2012. <BR> +Support for 32-bit platforms is problematic and not yet planned. + + + +<h2 id="usage">Usage</h2> +Simply compile your program with <tt>-fthread-sanitizer -fPIE</tt> and link it +with <tt>-fthread-sanitizer -pie</tt>.<BR> +To get a reasonable performance add <tt>-O1</tt> or higher. <BR> +Use <tt>-g</tt> to get file names and line numbers in the warning messages. <BR> + +Example: +<pre> +% cat projects/compiler-rt/lib/tsan/output_tests/tiny_race.c +#include <pthread.h> +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; +} +</pre> + +<pre> +% clang -fthread-sanitizer -g -O1 tiny_race.c -fPIE -pie +</pre> + +If a bug is detected, the program will print an error message to stderr. +Currently, ThreadSanitizer symbolizes its output using an external +<tt>addr2line</tt> +process (this will be fixed in future). +<pre> +% TSAN_OPTIONS=strip_path_prefix=`pwd`/ # Don't print full paths. +% ./a.out 2> log +% cat log +WARNING: ThreadSanitizer: data race (pid=19219) + Write of size 4 at 0x7fcf47b21bc0 by thread 1: + #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 1 (running) created at: + #0 pthread_create ??:0 (exe+0x00000000c790) + #1 main tiny_race.c:9 (exe+0x00000000a3a4) +</pre> + + +<h2 id="limitations">Limitations</h2> +<ul> +<li> ThreadSanitizer uses more real memory than a native run. +At the default settings the memory overhead is 9x plus 9Mb per each thread. +Settings with 5x and 3x overhead (but less accurate analysis) are also available. +<li> ThreadSanitizer maps (but does not reserve) a lot of virtual address space. +This means that tools like <tt>ulimit</tt> may not work as usually expected. +<li> Static linking is not supported. +<li> ThreadSanitizer requires <tt>-fPIE -pie</tt> +</ul> + + +<h2 id="status">Current Status</h2> +ThreadSanitizer is in alpha stage. +It is known to work on large C++ programs using pthreads, but we do not promise +anything (yet). <BR> +C++11 threading is not yet supported. + +We are actively working on enhancing the tool -- stay tuned. +Any help, especially in the form of minimized standalone tests is more than welcome. + +<h2 id="moreinfo">More Information</h2> +<a href="http://code.google.com/p/thread-sanitizer/">http://code.google.com/p/thread-sanitizer</a>. + + +</div> +</body> +</html> diff --git a/docs/Tooling.html b/docs/Tooling.html new file mode 100644 index 0000000..74837f4 --- /dev/null +++ b/docs/Tooling.html @@ -0,0 +1,120 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<title>Writing Clang Tools</title> +<link type="text/css" rel="stylesheet" href="../menu.css"> +<link type="text/css" rel="stylesheet" href="../content.css"> +</head> +<body> + +<!--#include virtual="../menu.html.incl"--> + +<div id="content"> + +<h1>Writing Clang Tools</h1> +<p>Clang provides infrastructure to write tools that need syntactic and semantic +information about a program. This document will give a short introduction of the +different ways to write clang tools, and their pros and cons.</p> + +<!-- ======================================================================= --> +<h2 id="libclang"><a href="http://clang.llvm.org/doxygen/group__CINDEX.html">LibClang</a></h2> +<!-- ======================================================================= --> + +<p>LibClang is a stable high level C interface to clang. When in doubt LibClang +is probably the interface you want to use. Consider the other interfaces only +when you have a good reason not to use LibClang.</p> +<p>Canonical examples of when to use LibClang:</p> +<ul> + <li>Xcode</li> + <li>Clang Python Bindings</li> +</ul> +<p>Use LibClang when you...</p> +<ul> + <li>want to interface with clang from other languages than C++</li> + <li>need a stable interface that takes care to be backwards compatible</li> + <li>want powerful high-level abstractions, like iterating through an AST +with a cursor, and don't want to learn all the nitty gritty details of Clang's +AST.</li> +</ul> +<p>Do not use LibClang when you...</p> +<ul> + <li>want full control over the Clang AST</li> +</ul> + +<!-- ======================================================================= --> +<h2 id="clang-plugins"><a href="ClangPlugins.html">Clang Plugins</a></h2> +<!-- ======================================================================= --> + +<p>Clang Plugins allow you to run additional actions on the AST as part of +a compilation. Plugins are dynamic libraries that are loaded at runtime by +the compiler, and they're easy to integrate into your build environment.</p> +<p>Canonical examples of when to use Clang Plugins:</p> +<ul> + <li>special lint-style warnings or errors for your project</li> + <li>creating additional build artifacts from a single compile step</li> +</ul> +<p>Use Clang Plugins when you...</p> +<ul> + <li>need your tool to rerun if any of the dependencies change</li> + <li>want your tool to make or break a build</li> + <li>need full control over the Clang AST</li> +</ul> +<p>Do not use Clang Plugins when you...</p> +<ul> + <li>want to run tools outside of your build environment</li> + <li>want full control on how Clang is set up, including mapping of in-memory + virtual files</li> + <li>need to run over a specific subset of files in your project which is not + necessarily related to any changes which would trigger rebuilds</li> +</ul> + +<!-- ======================================================================= --> +<h2 id="libtooling"><a href="LibTooling.html">LibTooling</a></h2> +<!-- ======================================================================= --> + +<p>LibTooling is a C++ interface aimed at writing standalone tools, as well as +integrating into services that run clang tools.</p> +<p>Canonical examples of when to use LibTooling:</p> +<ul> + <li>a simple syntax checker</li> + <li>refactoring tools</li> +</ul> +<p>Use LibTooling when you...</p> +<ul> + <li>want to run tools over a single file, or a specific subset of files, + independently of the build system</li> + <li>want full control over the Clang AST</li> + <li>want to share code with Clang Plugins</li> +</ul> +<p>Do not use LibTooling when you...</p> +<ul> + <li>want to run as part of the build triggered by dependency changes</li> + <li>want a stable interface so you don't need to change your code when the + AST API changes</li> + <li>want high level abstractions like cursors and code completion out of the + box</li> + <li>do not want to write your tools in C++</li> +</ul> + +<!-- ======================================================================= --> +<h2 id="clang-tools"><a href="ClangTools.html">Clang Tools</a></h2> +<!-- ======================================================================= --> + +<p>These are a collection of specific developer tools built on top of the +LibTooling infrastructure as part of the Clang project. They are targeted at +automating and improving core development activities of C/C++ developers.</p> +<p>Examples of tools we are building or planning as part of the Clang +project:</p> +<ul> + <li>Syntax checking (clang-check)</li> + <li>Automatic fixing of compile errors (clangc-fixit)</li> + <li>Automatic code formatting</li> + <li>Migration tools for new features in new language standards</li> + <li>Core refactoring tools</li> +</ul> + +</div> +</body> +</html> + diff --git a/docs/UsersManual.html b/docs/UsersManual.html index b33ed61..69f916c 100644 --- a/docs/UsersManual.html +++ b/docs/UsersManual.html @@ -43,12 +43,14 @@ td { <li><a href="#diagnostics_categories">Diagnostic Categories</a></li> <li><a href="#diagnostics_commandline">Controlling Diagnostics via Command Line Flags</a></li> <li><a href="#diagnostics_pragmas">Controlling Diagnostics via Pragmas</a></li> + <li><a href="#diagnostics_systemheader">Controlling Diagnostics in System Headers</a></li> <li><a href="#diagnostics_enable_everything">Enabling All Warnings</a></li> <li><a href="#analyzer_diagnositics">Controlling Static Analyzer Diagnostics</a></li> </ul> </li> <li><a href="#precompiledheaders">Precompiled Headers</a></li> <li><a href="#codegen">Controlling Code Generation</a></li> + <li><a href="#debuginfosize">Controlling Size of Debug Information</a></li> </ul> </li> <li><a href="#c">C Language Features</a> @@ -185,9 +187,10 @@ introduces the language selection and other high level options like -c, -g, etc. <p><b>-Werror=foo</b>: Turn warning "foo" into an error.</p> <p><b>-Wno-error=foo</b>: Turn warning "foo" into an warning even if -Werror is specified.</p> -<p><b>-Wfoo</b>: Enable warning foo</p> -<p><b>-Wno-foo</b>: Disable warning foo</p> +<p><b>-Wfoo</b>: Enable warning "foo".</p> +<p><b>-Wno-foo</b>: Disable warning "foo".</p> <p><b>-w</b>: Disable all warnings.</p> +<p><b>-Weverything</b>: <a href="#diagnostics_enable_everything">Enable <b>all</b> warnings.</a></p> <p><b>-pedantic</b>: Warn on language extensions.</p> <p><b>-pedantic-errors</b>: Error on language extensions.</p> <p><b>-Wsystem-headers</b>: Enable warnings from system headers.</p> @@ -227,6 +230,9 @@ print something like: <p>When this is disabled, Clang will print "test.c:28: warning..." with no column number.</p> + +<p>The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.</p> </dd> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> @@ -393,6 +399,9 @@ exprs.c:47:15:{47:8-47:14}{47:17-47:24}: error: invalid operands to binary expre </pre> <p>The {}'s are generated by -fdiagnostics-print-source-range-info.</p> + +<p>The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.</p> </dd> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> @@ -413,6 +422,51 @@ respectively). Both the file name and the insertion string escape backslash (as "\\"), tabs (as "\t"), newlines (as "\n"), double quotes(as "\"") and non-printable characters (as octal "\xxx").</p> + +<p>The printed column numbers count bytes from the beginning of the line; take +care if your source contains multibyte characters.</p> +</dd> + +<dt id="opt_fno-elide-type"> +<b>-fno-elide-type</b>: +Turns off elision in template type printing.</dt> +<dd><p>The default for template type printing is to elide as many template +arguments as possible, removing those which are the same in both template types, +leaving only the differences. Adding this flag will print all the template +arguments. If supported by the terminal, highlighting will still appear on +differing arguments.</p> + +Default: +<pre> +t.cc:4:5: <span class="note">note</span>: candidate function not viable: no known conversion from 'vector<map<[...], map<<span class="template-highlight">float</span>, [...]>>>' to 'vector<map<[...], map<<span class="template-highlight">double</span>, [...]>>>' for 1st argument; +</pre> +-fno-elide-type: +<pre> +t.cc:4:5: <span class="note">note</span>: candidate function not viable: no known conversion from 'vector<map<int, map<<span class="template-highlight">float</span>, int>>>' to 'vector<map<int, map<<span class="template-highlight">double</span>, int>>>' for 1st argument; +</pre> +</dd> + +<dt id="opt_fdiagnostics-show-template-tree"> +<b>-fdiagnostics-show-template-tree</b>: +Template type diffing prints a text tree.</dt> +<dd><p>For diffing large templated types, this option will cause Clang to +display the templates as an indented text tree, one argument per line, with +differences marked inline. This is compatible with -fno-elide-type.</p> + +Default: +<pre> +t.cc:4:5: <span class="note">note</span>: candidate function not viable: no known conversion from 'vector<map<[...], map<<span class="template-highlight">float</span>, [...]>>>' to 'vector<map<[...], map<<span class="template-highlight">double</span>, [...]>>>' for 1st argument; +</pre> +-fdiagnostics-show-template-tree +<pre> +t.cc:4:5: <span class="note">note</span>: candidate function not viable: no known conversion for 1st argument; + vector< + map< + [...], + map< + [<span class="template-highlight">float</span> != <span class="template-highlight">float</span>], + [...]>>> +</pre> </dd> </dl> @@ -443,9 +497,6 @@ the end of preprocessor directives. For example: <p>These extra tokens are not strictly conforming, and are usually best handled by commenting them out.</p> - -<p>This option is also enabled by <a href="">-Wfoo</a>, <a href="">-Wbar</a>, - and <a href="">-Wbaz</a>.</p> </dd> <!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> @@ -609,7 +660,7 @@ mapping of category names to category id's can be obtained by running '<tt>clang <h4 id="diagnostics_commandline">Controlling Diagnostics via Command Line Flags</h4> -<p>-W flags, -pedantic, etc</p> +<p>TODO: -W flags, -pedantic, etc</p> <h4 id="diagnostics_pragmas">Controlling Diagnostics via Pragmas</h4> @@ -653,6 +704,45 @@ GCC do not support the exact same set of warnings, so even when using GCC compatible #pragmas there is no guarantee that they will have identical behaviour on both compilers. </p> +<h4 id="diagnostics_systemheader">Controlling Diagnostics in System Headers</h4> + +<p>Warnings are suppressed when they occur in system headers. By default, an +included file is treated as a system header if it is found in an include path +specified by <tt>-isystem</tt>, but this can be overridden in several ways.</p> + +<p>The <tt>system_header</tt> pragma can be used to mark the current file as +being a system header. No warnings will be produced from the location of the +pragma onwards within the same file.</p> + +<pre> +char a = 'xy'; // warning + +#pragma clang system_header + +char b = 'ab'; // no warning +</pre> + +<p>The <tt>-isystem-prefix</tt> and <tt>-ino-system-prefix</tt> command-line +arguments can be used to override whether subsets of an include path are treated +as system headers. When the name in a <tt>#include</tt> directive is found +within a header search path and starts with a system prefix, the header is +treated as a system header. The last prefix on the command-line which matches +the specified header name takes precedence. For instance:</p> + +<pre> +clang -Ifoo -isystem bar -isystem-prefix x/ -ino-system-prefix x/y/ +</pre> + +<p>Here, <tt>#include "x/a.h"</tt> is treated as including a system header, even +if the header is found in <tt>foo</tt>, and <tt>#include "x/y/b.h"</tt> is +treated as not including a system header, even if the header is found in +<tt>bar</tt>. +</p> + +<p>A <tt>#include</tt> directive which finds a file relative to the current +directory is treated as including a system header if the including file is +treated as a system header.</p> + <h4 id="diagnostics_enable_everything">Enabling All Warnings</h4> <p>In addition to the traditional <tt>-W</tt> flags, one can enable <b>all</b> @@ -667,37 +757,11 @@ on both compilers. </p> <p>While not strictly part of the compiler, the diagnostics from Clang's <a href="http://clang-analyzer.llvm.org">static analyzer</a> can also be influenced -by the user via changes to the source code. This can be done in two ways: - -<ul> - -<li id="analyzer_annotations"><b>Annotations</b>: The static analyzer recognizes various GCC-style -attributes (e.g., <tt>__attribute__((nonnull)))</tt>) that can either suppress -static analyzer warnings or teach the analyzer about code invariants which -enable it to find more bugs. While many of these attributes are standard GCC -attributes, additional ones have been added to Clang to specifically support the -static analyzer. Detailed information on these annotations can be found in the -<a href="http://clang-analyzer.llvm.org/annotations.html">analyzer's -documentation</a>.</li> - -<li><b><tt>__clang_analyzer__</tt></b>: When the static analyzer is using Clang -to parse source files, it implicitly defines the preprocessor macro -<tt>__clang_analyzer__</tt>. While discouraged, code can use this macro to -selectively exclude code the analyzer examines. Here is an example: - -<pre> -#ifndef __clang_analyzer__ -// Code not to be analyzed -#endif -</pre> - -In general, this usage is discouraged. Instead, we prefer that users file bugs -against the analyzer when it flags false positives. There is also active -discussion of allowing users in the future to selectively silence specific -analyzer warnings (some of which can already be done using <a -href="#analyzer_annotations">annotations</a>).</li> - -</ul> +by the user via changes to the source code. See the available +<a href = "http://clang-analyzer.llvm.org/annotations.html" >annotations</a> and +the analyzer's +<a href= "http://clang-analyzer.llvm.org/faq.html#exclude_code" >FAQ page</a> for +more information. <!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> <h3 id="precompiledheaders">Precompiled Headers</h3> @@ -855,6 +919,39 @@ generator will always lower the builtin to a call to the specified function regardless of whether the target ISA has a trap instruction. This option is useful for environments (e.g. deeply embedded) where a trap cannot be properly handled, or when some custom behavior is desired.</dd> + +<dt id="opt_ftls-model"><b>-ftls-model=[model]</b>: Select which TLS model to +use.</dt> +<dd>Valid values are: <tt>global-dynamic</tt>, <tt>local-dynamic</tt>, +<tt>initial-exec</tt> and <tt>local-exec</tt>. The default value is +<tt>global-dynamic</tt>. The compiler may use a different model if the selected +model is not supported by the target, or if a more efficient model can be used. +The TLS model can be overridden per variable using the <tt>tls_model</tt> +attribute. +</dd> +</dl> + +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> +<h3 id="debuginfosize">Controlling Size of Debug Information</h3> +<!-- = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = --> + +<p>Debug info kind generated by Clang can be set by one of the flags listed +below. If multiple flags are present, the last one is used.</p> + +<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> +<dl> +<dt id="opt_g0"><b>-g0</b>: Don't generate any debug info (default). + +<dt id="opt_gline-tables-only"><b>-gline-tables-only</b>: +Generate line number tables only. +<dd> +This kind of debug info allows to obtain stack traces with function +names, file names and line numbers (by such tools as +gdb or addr2line). It doesn't contain any other data (e.g. +description of local variables or function parameters). +</dd> + +<dt id="opt_g"><b>-g</b>: Generate complete debug info. </dl> <!-- ======================================================================= --> @@ -937,9 +1034,18 @@ interest in these features yet, so it's hard to say when they will be implemented.</li> <li>clang does not support nested functions; this is a complex feature which -is infrequently used, so it is unlikely to be implemented anytime soon.</li> +is infrequently used, so it is unlikely to be implemented anytime soon. In C++11 +it can be emulated by assigning lambda functions to local variables, e.g: +<pre> + auto const local_function = [&](int parameter) { + // Do something + }; + ... + local_function(1); +</pre> +</li> -<li>clang does not support global register variables, this is unlikely +<li>clang does not support global register variables; this is unlikely to be implemented soon because it requires additional LLVM backend support. </li> @@ -955,7 +1061,7 @@ in 4.3, the glibc headers will not try to use this extension with clang at the moment.</li> <li>clang does not support the gcc extension for forward-declaring function -parameters; this has not showed up in any real-world code yet, though, so it +parameters; this has not shown up in any real-world code yet, though, so it might never be implemented.</li> </ul> @@ -1001,6 +1107,14 @@ support is incomplete; enabling Microsoft extensions will silently drop certain constructs (including __declspec and Microsoft-style asm statements). </p> +<p>clang has a -fms-compatibility flag that makes clang accept enough +invalid C++ to be able to parse most Microsoft headers. This flag is enabled by +default for Windows targets.</p> + +<p>-fdelayed-template-parsing lets clang delay all template instantiation until +the end of a translation unit. This flag is enabled by default for Windows +targets.</p> + <ul> <li>clang allows setting _MSC_VER with -fmsc-version=. It defaults to 1300 which is the same as Visual C/C++ 2003. Any number is supported and can greatly affect @@ -1015,6 +1129,8 @@ record members can be declared using user defined typedefs.</li> controlling record layout. GCC also contains support for this feature, however where MSVC and GCC are incompatible clang follows the MSVC definition.</li> + +<li>clang defaults to C++11 for Windows targets.</li> </ul> <!-- ======================================================================= --> @@ -1092,7 +1208,7 @@ Generating assembly requires a suitable LLVM backend. <h4 id="target_os_darwin">Darwin (Mac OS/X)</h4> <!-- ======================================= --> -<p>No __thread support, 64-bit ObjC support requires SL tools.</p> +<p>None</p> <!-- ======================================= --> <h4 id="target_os_win32">Windows</h4> @@ -1100,6 +1216,8 @@ Generating assembly requires a suitable LLVM backend. <p>Experimental supports are on Cygming.</p> +<p>See also <a href="#c_ms">Microsoft Extensions</a>.</p> + <h5>Cygwin</h5> <p>Clang works on Cygwin-1.7.</p> @@ -1135,7 +1253,7 @@ Clang assumes directories as below;</p> <li><tt>some_directory/bin/../include</tt></li> </ul> -<p>This directory layout is standard for any toolchain you will find on the official <a href="mingw-w64.sourceforge.net">MinGW-w64 website</a>. +<p>This directory layout is standard for any toolchain you will find on the official <a href="http://mingw-w64.sourceforge.net">MinGW-w64 website</a>. <p>Clang expects the GCC executable "gcc.exe" compiled for i686-w64-mingw32 (or x86_64-w64-mingw32) to be present on PATH.</p> diff --git a/docs/tools/clang.pod b/docs/tools/clang.pod index 8f61568..425a91e 100644 --- a/docs/tools/clang.pod +++ b/docs/tools/clang.pod @@ -303,6 +303,14 @@ This flag sets the default visibility level. This flag specifies that variables without initializers get common linkage. It can be disabled with B<-fno-common>. +=item B<-ftls-model> + +Set the default thread-local storage (TLS) model to use for thread-local +variables. Valid values are: "global-dynamic", "local-dynamic", "initial-exec" +and "local-exec". The default is "global-dynamic". The default model can be +overridden with the tls_model attribute. The compiler will try to choose a more +efficient model if possible. + =item B<-flto> B<-emit-llvm> Generate output files in LLVM formats, suitable for link time optimization. When |