Commit Graph

4565 Commits

Author SHA1 Message Date
Björn Schäpers c5243c63cd [clang-format] Fix aligning with linebreaks
Breaking a string literal or a function calls arguments with
AlignConsecutiveDeclarations or AlignConsecutiveAssignments did misalign
the continued line. E.g.:

void foo() {
  int myVar = 5;
  double x  = 3.14;
  auto str  = "Hello"
            "World";
}

or

void foo() {
  int    myVar = 5;
  double x = 3.14;
  auto   str = "Hello"
             "World";
}

Differential Revision: https://reviews.llvm.org/D98214
2021-03-28 16:26:27 +02:00
Utkarsh Saxena aa979084df [clang][Syntax] Optimize expandedTokens for token ranges.
`expandedTokens(SourceRange)` used to do a binary search to get the
expanded tokens belonging to a source range. Each binary search uses
`isBeforeInTranslationUnit` to order two source locations. This is
inherently very slow.
By profiling clangd we found out that users like clangd::SelectionTree
spend 95% of time in `isBeforeInTranslationUnit`. Also it is worth
noting that users of `expandedTokens(SourceRange)` majorly use ranges
provided by AST to query this funciton. The ranges provided by AST are
token ranges (starting at the beginning of a token and ending at the
beginning of another token).

Therefore we can avoid the binary search in majority of the cases by
maintaining an index of ExpandedToken by their SourceLocations. We still
do binary search for ranges which are not token ranges but such
instances are quite low.

Performance:
`~/build/bin/clangd --check=clang/lib/Serialization/ASTReader.cpp`
Before: Took 2:10s to complete.
Now: Took 1:13s to complete.

Differential Revision: https://reviews.llvm.org/D99086
2021-03-25 18:54:15 +01:00
Krasimir Georgiev d9abcdd9f4 [clang-format] Fix ObjC method indent after f7f9f94b
Commit
f7f9f94b2e
changed the indent of ObjC method arguments from +4 to +2, if the method
occurs after a block statement.  I believe this was unintentional and there
was insufficient ObjC test coverage to catch this.

Example: `clang-format -style=google test.mm`

before:
```
void aaaaaaaaaaaaaaaaaaaaa(int c) {
  if (c) {
    f();
  }
  [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd
      eeeeeeeeeeeeeeeeeeeeeeeeeeeee:^(fffffffffffffff gggggggg) {
        f(SSSSS, c);
      }];
}
```

after:
```
void aaaaaaaaaaaaaaaaaaaaa(int c) {
  if (c) {
    f();
  }
  [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd
    eeeeeeeeeeeeeeeeeeeeeeeeeeeee:^(fffffffffffffff gggggggg) {
      f(SSSSS, c);
    }];
}
```

Differential Revision: https://reviews.llvm.org/D99063
2021-03-25 10:52:08 +01:00
Janusz Nykiel e030ce3ec7 [Tooling] Handle compilation databases containing commands with double dashes
As of CMake commit https://gitlab.kitware.com/cmake/cmake/-/commit/d993ebd4,
which first appeared in CMake 3.19.x series, in the compile commands for
clang-cl, CMake puts `--` before the input file. When operating on such a
database, the `InterpolatingCompilationDatabase` - specifically, the
`TransferableCommand` constructor - does not recognize that pattern and so, does
not strip the input, or the double dash when 'transferring' the compile command.
This results in a incorrect compile command - with the double dash and old input
file left in, and the language options and new input file appended after them,
where they're all treated as inputs, including the language version option.

Test files for some tests have names similar enough to be matched to commands
from the database, e.g.:

`.../path-mappings.test.tmp/server/bar.cpp`

can be matched to:

`.../Driver/ToolChains/BareMetal.cpp`

etc. When that happens, the tool being tested tries to use the matched, and
incorrectly 'transferred' compile command, and fails, reporting errors similar
to:

`error: no such file or directory: '/std:c++14'; did you mean '/std:c++14'? [clang-diagnostic-error]`

This happens in at least 4 tests:

  Clang Tools :: clang-tidy/checkers/performance-trivially-destructible.cpp
  Clangd :: check-fail.test
  Clangd :: check.test
  Clangd :: path-mappings.test

The fix for `TransferableCommand` removes the `--` and everything after it when
determining the arguments that apply to the new file. `--` is inserted in the
'transferred' command if the new file name starts with `-` and when operating in
clang-cl mode, also `/`. Additionally, other places in the code known to do
argument adjustment without accounting for the `--` and causing the tests to
fail are fixed as well.

Differential Revision: https://reviews.llvm.org/D98824
2021-03-24 16:01:47 -04:00
Balázs Kéri f6cdb2c0a7 [clang][ASTImporter] Add import of DeducedTemplateSpecializationType.
Reviewed By: shafik

Differential Revision: https://reviews.llvm.org/D99188
2021-03-24 09:43:58 +01:00
Raphael Isemann 274907c0a4 [ASTImporter] Split out Objective-C related unit tests
This moves the two tests we have for importing Objective-C nodes to their own
file. The motivation is that this means I can add more Objective-C tests without
making the compilation time of ASTImporterTest even longer. Also it seems nice
to separate the Apple-specific stuff from the ASTImporter test.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D99162
2021-03-23 13:58:45 +01:00
Balázs Kéri 3cde27bc56 [clang][ASTImporter] Import "CapturedVLAType" in FieldDecl.
Update ASTImporter to import value of FieldDecl::getCapturedVLAType.

Reviewed By: shafik, martong

Differential Revision: https://reviews.llvm.org/D99062
2021-03-23 09:54:25 +01:00
Stephen Kelly 4c65dfc895 [AST] Add introspection support for Decls
The test code has lots of interesting locations which are not yet
introspected, but those will come later:

 http://ce.steveire.com/z/3T90hR

Differential Revision: https://reviews.llvm.org/D98775
2021-03-22 23:16:02 +00:00
Raphael Isemann e421a74108 [ASTImporter] Fix import of ObjCPropertyDecl that share the same name
Objective-C apparently allows name conflicts between instance and class
properties, so this is valid code:

```
@protocol DupProp
@property (class, readonly) int prop;
@property (readonly) int prop;
@end
```

The ASTImporter however isn't aware of this and will consider the two properties
as if they are the same property because it just compares their name and types.
This causes that when importing both properties we only end up with one property
(whatever is imported first from what I can see).

Beside generating a different AST this also leads to a bunch of asserts and
crashes as we still correctly import the two different getters for both
properties (the import code for methods does the correct check where it
differentiated between instance and class methods). As one of the setters will
not have its associated ObjCPropertyDecl imported, any call to
`ObjCMethodDecl::findPropertyDecl` will just lead to an assert or crash.

Fixes rdar://74322659

Reviewed By: shafik, kastiglione

Differential Revision: https://reviews.llvm.org/D99077
2021-03-22 18:05:50 +01:00
Dmitri Gribenko 9cd7c41306 [analyzer] Don't include private gtest headers 2021-03-22 13:31:38 +01:00
Valeriy Savchenko 02b51e5316 [analyzer][solver] Redesign constraint ranges data structure
ImmutableSet doesn't seem like the perfect fit for the RangeSet
data structure.  It is good for saving memory in a persistent
setting, but not for the case when the population of the container
is tiny.  This commit replaces RangeSet implementation and
redesigns the most common operations to be more efficient.

Differential Revision: https://reviews.llvm.org/D86465
2021-03-22 13:52:35 +03:00
Chuanqi Xu 55486161fa [ASTMatcher] Add AST Matcher support for C++20 coroutine keywords
Summary: Try to enable the support for C++20 coroutine keywords for AST
Matchers.

Reviewers: sammccall, njames93, aaron.ballman

Differential Revision: https://reviews.llvm.org/D96316
2021-03-22 10:27:46 +08:00
joker881 b98ad2ac08 Title: Remove a redundant parameter in clang/unittests/AST/CMakeLists.txt Reviewed by: MaskRay Differential Revision: https://reviews.llvm.org/D98922 2021-03-20 14:39:05 +08:00
Fangrui Song 28d58d8fe2 [Driver] Stop searching other prefixes once a GCC installation is found in one prefix
so that when --sysroot is specified, the detected GCC installation will not be
overridden by another from /usr which happens to have a larger version.

This behavior is particularly inconvenient when the system has a larger version
GCC while the user wants to try out an older sysroot.

Delete some tests from linux-ld.c which overlap with cross-linux.c
2021-03-19 20:35:59 -07:00
Balázs Kéri 96e675bdd5 [clang][ASTImporter] Add import support for SourceLocExpr.
It is possible that imported `SourceLocExpr` can cause not expected behavior (if `__builtin_LINE()` is used together with `__LINE__` for example) but still it may be worth to import these because some projects use it.

Reviewed By: teemperor

Differential Revision: https://reviews.llvm.org/D98876
2021-03-19 16:33:04 +01:00
Balazs Benics c1fb23c1aa [clang][ASTImporter] Fix import of VarDecl regarding thread local storage spec
After the import, we did not copy the `TSCSpec`.
This commit resolves that.

Reviewed By: balazske

Differential Revision: https://reviews.llvm.org/D98707
2021-03-18 13:06:38 +01:00
Aaron Ballman c165a99a1b [SYCL] Rework the SYCL driver options
SYCL compilations initiated by the driver will spawn off one or more
frontend compilation jobs (one for device and one for host). This patch
reworks the driver options to make upstreaming this from the downstream
SYCL fork easier.

This patch introduces a language option to identify host executions
(SYCLIsHost) and a -cc1 frontend option to enable this mode. -fsycl and
-fno-sycl become driver-only options that are rejected when passed to
-cc1. This is because the frontend and beyond should be looking at
whether the user is doing a device or host compilation specifically.
Because the frontend should only ever be in one mode or the other,
-fsycl-is-device and -fsycl-is-host are mutually exclusive options.
2021-03-17 08:27:19 -04:00
Stephen Kelly b90e7bf25d NFC: Use a simple macro to test AST node introspection 2021-03-17 12:08:55 +00:00
Vassil Vassilev 0cb7e7ca0c Make iteration over the DeclContext::lookup_result safe.
The idiom:
```
DeclContext::lookup_result R = DeclContext::lookup(Name);
for (auto *D : R) {...}
```

is not safe when in the loop body we trigger deserialization from an AST file.
The deserialization can insert new declarations in the StoredDeclsList whose
underlying type is a vector. When the vector decides to reallocate its storage
the pointer we hold becomes invalid.

This patch replaces a SmallVector with an singly-linked list. The current
approach stores a SmallVector<NamedDecl*, 4> which is around 8 pointers.
The linked list is 3, 5, or 7. We do better in terms of memory usage for small
cases (and worse in terms of locality -- the linked list entries won't be near
each other, but will be near their corresponding declarations, and we were going
to fetch those memory pages anyway). For larger cases: the vector uses a
doubling strategy for reallocation, so will generally be between half-full and
full. Let's say it's 75% full on average, so there's N * 4/3 + 4 pointers' worth
of space allocated currently and will be 2N pointers with the linked list. So we
break even when there are N=6 entries and slightly lose in terms of memory usage
after that. We suspect that's still a win on average.

Thanks to @rsmith!

Differential revision: https://reviews.llvm.org/D91524
2021-03-17 08:59:04 +00:00
Stephen Kelly 19740652c4 [AST] Add generator for source location introspection
Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

Differential Revision: https://reviews.llvm.org/D93164
2021-03-15 10:52:44 +00:00
Stephen Kelly 6e303a982d Revert "[AST] Add generator for source location introspection"
This reverts commit 91abaa1f8d.
2021-03-15 01:16:10 +00:00
Stephen Kelly 91abaa1f8d [AST] Add generator for source location introspection
Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

Differential Revision: https://reviews.llvm.org/D93164
2021-03-15 00:00:29 +00:00
Stephen Kelly e312b4b6c7 Revert "[AST] Add generator for source location introspection"
This reverts commit 477e4b9746.
2021-03-14 22:51:45 +00:00
Stephen Kelly 477e4b9746 [AST] Add generator for source location introspection
Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

The JSON file can also be used to generate bindings for other languages,
such as Python and Javascript:

  https://steveire.wordpress.com/2019/04/30/the-future-of-ast-matching

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Also in this version, the platforms/cmake configurations are excluded as
much as possible so that support can be added iteratively.  Currently a
break on any platform causes a revert of the entire feature.  This way,
the `OR WIN32` can be removed in a future commit and if it breaks the
buildbots, only that commit gets reverted, making the entire process
easier to manage.

Differential Revision: https://reviews.llvm.org/D93164
2021-03-14 22:32:42 +00:00
Nikita Popov e0f70a8a97 Revert "[AST] Add generator for source location introspection"
Breaks the build ... somehow: https://llvm-compile-time-tracker.com/show_error.php?commit=77f7d2be214a1de29d583c75739f563593991fc3

FAILED: tools/clang/include/clang/Tooling/NodeIntrospection.inc
cd /root/llvm-compile-time-tracker/llvm-project-build/tools/clang/lib/Tooling && /usr/bin/cmake -E make_directory /root/llvm-compile-time-tracker/llvm-project-build/tools/clang/lib/Tooling/generated/ && /root/llvm-compile-time-tracker/llvm-project/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py --json-input-path /root/llvm-compile-time-tracker/llvm-project-build/ASTNodeAPI.json --output-file generated/NodeIntrospection.inc --empty-implementation 0 && /usr/bin/cmake -E copy_if_different /root/llvm-compile-time-tracker/llvm-project-build/tools/clang/lib/Tooling/generated/NodeIntrospection.inc /root/llvm-compile-time-tracker/llvm-project-build/tools/clang/include/clang/Tooling/NodeIntrospection.inc
/bin/sh: 1: /root/llvm-compile-time-tracker/llvm-project/clang/lib/Tooling/DumpTool/generate_cxx_src_locs.py: not found

This reverts commit cefe711135.
This reverts commit f72f122fee.
This reverts commit 970c21e345.
This reverts commit 77f7d2be21.
2021-03-14 17:05:08 +01:00
Stephen Kelly 970c21e345 Remove unneeded targets dependency 2021-03-14 15:37:30 +00:00
Stephen Kelly 77f7d2be21 [AST] Add generator for source location introspection
Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Differential Revision: https://reviews.llvm.org/D93164
2021-03-14 10:54:33 +00:00
Kadir Cetinkaya f43ff34ae6
[clang] Mark re-injected tokens appropriately during pragma handling
This hides such tokens from TokenWatcher, preventing crashes in clients
trying to match spelled and expanded tokens.

Fixes https://github.com/clangd/clangd/issues/712

Differential Revision: https://reviews.llvm.org/D98483
2021-03-12 18:18:17 +01:00
Stephen Kelly 14050ddc40 Revert "[AST] Add generator for source location introspection"
This reverts commit d627a27d26.

This fails to link on Windows somehow.
2021-03-10 23:36:06 +00:00
Stephen Kelly d627a27d26 [AST] Add generator for source location introspection
Generate a json file containing descriptions of AST classes and their
public accessors which return SourceLocation or SourceRange.

Use the JSON file to generate a C++ API and implementation for accessing
the source locations and method names for accessing them for a given AST
node.

This new API can be used to implement 'srcloc' output in clang-query:

  http://ce.steveire.com/z/m_kTIo

In this first version of this feature, only the accessors for Stmt
classes are generated, not Decls, TypeLocs etc.  Those can be added
after this change is reviewed, as this change is mostly about
infrastructure of these code generators.

Differential Revision: https://reviews.llvm.org/D93164
2021-03-10 22:38:39 +00:00
Krasimir Georgiev 587859d977 clang-format: use `pb` as a canonical raw string delimiter for google style
This updates the canonical text proto raw string delimiter to `pb` for Google style, moving codebases towards a simpler and more consistent style.

Also updates a behavior where the canonical delimiter was not applied for raw strings with empty delimiters detected via well-known enclosing functions that expect a text proto, effectively making the canonical delimiter more viral. This feature is not widely used so this should be safe and more in line with promoting the canonicity of the canonical delimiter.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D97688
2021-03-09 09:07:14 +01:00
Shoaib Meenai 9a2a167b6c [DirectoryWatcher] Increase timeout to make test less flaky
We've observed this test being significantly flaky on our Mac CI
machines when we're running the full check-clang suite. It fails because
the wait_for condition isn't met within 3 seconds. We believe it's
because our CI machines are somewhat underpowered and pretty heavily
loaded when we're running the full check-clang suite.

I ran some experiments on increasing the timeout. I ran the full
check-clang suite 100 times with each timeout value and recorded how
many flaky failures we encountered in these tests. The results are:

3 second timeout (baseline): 20 failures
10 second timeout: 14 failures
20 second timeout: 4 failures
30 second timeout: 2 failures
40 second timeout: 1 failure
50 second timeout: 0 failures
60 second timeout: 0 failures

I ran another set of 100 tests for the 50 second timeout and observed
one flaky failure. By contrast, I ended up running check-clang 500 times
for the 60 second timeout and didn't observe a single flaky failure.
That's how the 60 second timeout value used in this patch was derived.

While a 60 second timeout might seem high, keep in mind that:
- This is a timeout, not a sleep; the test should require much less time
  the vast majority of instances, especially on more powerful machines.
- The long timeout is most likely to occur when other tests are also
  running at the same time, so the latency of the timeout will also be
  masked by the latency of the other tests.

See https://reviews.llvm.org/D58418?id=200123#inline-554211 for where
this timeout was originally introduced and the possibility of raising it
if it wasn't enough was discussed.

Reviewed By: plotfi

Differential Revision: https://reviews.llvm.org/D97878
2021-03-05 17:49:14 -08:00
Tim Wojtulewicz f7f9f94b2e [clang-format] Rework Whitesmiths mode to use line-level values in UnwrappedLineParser
This commit removes the old way of handling Whitesmiths mode in favor of just setting the
levels during parsing and letting the formatter handle it from there. It requires a bit of
special-casing during the parsing, but ends up a bit cleaner than before. It also removes
some of switch/case unit tests that don't really make much sense when dealing with
Whitesmiths.

Differential Revision: https://reviews.llvm.org/D94500
2021-03-05 21:42:46 +01:00
Björn Schäpers 7b02794f0a [clang-format] Rename case sorting
As discussed in D95017 the names case sensitive and insensitive should
be switched.

This amends a8105b3766.

Differential Revision: https://reviews.llvm.org/D97927
2021-03-05 21:42:45 +01:00
Jan Svoboda 4295ae96cd [clang][modules] Use extensible RTTI for ModuleFileExtension
Clang exposes an interface for extending the PCM/PCH file format: `ModuleFileExtension`.

Clang itself has only a single implementation of the interface: `TestModuleFileExtension` that can be instantiated via the `-ftest-module-file_extension=` command line argument (and is stored in `FrontendOptions::ModuleFileExtensions`).

Clients of the Clang library can extend the PCM/PCH file format by pushing an instance of their extension class to the `FrontendOptions::ModuleFileExtensions` vector.

When generating the `-ftest-module-file_extension=` command line argument from `FrontendOptions`, a downcast is used to distinguish between the Clang's testing extension and other (client) extensions.

This functionality is enabled by LLVM-style RTTI. However, this style of RTTI is hard to extend, as it requires patching Clang (adding new case to the `ModuleFileExtensionKind` enum).

This patch switches to the LLVM RTTI for open class hierarchies, which allows libClang users (e.g. Swift) to create implementations of `ModuleFileExtension` without patching Clang. (Documentation of the feature: https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html#rtti-for-open-class-hierarchies)

Reviewed By: artemcm

Differential Revision: https://reviews.llvm.org/D97702
2021-03-05 11:11:05 +01:00
Fangrui Song 931a3aa967 [Driver][test] Fix ClangDriverTest 2021-03-04 22:44:37 -08:00
Krystian Kuzniarek 6ca52815fb [clang-format][PR47290] Add ShortNamespaceLines format option
clang-format documentation states that having enabled
FixNamespaceComments one may expect below code:

c++
namespace a {
foo();
}

to be turned into:

c++
namespace a {
foo();
} // namespace a

In reality, no "// namespace a" was added. The problem was too high
value of kShortNamespaceMaxLines, which is used while deciding whether
a namespace is long enough to be formatted.

As with 9163fe2, clang-format idempotence is preserved.

Differential Revision: https://reviews.llvm.org/D87587
2021-03-01 21:28:14 +01:00
Björn Schäpers 418b4a7b31 [clang-format] Respect spaces in line comment section...
... without an active column limit.

Before line comments were not touched at all with ColumnLimit == 0.

Differential Revision: https://reviews.llvm.org/D96896
2021-03-01 21:28:14 +01:00
Sam McCall 588db1ccff [clangd] Use flags from open files when opening headers they include
Currently our strategy for getting header compile flags is something like:

A) look for flags for the header in compile_commands.json
   This basically never works, build systems don't generate this info.
B) try to match to an impl file in compile_commands.json and use its flags
   This only (mostly) works if the headers are in the same project.
C) give up and use fallback flags
   This kind of works for stdlib in the default configuration, and
   otherwise doesn't.

Obviously there are big gaps here.

This patch inserts a new attempt between A and B: if the header is
transitively included by any open file (whether same project or not),
then we use its compile command.

This doesn't make any attempt to solve some related problems:
 - parsing non-self-contained header files in context (importing PP state)
 - using the compile flags of non-opened candidate files found in the index

Fixes https://github.com/clangd/clangd/issues/123
Fixes https://github.com/clangd/clangd/issues/695
See https://github.com/clangd/clangd/issues/519

Differential Revision: https://reviews.llvm.org/D97351
2021-03-01 09:43:59 +01:00
Darwin Xu e0b1df924a [clang-format] Fix AlignConsecutiveDeclarations handling of pointers
This is a bug fix of https://bugs.llvm.org/show_bug.cgi?id=49175

The expected code format:

unsigned int*       a;
int*                b;
unsigned int Const* c;

The actual code after formatting (without this patch):

unsigned int* a;
int*          b;
unsigned int Const* c;

Differential Revision: https://reviews.llvm.org/D97137
2021-02-27 22:56:36 +01:00
Jakub Budiský 2a42c759ae [clang-format] [PR19056] Add support for access modifiers indentation
Adds support for coding styles that make a separate indentation level for access modifiers, such as Code::Blocks or QtCreator.

The new option, `IndentAccessModifiers`, if enabled, forces the content inside classes, structs and unions (“records”) to be indented twice while removing a level for access modifiers. The value of `AccessModifierOffset` is disregarded in this case, aiming towards an ease of use.

======
The PR (https://bugs.llvm.org/show_bug.cgi?id=19056) had an implementation attempt by @MyDeveloperDay already (https://reviews.llvm.org/D60225) but I've decided to start from scratch. They differ in functionality, chosen approaches, and even the option name. The code tries to re-use the existing functionality to achieve this behavior, limiting possibility of breaking something else.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D94661
2021-02-26 09:17:07 +01:00
Kadir Cetinkaya 7c9c0a87c8
[clang][DeclPrinter] Pass Context into StmtPrinter whenever possible
ASTContext were only passed to the StmtPrinter in some places, while it
is always available in DeclPrinter. The context is used by StmtPrinter to better
print statements in some cases, like printing constants as written.

Differential Revision: https://reviews.llvm.org/D97043
2021-02-23 09:42:19 +01:00
Mikhail Goncharov 3b148d6f99 Revert "Revert "Revert "Implement nullPointerConstant() using a better API."""
This reverts commit ba1d9546ee.
2021-02-22 14:37:03 +01:00
Mikhail Goncharov ba1d9546ee Revert "Revert "Implement nullPointerConstant() using a better API.""
This reverts commit 6984e0d439.

While change by itself seems to be consistent with nullPointerConstant
docs of not matching "int i = 0;" but it's not clear why it's wrong and
9148302a2a author just forgot to update
the doc.
2021-02-22 13:43:42 +01:00
Anastasia Stulova cf3ef15a6e [OpenCL] Add builtin declarations by default.
This change enables the builtin function declarations
in clang driver by default using the Tablegen solution
along with the implicit include of 'opencl-c-base.h'
header.

A new flag '-cl-no-stdinc' disabling all default
declarations and header includes is added. If any other
mechanisms were used to include the declarations (e.g.
with -Xclang -finclude-default-header) and the new default
approach is not sufficient the, `-cl-no-stdinc` flag has
to be used with clang to activate the old behavior.

Tags: #clang

Differential Revision: https://reviews.llvm.org/D96515
2021-02-22 12:24:16 +00:00
Balazs Benics 38b185832e [analyzer][CTU] API for CTU macro expansions
Removes `CrossTranslationUnitContext::getImportedFromSourceLocation`
Removes the corresponding unit-test segment.

Introduces the `CrossTranslationUnitContext::getMacroExpansionContextForSourceLocation`
which will return the macro expansion context for an imported TU. Also adds a
few implementation FIXME notes where applicable, since this feature is
not implemented yet. This fact is also noted as Doxygen comments.

Uplifts a few CTU LIT test to match the current **incomplete** behavior.

It is a regression to some extent since now we don't expand any
macros in imported TUs. At least we don't crash anymore.

Note that the introduced function is already covered by LIT tests.
Eg.: Analysis/plist-macros-with-expansion-ctu.c

Reviewed By: balazske, Szelethus

Differential Revision: https://reviews.llvm.org/D94673
2021-02-22 11:12:22 +01:00
Balazs Benics 6e3071007b [analyzer] Introduce MacroExpansionContext to libAnalysis
Introduce `MacroExpansionContext` to track what and how macros in a translation
unit expand. This is the first element of the patch-stack in this direction.

The main goal is to substitute the current macro expansion generator in the
`PlistsDiagnostics`, but all the other `DiagnosticsConsumer` could benefit from
this.

`getExpandedText` and `getOriginalText` are the primary functions of this class.
The former can provide you the text that was the result of the macro expansion
chain starting from a `SourceLocation`.
While the latter will tell you **what text** was in the original source code
replaced by the macro expansion chain from that location.

Here is an example:

  void bar();
  #define retArg(x) x
  #define retArgUnclosed retArg(bar()
  #define BB CC
  #define applyInt BB(int)
  #define CC(x) retArgUnclosed

  void unbalancedMacros() {
    applyInt  );
  //^~~~~~~~~~^ is the substituted range
  // Original text is "applyInt  )"
  // Expanded text is "bar()"
  }

  #define expandArgUnclosedCommaExpr(x) (x, bar(), 1
  #define f expandArgUnclosedCommaExpr

  void unbalancedMacros2() {
    int x =  f(f(1))  ));  // Look at the parenthesis!
  //         ^~~~~~^ is the substituted range
  // Original text is "f(f(1))"
  // Expanded text is "((1,bar(),1,bar(),1"
  }

Might worth investigating how to provide a reusable component, which could be
used for example by a standalone tool eg. expanding all macros to their
definitions.

I borrowed the main idea from the `PrintPreprocessedOutput.cpp` Frontend
component, providing a `PPCallbacks` instance hooking the preprocessor events.
I'm using that for calculating the source range where tokens will be expanded
to. I'm also using the `Preprocessor`'s `OnToken` callback, via the
`Preprocessor::setTokenWatcher` to reconstruct the expanded text.

Unfortunately, I concatenate the token's string representation without any
whitespaces except if the token is an identifier when I emit an extra space
to produce valid code for `int var` token sequences.
This could be improved later if needed.

Patch-stack:
  1) D93222 (this one) Introduces the MacroExpansionContext class and unittests

  2) D93223 Create MacroExpansionContext member in AnalysisConsumer and pass
     down to the diagnostics consumers

  3) D93224 Use the MacroExpansionContext for macro expansions in plists
     It replaces the 'old' macro expansion mechanism.

  4) D94673 API for CTU macro expansions
     You should be able to get a `MacroExpansionContext` for each imported TU.
     Right now it will just return `llvm::None` as this is not implemented yet.

  5) FIXME: Implement macro expansion tracking for imported TUs as well.

It would also relieve us from bugs like:
  - [fixed] D86135
  - [confirmed] The `__VA_ARGS__` and other macro nitty-gritty, such as how to
    stringify macro parameters, where to put or swallow commas, etc. are not
    handled correctly.
  - [confirmed] Unbalanced parenthesis are not well handled - resulting in
    incorrect expansions or even crashes.
  - [confirmed][crashing] https://bugs.llvm.org/show_bug.cgi?id=48358

Reviewed By: martong, Szelethus

Differential Revision: https://reviews.llvm.org/D93222
2021-02-22 11:11:57 +01:00
Stephen Kelly 559f372844 [ASTMatchers] Fix hasUnaryOperand matcher for postfix operators
Differential Revision: https://reviews.llvm.org/D97095
2021-02-20 17:54:12 +00:00
Stephen Kelly 6984e0d439 Revert "Implement nullPointerConstant() using a better API."
This reverts commit 9148302a (2019-08-22) which broke the pre-existing
unit test for the matcher.  Also revert commit 518b2266 (Fix the
nullPointerConstant() test to get bots back to green., 2019-08-22) which
incorrectly changed the test to expect the broken behavior.

Differential Revision: https://reviews.llvm.org/D96665
2021-02-20 17:33:07 +00:00
Stephen Kelly e4d5f00093 [ASTMatchers] Fix hasParent while ignoring unwritten nodes
For example, before this patch we can use has() to get from a
cxxRewrittenBinaryOperator to its operand, but hasParent doesn't get
back to the cxxRewrittenBinaryOperator.  This patch fixes that.

Differential Revision: https://reviews.llvm.org/D96113
2021-02-18 15:04:03 +00:00
Haojian Wu 780ead41e0 [Syntax] No crash on OpaqueValueExpr.
OpaqueValueExpr doesn't correspond to the concrete syntax, it has
invalid source location, ignore them.

Reviewed By: kbobyrev

Differential Revision: https://reviews.llvm.org/D96112
2021-02-18 10:32:04 +01:00
Jan Svoboda ed86328515 [clang][cli] Add explicit round-trip test
This patch adds a test that verifies all `CompilerInvocation` members are filled correctly during command line round-trip.

Reviewed By: dexonsmith

Differential Revision: https://reviews.llvm.org/D96705
2021-02-16 14:56:26 +01:00
Björn Schäpers 25f753c51e [clang-format] Add possibility to be based on parent directory
This allows the define BasedOnStyle: InheritParentConfig and then
clang-format looks into the parent directories for their
.clang-format and takes that as a basis.

Differential Revision: https://reviews.llvm.org/D93844
2021-02-14 19:56:10 +01:00
Haojian Wu e159a3ced4 [Syntax] Remove a strict valid source location assertion for TypeLoc.
The EndLoc of a type loc can be invalid for broken code.

Also extend the existing test to support error code with `error-ok`
annotation.

Differential Revision: https://reviews.llvm.org/D96261
2021-02-11 09:53:52 +01:00
Haojian Wu 35a5e88390 [Syntax] NFC, Simplify a test with annotations 2021-02-11 09:49:06 +01:00
Jan Svoboda 40c261c41c [clang][cli] Generate and round-trip language options
This patch implements generation of remaining language options and tests it by performing parse-generate-parse round trip (on by default for assert builds, off otherwise).

This patch also correctly reports failures in `parseSanitizerKinds`, which is necessary for emitting diagnostics when an invalid sanitizer is passed to `-fsanitize=` during round-trip.

This patch also removes TableGen marshalling classes from two options:
* `fsanitize_blacklist` When parsing: it's first initialized via the generated code, but then also changed by manually written code, which is confusing.
* `fopenmp` When parsing: it's first initialized via generated code, but then conditionally changed by manually written code. This is also confusing. Moreover, we need to do some extra checks when generating it, which would be really cumbersome in TableGen. (Specifically, not emitting it when `-fopenmp-simd` was present.)

Reviewed By: dexonsmith

Differential Revision: https://reviews.llvm.org/D95793
2021-02-09 10:18:55 +01:00
Kadir Cetinkaya f743184911
[clang][CodeComplete] Fix crash on ParenListExprs
Fixes https://github.com/clangd/clangd/issues/676.

Differential Revision: https://reviews.llvm.org/D95935
2021-02-08 13:16:49 +01:00
Stephen Kelly ddca007a29 Add code complete support for mapAnyOf 2021-02-07 16:03:05 +00:00
Stephen Kelly 04b69d9a60 Add clang-query support for mapAnyOf
Differential Revision: https://reviews.llvm.org/D94880
2021-02-07 15:40:15 +00:00
Stephen Kelly 45e210dbeb [ASTMatchers] Make it possible to build mapAnyOf through the registry 2021-02-07 15:36:15 +00:00
Stephen Kelly d3bccdcd50 [ASTMatchers ]Make MatcherDescriptors indicate the node type they match 2021-02-07 15:13:28 +00:00
Haojian Wu 6c1a23303d [Syntax] Support condition for IfStmt.
Differential Revision: https://reviews.llvm.org/D95782
2021-02-04 09:15:30 +01:00
Stephen Kelly 9e5fc578f9 [ASTMatchers] Ignore parts of BindingDecls which are not spelled in source
Differential Revision: https://reviews.llvm.org/D95740
2021-02-02 14:23:13 +00:00
Kent Sommer a8105b3766 [clang-format] Add case aware include sorting.
Adds an option to [clang-format] which sorts headers in an alphabetical manner using case only for tie-breakers. The options is off by default in favor of the current ASCIIbetical sorting style.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D95017
2021-02-02 15:12:27 +01:00
Stephen Kelly 467a045601 [ASTMatchers] Add matchers for decomposition decls
Differential Revision: https://reviews.llvm.org/D95739
2021-02-02 14:11:02 +00:00
Stephen Kelly d6a06365cf [ASTMatchers] Fix matching after generic top-level matcher
With a matcher like

  expr(anyOf(integerLiteral(equals(42)), unless(expr())))

and code such as

  struct B {
    B(int);
  };

  B func1() { return 42; }

the top-level expr() would match each of the nodes which are not spelled
in the source and then ignore-traverse to match the integerLiteral node.
This would result in multiple results reported for the integerLiteral.

Fix that by only running matching logic on nodes which are not skipped
with the top-level matcher.

Differential Revision: https://reviews.llvm.org/D95735
2021-02-02 13:31:05 +00:00
Björn Schäpers 772eb24e00 [clang-format] Add option to control the spaces in a line comment
Differential Revision: https://reviews.llvm.org/D92257
2021-02-01 22:48:50 +01:00
Stephen Kelly bb57a3422a Fix traversal with hasDescendant into lambdas
Differential Revision: https://reviews.llvm.org/D95607
2021-01-30 13:57:41 +00:00
Stephen Kelly 79125085f1 [ASTMatchers] Fix traversal below range-for elements
Differential Revision: https://reviews.llvm.org/D95562
2021-01-30 13:47:14 +00:00
Björn Schäpers 4ad41f1daf Revert "[clang-format] Add option to control the spaces in a line comment"
This reverts commit 078f30e04d.
2021-01-29 09:30:52 +01:00
Björn Schäpers 078f30e04d [clang-format] Add option to control the spaces in a line comment
Differential Revision: https://reviews.llvm.org/D92257
2021-01-29 07:00:08 +01:00
Stephen Kelly 43cc4f1500 Ensure that we traverse non-op() method bodys of lambdas
Differential Revision: https://reviews.llvm.org/D95644
2021-01-29 00:49:28 +00:00
Stephen Kelly 3c79734f29 [ASTMatchers] Add invocation matcher
Differential Revision: https://reviews.llvm.org/D94865
2021-01-28 20:47:09 +00:00
Stephen Kelly 6f0df3cddb [ASTMatchers] Avoid pathological traversal over nested lambdas
Differential Revision: https://reviews.llvm.org/D95573
2021-01-28 20:45:45 +00:00
Marek Kurdej e3713f156b [clang-format] Avoid considering include directive as a template closer.
This fixes a bug [[ http://llvm.org/PR48891 | PR48891 ]] introduced in D93839 where:
```
#include <stdint.h>
namespace rep {}
```
got formatted as
```
#include <stdint.h>
namespace rep {
}
```

Reviewed By: MyDeveloperDay, leonardchan

Differential Revision: https://reviews.llvm.org/D95479
2021-01-27 09:15:30 +01:00
Duncan P. N. Exon Smith 8afabff6b1 Frontend: Fix memory leak in CompilerInstance::setVerboseOutputStream
Found this memory leak in `CompilerInstance::setVerboseOutputStream` by
inspection; it looks like this wasn't previously exercised, since it was
never called twice.

Differential Revision: https://reviews.llvm.org/D93249
2021-01-26 14:57:23 -08:00
Marek Kurdej 6d5c1cd2ab Revert "[clang-format] add case aware include sorting"
This reverts commit 3395a336b0 as there was a post-merge doubt about option naming and type.
2021-01-26 11:58:56 +01:00
Jan Svoboda 2154cffdc2 [clang][cli] Store LangStandard::Kind in LangOptions
The `LangStandard::Kind` parsed from command line arguments is used to set up some `LangOption` defaults, but isn't stored anywhere.

To be able to generate `-std=` (in future patch), we need `CompilerInvocation` to not forget it.

This patch demonstrates another use-case: using `LangStd` to set up defaults of marshalled options.

Reviewed By: dexonsmith

Differential Revision: https://reviews.llvm.org/D95342
2021-01-26 09:05:43 +01:00
Albertas Vyšniauskas 60bf5826cf [clang-format] PR16518 Add flag to suppress empty line insertion before access modifier
Add new option called InsertEmptyLineBeforeAccessModifier. Empty line
before access modifier is inerted if this option is set to true (which
is the default value, because clang-format always inserts empty lines
before access modifiers), otherwise empty lines are removed.

Fixes issue #16518.

Differential Revision: https://reviews.llvm.org/D93846
2021-01-25 21:02:41 +01:00
Lukas Barth 3395a336b0 [clang-format] add case aware include sorting
* Adds an option to [clang-format] which sorts
  headers in an alphabetical manner using case
  only for tie-breakers. The options is off by
  default in favor of the current ASCIIbetical
  sorting style.

Reviewed By: curdeius, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D95017
2021-01-25 18:53:22 +01:00
Lukas Barth 256314711f [clang-format] Add the possibility to align assignments spanning empty lines or comments
Currently, empty lines and comments break alignment of assignments on consecutive
lines. This makes the AlignConsecutiveAssignments option an enum that allows controlling
whether empty lines or empty lines and comments should be ignored when aligning
assignments.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, tinloaf

Differential Revision: https://reviews.llvm.org/D93986
2021-01-25 09:41:50 +01:00
Marek Kurdej 7b9d88ab38 Revert "[clang-format] Add the possibility to align assignments spanning empty lines or comments"
This reverts commit f00a20e51c.
2021-01-25 09:40:46 +01:00
Marek Kurdej f00a20e51c [clang-format] Add the possibility to align assignments spanning empty lines or comments
Currently, empty lines and comments break alignment of assignments on consecutive
lines. This makes the AlignConsecutiveAssignments option an enum that allows controlling
whether empty lines or empty lines and comments should be ignored when aligning
assignments.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, tinloaf

Differential Revision: https://reviews.llvm.org/D93986
2021-01-25 09:36:55 +01:00
Balázs Kéri 98a8344895 [clang][ASTImporter] Add support for importing CXXFoldExpr.
Reviewed By: shafik, martong

Differential Revision: https://reviews.llvm.org/D94786
2021-01-22 15:20:55 +01:00
Stephen Kelly 8000c77853 Make it possible to store a ASTNodeKind in VariantValue
Differential Revision: https://reviews.llvm.org/D94878
2021-01-20 15:44:45 +00:00
Stephen Kelly 0cd0eb6e0a Add API to retrieve a clade kind from ASTNodeKind
Differential Revision: https://reviews.llvm.org/D94877
2021-01-19 22:51:30 +00:00
Stephen Kelly ecf696641e [ASTMatchers] Allow use of mapAnyOf in more contexts
Add an operator overload to ArgumentAdaptingMatcherFunc to allow use of
mapAnyOf within hasAncestor, hasParent etc.

Differential Revision: https://reviews.llvm.org/D94864
2021-01-19 22:10:09 +00:00
Björn Schäpers cbdde495ba [clang-format] Apply Allman style to lambdas
Differential Revision: https://reviews.llvm.org/D94906
2021-01-19 18:17:01 +01:00
Björn Schäpers bcc1dee600 [clang-format] Add StatementAttributeLikeMacros option
This allows to ignore for example Qts emit when
AlignConsecutiveDeclarations is set, otherwise it is parsed as a type
and it results in some misformating:

unsigned char MyChar = 'x';
emit          signal(MyChar);

Differential Revision: https://reviews.llvm.org/D93776
2021-01-18 06:54:31 +01:00
mydeveloperday 00dc97f167 [clang-format] PR48594 BraceWrapping: SplitEmptyRecord ignored for templates
https://bugs.llvm.org/show_bug.cgi?id=48594

Empty or small templates were not being treated the same way as small classes especially when SplitEmptyRecord was set to true

This revision aims to help this by identifying a case when we should try not to merge the lines together

Reviewed By: curdeius, JohelEGP

Differential Revision: https://reviews.llvm.org/D93839
2021-01-17 11:14:33 +00:00
mydeveloperday 9af03864df [clang-format] Revert e9e6e3b34a
Reverting {D92753} due to issues with #pragma indentation in #ifdef/endif structure
2021-01-17 11:07:31 +00:00
Stephen Kelly b765eaf9a6 [ASTMatchers] Add support for CXXRewrittenBinaryOperator
Differential Revision: https://reviews.llvm.org/D94130
2021-01-16 13:44:22 +00:00
Stephen Kelly e810e95e4b [ASTMatchers] Add binaryOperation matcher
This is a simple utility which allows matching on binaryOperator and
cxxOperatorCallExpr. It can also be extended to support
cxxRewrittenBinaryOperator.

Add generic support for MapAnyOfMatchers to auto-marshalling functions.

Differential Revision: https://reviews.llvm.org/D94129
2021-01-16 13:44:09 +00:00
Stephen Kelly dbe056c2e3 [ASTMatchers] Make cxxOperatorCallExpr matchers API-compatible with n-ary operators
This makes them composable with mapAnyOf().

Differential Revision: https://reviews.llvm.org/D94128
2021-01-16 12:53:11 +00:00
Stephen Kelly a7101450a4 [ASTMatchers] Add mapAnyOf matcher
Make it possible to compose a matcher for different base nodes.

This accepts one or more node matcher functors and zero or more
matchers, composing the latter into the former.

This allows composing of matchers where the same inner matcher name is
used for the same concept, but with a different node functor. Currently,
there is a limitation that the nodes must be in the same "clade", so
while

  mapAnyOf(ifStmt, forStmt).with(hasBody(stmt()))

can be used, functionDecl can not be added to the tuple.

It is possible to use this in clang-query, but it will require changes
to the QueryParser, so is deferred to a future review.

Differential Revision: https://reviews.llvm.org/D94127
2021-01-16 12:53:11 +00:00
Stephan Bergmann 215ed9b33c Adapt CastExpr::getSubExprAsWritten to ConstantExpr
Differential Revision: https://reviews.llvm.org/D87030
2021-01-12 09:41:03 +01:00
Jan Svoboda 97100646d1 Reapply "[clang][cli] Port DiagnosticOpts to new option parsing system"
This reverts commit 8e3e148c

This commit fixes two issues with the original patch:
* The sanitizer build bot reported an uninitialized value. This was caused by normalizeStringIntegral not returning None on failure.
* Some build bots complained about inaccessible keypaths. To mitigate that, "this->" was added back to the keypath to restore the previous behavior.
2021-01-11 10:05:53 +01:00
Rafał Jelonek 89878e8c96 [clang-format] Find main include after block ended with #pragma hdrstop
Find main include in first include block not ended with #pragma hdrstop

Reviewed By: curdeius

Differential Revision: https://reviews.llvm.org/D94217
2021-01-11 09:49:34 +01:00
Rafał Jelonek 7473940bae [clang-format] turn on formatting after "clang-format on" while sorting includes
Formatting is not active after "clang-format on" due to merging lines while formatting is off. Also, use trimmed line. Behaviour with LF is different than with CRLF.

Reviewed By: curdeius, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D94206
2021-01-11 09:41:15 +01:00
Rafał Jelonek ee27c767bd [clang-format] Skip UTF8 Byte Order Mark while sorting includes
If file contain BOM then first instruction (include or clang-format off) is ignored

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D94201
2021-01-11 09:32:55 +01:00