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
If file contain BOM then first instruction (include or clang-format off) is ignored
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D94201
This patch introduces additional infrastructure necessary to accommodate DiagnosticOptions.
DiagnosticOptions are unique in that they are parsed by the same function in cc1 AND in the Clang driver. The call to the parsing function from the driver occurs early on in the compilation process, where no proper DiagnosticEngine exists, because the diagnostic options (passed through command line) are not known yet.
To preserve the current behavior, we need to be able to selectively parse:
* all options (for -cc1),
* only diagnostic options (for driver).
This patch achieves that in the following way:
* new MacroPrefix field is added to the Option TableGen class,
* new IsDiag TableGen mixin sets MacroPrefix to "DIAG_",
* TableGen backend serializes option records into a macro with the prefix,
* CompilerInvocation parse/generate methods define the [DIAG_]OPTION_WITH_MARSHALLING macros to handle diagnostic options separately.
Depends on D93700, D93701 & D93702.
Reviewed By: dexonsmith
Differential Revision: https://reviews.llvm.org/D84673
The assertion can happen if ASTImporter imports a CXXRecordDecl in a template
and then imports another redeclaration of this declaration, while the first import is in progress.
The process of first import did not set the "described template" yet
and the second import finds the first declaration at setting the injected types.
Setting the injected type requires in the assertion that the described template is set.
The exact assertion was:
clang/lib/AST/ASTContext.cpp:4411:
clang::QualType clang::ASTContext::getInjectedClassNameType(clang::CXXRecordDecl*, clang::QualType) const:
Assertion `NeedsInjectedClassNameType(Decl)' failed.
Reviewed By: shafik
Differential Revision: https://reviews.llvm.org/D94067
This allows us to verify that we don't emit options multiple times.
In most cases, that would be benign, but for options with `MarshallingInfoVectorString`, emitting wrong number of arguments might change the semantics.
Reviewed By: Bigcheese
Differential Revision: https://reviews.llvm.org/D93636
This reverts 7ad666798f and 1876a2914f that reverted:
741978d727 [clang][cli] Port CodeGen option flags to new option parsing system
383778e217 [clang][cli] Port LangOpts option flags to new option parsing system
aec2991d08 [clang][cli] Port LangOpts simple string based options to new option parsing system
95d3cc67ca [clang][cli] Port CodeGenOpts simple string flags to new option parsing system
27b7d64688 [clang][cli] Streamline MarshallingInfoFlag description
70410a2649 [clang][cli] Let denormalizer decide how to render the option based on the option class
63a24816f5 [clang][cli] Implement `getAllArgValues` marshalling
Commit 741978d727 accidentally changed the `Group` attribute of `g[no_]column_info` options from `g_flags_Group` to `g_Group`, which changed the debug info options passed to cc1 by the driver.
Similar change was also present in 383778e217, which accidentally added `Group<f_Group>` to `f[no_]const_strings` and `f[no_]signed_wchar`.
This patch corrects all three accidental changes by replacing `Bool{G,F}Option` with `BoolCC1Option`.
Stencils `maybeDeref` and `maybeAddressOf` are designed to handle nodes that may
be pointers. Currently, they only handle native pointers. This patch extends the
support to recognize smart pointers and handle them as well.
Differential Revision: https://reviews.llvm.org/D93637
Because we don't know in ASTMatchFinder whether we're matching in AsIs
or IgnoreUnlessSpelledInSource mode, we need to traverse the lambda
twice, but store whether we're matching in nodes spelled in source or
not.
Differential Revision: https://reviews.llvm.org/D93688
https://bugs.llvm.org/show_bug.cgi?id=48569
This is a tentative fix which addresses a PR raise regarding Case indentation when working with Whitesmiths Indentation
I could not find online any reference sources as to what the case indentation for Whitesmith's should be (or be allowed to be)
But according to the documentation, we don't obey the rules for Whitesmith's
```
In particular, the documentation states that this option is to "indent case labels one level from the switch statement. When false, use the same indentation level as for the switch statement."
```
The behaviour we add here is actually as the TODO in the tests used to state in {D67627}, but when {D82016} was added and I brought these tests out from being TODO I realized I changed the indentation.
Reviewed By: curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D93806
This should've been in 7ad666798f but wasn't.
Squashes these twoc commits:
Revert "[clang][cli] Let denormalizer decide how to render the option based on the option class"
This reverts commit 70410a2649.
Revert "[clang][cli] Implement `getAllArgValues` marshalling"
This reverts commit 63a24816f5.
https://bugs.llvm.org/show_bug.cgi?id=48539
Add support for Qt Translator Comments to reflow
When reflown and a part of the comments are added on a new line, it should repeat these extra characters as part of the comment token.
Reviewed By: curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D93490
https://bugs.llvm.org/show_bug.cgi?id=48535
using `SpaceAfterCStyleCast: true`
```
size_t idx = (size_t) a;
size_t idx = (size_t) (a - 1);
```
is formatted as:
```
size_t idx = (size_t) a;
size_t idx = (size_t)(a - 1);
```
This revision aims to improve that by improving the function which tries to identify a CastRParen
Reviewed By: curdeius
Differential Revision: https://reviews.llvm.org/D93626
Before this patch, you needed to use `AutoNormalizeEnumJoined` whenever you wanted to **de**normalize joined enum.
Besides the naming confusion, this means the fact the option is joined is specified in two places: in the normalization multiclass and in the `Joined<["-"], ...>` multiclass.
This patch makes this work automatically, taking into account the `OptionClass` of options.
Also, the enum denormalizer now just looks up the spelling of the present enum case in a table and forwards it to the string denormalizer.
I also added more tests that exercise this.
Reviewed By: dexonsmith
Original patch by Daniel Grumberg.
Differential Revision: https://reviews.llvm.org/D84189
This allows ASTs to be merged when they contain GenericSelectionExpr
nodes (this is _Generic from C11). This is needed, for example, for
CTU analysis of C code that makes use of _Generic, like the Linux
kernel.
The node is already supported in the AST, but it didn't have a matcher
in ASTMatchers. So, this change adds the matcher and adds support to
ASTImporter. Additionally, this change adds support for structural
equivalence of _Generic in the AST.
Reviewed By: martong, aaron.ballman
Differential Revision: https://reviews.llvm.org/D92600
If both flags created through BoolOption are CC1Option and the keypath has a non-default or non-implied value, the denormalizer gets called twice. If the denormalizer has the ability to generate both flags, we can end up generating the same flag twice.
Reviewed By: dexonsmith, Bigcheese
Differential Revision: https://reviews.llvm.org/D93094
We cannot be sure whether a flag is CC1Option inside the definition of `BoolOption`. Take the example below:
```
let Flags = [CC1Option] in {
defm xxx : BoolOption<...>;
}
```
where TableGen applies `Flags = [CC1Option]` to the `xxx` and `no_xxx` records **after** they have been is fully declared by `BoolOption`.
For the refactored `-f[no-]debug-pass-manager` flags (see the diff), this means `BoolOption` never adds any marshalling info, as it doesn't see either of the flags as `CC1Option`.
For that reason, we should defensively append the marshalling information to both flags inside `BoolOption`. Now the check for `CC1Option` needs to happen later, in the parsing macro, when all TableGen logic has been resolved.
However, for some flags defined through `BoolOption`, we can run into issues:
```
// Options.td
def fenable_xxx : /* ... */;
// Both flags are CC1Option, the first is implied.
defm xxx : BoolOption<"xxx,
"Opts.Xxx", DefaultsToFalse,
ChangedBy<PosFlag, [CC1Option], "", [fenable_xxx]>,
ResetBy<NegFlag, [CC1Option]>>;
```
When parsing `clang -cc1 -fenable-xxx`:
* we run parsing for `PosFlag`:
* set `Opts.Xxx` to default `false`,
* discover `PosFlag` is implied by `-fenable-xxx`: set `Opts.Xxx` to `true`,
* don't see `-fxxx` on command line: do nothing,
* we run parsing for `NegFlag`:
* set `Opts.Xxx` to default `false`,
* discover `NegFlag` cannot be implied: do nothing,
* don't see `-fno-xxx` on command line: do nothing.
Now we ended up with `Opts.Xxx` set to `false` instead of `true`. For this reason, we need to ensure to append the same `ImpliedByAnyOf` instance to both flags.
This means both parsing runs now behave identically (they set the same default value, run the same "implied by" check, and call `makeBooleanOptionNormalizer` that already has information on both flags, so it returns the same value in both calls).
The solution works well, but what might be confusing is this: you have defined a flag **A** that is not `CC1Option`, but can be implied by another flag **B** that is `CC1Option`:
* if **A** is defined manually, it will never get implied, as the code never runs
```
def no_signed_zeros : Flag<["-"], "fno-signed-zeros">, Group<f_Group>, Flags<[]>,
MarshallingInfoFlag<"LangOpts->NoSignedZero">, ImpliedByAnyOf<[menable_unsafe_fp_math]>;
```
* if **A** is defined by `BoolOption`, it could get implied, as the code is run by its `CC1Option` counterpart:
```
defm signed_zeros : BoolOption<"signed-zeros",
"LangOpts->NoSignedZero", DefaultsToFalse,
ChangedBy<NegFlag, [], "Allow optimizations that ignore the sign of floating point zeros",
[cl_no_signed_zeros, menable_unsafe_fp_math]>,
ResetBy<PosFlag, [CC1Option]>, "f">, Group<f_Group>;
```
This is a surprising inconsistency.
One solution might be to somehow propagate the final `Flags` of the implied flag in `ImpliedByAnyOf` and check whether it has `CC1Option` in the parsing macro. However, I think it doesn't make sense to spend time thinking about a corner case that won't come up in real code.
An observation: it is unfortunate that the marshalling information is a part of the flag definition. If we represented it in a separate structure, we could avoid the "double parsing" problem by having a single source of truth. This would require a lot of additional work though.
Note: the original patch missed the `CC1Option` check in the parsing macro, making my reasoning here incomplete. Moreover, it contained a change to denormalization that wasn't necessarily related to these changes, so I've extracted that to a follow-up patch: D93094.
Reviewed By: dexonsmith, Bigcheese
Differential Revision: https://reviews.llvm.org/D93008
Summary: The clang-format may go wrong when handle c++ coroutine keywords and pointer.
The default value for PointerAlignment is PAS_Right. So the following format is good:
```
co_return *a;
```
But within some code style, the value for PointerAlignment is PAS_Left, the behavior goes wrong:
```
co_return* a;
```
test-plan: check-clang
reviewers: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D91245
The import of a typedefs with an attribute uses clang::Decl::setAttrs().
But that needs the ASTContext which we can get only from the
TranslationUnitDecl. But we can get the TUDecl only thourgh the
DeclContext, which is not set by the time of the setAttrs call.
Fix: import the attributes only after the DC is surely imported.
Btw, having the attribute import initiated from GetImportedOrCreateDecl was
fundamentally flawed. Now that is implicitly fixed.
Differential Revision: https://reviews.llvm.org/D92962
This introduces more flexible multiclass for declaring two flags controlling the same boolean keypath.
Compared to existing Opt{In,Out}FFlag multiclasses, the new syntax makes it easier to read option declarations and reason about the keypath.
This also makes specifying common properties of both flags possible.
I'm open to suggestions on the class names. Not 100% sure the benefits are worth the added complexity.
Depends on D92774.
Reviewed By: dexonsmith
Differential Revision: https://reviews.llvm.org/D92775
We don't need to always generate `-f[no-]experimental-new-pass-manager`.
This patch does not change the behavior of any other command line flag. (For example `-triple` is still being always generated.)
Reviewed By: dexonsmith, Bigcheese
Differential Revision: https://reviews.llvm.org/D92857
Add more tests of the command line marshalling infrastructure.
The new tests now make a "round-trip": from arguments, to CompilerInvocation instance to arguments again in a single test case.
The TODOs are resolved in a follow-up patch.
Depends on D92830.
Reviewed By: dexonsmith
Differential Revision: https://reviews.llvm.org/D92774
Migrate over to the `FileEntryRef` overloads of
`SourceManager::createFileID` and `overrideFileContents` (using
`getVirtualFileRef`) in `TextDiagnostic`'s `ShowLine` test.
No functionality change.
Differential Revision: https://reviews.llvm.org/D92968
Migrate to the `FileEntryRef` overload of `SourceManager::createFileID`
(using `FileManager::getOptionalFileRef`) in RefactoringTest.cpp and
RewriterTestContext.h.
No functionality change.
Differential Revision: https://reviews.llvm.org/D92967
A quick search of github.com, shows one common scenario for excessive use of //clang-format off/on is the indentation of #pragma's, especially around the areas of loop optimization or OpenMP
This revision aims to help that by introducing an `IndentPragmas` style, the aim of which is to keep the pragma at the current level of scope
```
for (int i = 0; i < 5; i++) {
// clang-format off
#pragma HLS UNROLL
// clang-format on
for (int j = 0; j < 5; j++) {
// clang-format off
#pragma HLS UNROLL
// clang-format on
....
```
can become
```
for (int i = 0; i < 5; i++) {
#pragma HLS UNROLL
for (int j = 0; j < 5; j++) {
#pragma HLS UNROLL
....
```
This revision also support working alongside the `IndentPPDirective` of `BeforeHash` and `AfterHash` (see unit tests for examples)
Reviewed By: curdeius
Differential Revision: https://reviews.llvm.org/D92753
clang-format see the `disable:` in __pragma(warning(disable:)) as ObjectiveC method call
Remove any line starting with `#` or __pragma line from being part of the ObjectiveC guess
https://bugs.llvm.org/show_bug.cgi?id=42434
Reviewed By: curdeius, krasimir
Differential Revision: https://reviews.llvm.org/D92922
CXXDeductionGuideDecl with a local typedef has its own copy of the
TypedefDecl with the CXXDeductionGuideDecl as the DeclContext of that
TypedefDecl.
```
template <typename T> struct A {
typedef T U;
A(U, T);
};
A a{(int)0, (int)0};
```
Related discussion on cfe-dev:
http://lists.llvm.org/pipermail/cfe-dev/2020-November/067252.html
Without this fix, when we import the CXXDeductionGuideDecl (via
VisitFunctionDecl) then before creating the Decl we must import the
FunctionType. However, the first parameter's type is the afore mentioned
local typedef. So, we then start importing the TypedefDecl whose
DeclContext is the CXXDeductionGuideDecl itself. The infinite loop is
formed.
```
#0 clang::ASTNodeImporter::VisitCXXDeductionGuideDecl(clang::CXXDeductionGuideDecl*) clang/lib/AST/ASTImporter.cpp:3543:0
#1 clang::declvisitor::Base<std::add_pointer, clang::ASTNodeImporter, llvm::Expected<clang::Decl*> >::Visit(clang::Decl*) /home/egbomrt/WORK/llvm5/build/debug/tools/clang/include/clang/AST/DeclNodes.inc:405:0
#2 clang::ASTImporter::ImportImpl(clang::Decl*) clang/lib/AST/ASTImporter.cpp:8038:0
#3 clang::ASTImporter::Import(clang::Decl*) clang/lib/AST/ASTImporter.cpp:8200:0
#4 clang::ASTImporter::ImportContext(clang::DeclContext*) clang/lib/AST/ASTImporter.cpp:8297:0
#5 clang::ASTNodeImporter::ImportDeclContext(clang::Decl*, clang::DeclContext*&, clang::DeclContext*&) clang/lib/AST/ASTImporter.cpp:1852:0
#6 clang::ASTNodeImporter::ImportDeclParts(clang::NamedDecl*, clang::DeclContext*&, clang::DeclContext*&, clang::DeclarationName&, clang::NamedDecl*&, clang::SourceLocation&) clang/lib/AST/ASTImporter.cpp:1628:0
#7 clang::ASTNodeImporter::VisitTypedefNameDecl(clang::TypedefNameDecl*, bool) clang/lib/AST/ASTImporter.cpp:2419:0
#8 clang::ASTNodeImporter::VisitTypedefDecl(clang::TypedefDecl*) clang/lib/AST/ASTImporter.cpp:2500:0
#9 clang::declvisitor::Base<std::add_pointer, clang::ASTNodeImporter, llvm::Expected<clang::Decl*> >::Visit(clang::Decl*) /home/egbomrt/WORK/llvm5/build/debug/tools/clang/include/clang/AST/DeclNodes.inc:315:0
#10 clang::ASTImporter::ImportImpl(clang::Decl*) clang/lib/AST/ASTImporter.cpp:8038:0
#11 clang::ASTImporter::Import(clang::Decl*) clang/lib/AST/ASTImporter.cpp:8200:0
#12 llvm::Expected<clang::TypedefNameDecl*> clang::ASTNodeImporter::import<clang::TypedefNameDecl>(clang::TypedefNameDecl*) clang/lib/AST/ASTImporter.cpp:165:0
#13 clang::ASTNodeImporter::VisitTypedefType(clang::TypedefType const*) clang/lib/AST/ASTImporter.cpp:1304:0
#14 clang::TypeVisitor<clang::ASTNodeImporter, llvm::Expected<clang::QualType> >::Visit(clang::Type const*) /home/egbomrt/WORK/llvm5/build/debug/tools/clang/include/clang/AST/TypeNodes.inc:74:0
#15 clang::ASTImporter::Import(clang::QualType) clang/lib/AST/ASTImporter.cpp:8071:0
#16 llvm::Expected<clang::QualType> clang::ASTNodeImporter::import<clang::QualType>(clang::QualType const&) clang/lib/AST/ASTImporter.cpp:179:0
#17 clang::ASTNodeImporter::VisitFunctionProtoType(clang::FunctionProtoType const*) clang/lib/AST/ASTImporter.cpp:1244:0
#18 clang::TypeVisitor<clang::ASTNodeImporter, llvm::Expected<clang::QualType> >::Visit(clang::Type const*) /home/egbomrt/WORK/llvm5/build/debug/tools/clang/include/clang/AST/TypeNodes.inc:47:0
#19 clang::ASTImporter::Import(clang::QualType) clang/lib/AST/ASTImporter.cpp:8071:0
#20 llvm::Expected<clang::QualType> clang::ASTNodeImporter::import<clang::QualType>(clang::QualType const&) clang/lib/AST/ASTImporter.cpp:179:0
#21 clang::QualType clang::ASTNodeImporter::importChecked<clang::QualType>(llvm::Error&, clang::QualType const&) clang/lib/AST/ASTImporter.cpp:198:0
#22 clang::ASTNodeImporter::VisitFunctionDecl(clang::FunctionDecl*) clang/lib/AST/ASTImporter.cpp:3313:0
#23 clang::ASTNodeImporter::VisitCXXDeductionGuideDecl(clang::CXXDeductionGuideDecl*) clang/lib/AST/ASTImporter.cpp:3543:0
```
The fix is to first create the TypedefDecl and only then start to import
the DeclContext.
Basically, we could do this during the import of all other Decls (not
just for typedefs). But it seems, there is only one another AST
construct that has a similar cycle: a struct defined as a function
parameter:
```
int struct_in_proto(struct data_t{int a;int b;} *d);
```
In that case, however, we had decided to return simply with an error
back then because that seemed to be a very rare construct.
Differential Revision: https://reviews.llvm.org/D92209
Add more tests of the command line marshalling infrastructure.
The new tests now make a "round-trip": from arguments, to CompilerInvocation instance to arguments again in a single test case.
The TODOs are resolved in a follow-up patch.
Depends on D92830.
Reviewed By: dexonsmith
Differential Revision: https://reviews.llvm.org/D92774
Allow hashing FileEntryRef and DirectoryEntryRef via `hash_value`, and
use that to implement `DenseMapInfo`. This hash should be equal whenever
the entry is the same (the name used to reference it is not relevant).
Also add `DirectoryEntryRef::isSameRef` to simplify the implementation
and facilitate testing.
Differential Revision: https://reviews.llvm.org/D92627
Previously, loading one from a file meant allowing the library to do the IO.
Clangd would prefer to do such IO itself (e.g. to allow caching).
Differential Revision: https://reviews.llvm.org/D92640
I use several of the clang-format clean directories as a test suite, this one had got slightly out of wack in a prior commit
Reviewed By: HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D92666
This function doesn't seem to be used in-tree outside tests.
However clangd wants to use it soon, and having the CDB be self-contained seems
reasonable.
Differential Revision: https://reviews.llvm.org/D92646
This is a starting point to improve the handling of concepts in clang-format. There is currently no real formatting of concepts and this can lead to some odd formatting, e.g.
Reviewed By: mitchell-stellar, miscco, curdeius
Differential Revision: https://reviews.llvm.org/D79773
The static_assert in "libcxx/include/memory" was the main offender here,
but then I figured I might as well `git grep -i instantat` and fix all
the instances I found. One was in user-facing HTML documentation;
the rest were in comments or tests.
This makes the options API composable, allows boolean flags to imply non-boolean values and makes the code more logical (IMO).
Differential Revision: https://reviews.llvm.org/D91861
Add `FileEntryRef::getDir`, which returns a `DirectoryEntryRef`. This
includes a few changes:
- Customize `OptionalStorage` so that `Optional<DirectoryEntryRef>` is
pointer-sized (like the change made to `Optional<FileEntryRef>`).
Factored out a common class, `FileMgr::MapEntryOptionalStorage`, to
reduce the code duplication.
- Store an `Optional<DirectoryEntryRef>` in `FileEntryRef::MapValue`.
This is set if and only if `MapValue` has a real `FileEntry`.
- Change `FileManager::getFileRef` and `getVirtualFileRef` to use
`getDirectoryRef` and store it in the `StringMap` for `FileEntryRef`.
Differential Revision: https://reviews.llvm.org/D90484
A number of declarations were leftover after the move from `clang::tooling` to
`clang::transformer`. This patch removes those declarations and upgrades the
handful of references to the deprecated declarations.
Differential Revision: https://reviews.llvm.org/D92340
CXXDeductionGuideDecl is a FunctionDecl, but its constructor should be called
appropriately, at least to set the kind variable properly.
Differential Revision: https://reviews.llvm.org/D92109
The test case isn't using the AST matchers for all checks as there doesn't seem to be support for
matching NonTypeTemplateParmDecl default arguments. Otherwise this is simply importing the
default arguments.
Reviewed By: martong
Differential Revision: https://reviews.llvm.org/D92106
The test case isn't using the AST matchers for all checks as there doesn't seem to be support for
matching TemplateTypeParmDecl default arguments. Otherwise this is simply importing the
default arguments.
Also updates several LLDB tests that now as intended omit the default template
arguments of several std templates.
Reviewed By: martong
Differential Revision: https://reviews.llvm.org/D92103
Same idea as in D92103 and D92106, but I realised after creating those reviews that there are
also TemplateTemplateParmDecls that can have default arguments, so here's hopefully the
last patch for default template arguments.
Reviewed By: martong
Differential Revision: https://reviews.llvm.org/D92119
When importing a `ClassTemplateSpecializationDecl` definition into a TU with a matching
`ClassTemplateSpecializationDecl` definition and a more recent forward decl, the ASTImporter
currently will call `MapImported()` for the definitions, but will return the forward declaration
from the `ASTImporter::Import()` call.
This is triggering some assertions in LLDB when we try to fully import some DeclContexts
before we delete the 'From' AST. The returned 'To' Decl before this patch is just the most recent
forward decl but that's not the Decl with the definition to which the ASTImporter will import
the child declarations.
This patch just changes that the ASTImporter returns the definition that the imported Decl was
merged with instead of the found forward declaration.
Reviewed By: martong
Differential Revision: https://reviews.llvm.org/D92016
traverse() predates the IgnoreUnlessSpelledInSource mode. Update example
and test code to use the newer mode.
Differential Revision: https://reviews.llvm.org/D91917
Currently, `node` only includes the semicolon for (some) statements. However,
declarations have the same issue of (potentially) trailing semicolons, so `node`
should behave the same for them.
Differential Revision: https://reviews.llvm.org/D91872
Don't match Stmt or Decl nodes not spelled in the source when using
TK_IgnoreUnlessSpelledInSource. This prevents accidental modification
of source code at incorrect locations.
Differential Revision: https://reviews.llvm.org/D90984
Update the ASTNodeTraverser to dump only nodes spelled in source. There
are only a few which need to be handled, but Decl nodes for which
isImplicit() is true are handled together.
Update the RAV instances used in ASTMatchFinder to ignore the nodes too.
As with handling of template instantiations, it is necessary to allow
the RAV to process the implicit nodes because they need to be visitable
before the first traverse() matcher is encountered. An exception to
this is in the MatchChildASTVisitor, because we sometimes wish to make a
node matchable but make its children not-matchable. This is the case
for defaulted CXXMethodDecls for example.
Extend TransformerTests to illustrate the kinds of problems that can
arise when performing source code rewriting due to matching implicit
nodes.
This change accounts for handling nodes not spelled in source when using
direct matching of nodes, and when using the has() and hasDescendant()
matchers. Other matchers such as
cxxRecordDecl(hasMethod(cxxMethodDecl())) still succeed for
compiler-generated methods for example after this change. Updating the
implementations of hasMethod() and other matchers is for a follow-up
patch.
Differential Revision: https://reviews.llvm.org/D90982
Original commit message: "
Move the test compiler setup in a common place. NFCI
This patch reduces the copy paste in the unittest/CodeGen folder by moving the
common compiler setup phase in a header file.
Differential revision: https://reviews.llvm.org/D91061
"
This patch includes a fix for the memory leaks pointed out by @vitalybuka
This patch reduces the copy paste in the unittest/CodeGen folder by moving the
common compiler setup phase in a header file.
Differential revision: https://reviews.llvm.org/D91061
In JavaScript breaking before a `@tag` in a comment puts it on a new line, and
machinery that parses these comments will fail to understand such comments.
This adapts clang-format to not break before `@`. Similar functionality exists
for not breaking before `{`.
Reviewed By: mprobst
Differential Revision: https://reviews.llvm.org/D91078
This ports a number of OpenCL and fast-math flags for floating point
over to the new marshalling infrastructure.
As part of this, `Opt{In,Out}FFlag` were enhanced to allow other flags to
imply them, via `DefaultAnyOf<>`. For example:
```
defm signed_zeros : OptOutFFlag<"signed-zeros", ...,
"LangOpts->NoSignedZero",
DefaultAnyOf<[cl_no_signed_zeros, menable_unsafe_fp_math]>>;
```
defines `-fsigned-zeros` (`false`) and `-fno-signed-zeros` (`true`)
linked to the keypath `LangOpts->NoSignedZero`, defaulting to `false`,
but set to `true` implicitly if one of `-cl-no-signed-zeros` or
`-menable-unsafe-fp-math` is on.
Note that the initial patch was written Daniel Grumberg.
Differential Revision: https://reviews.llvm.org/D82756
In C++ with -Werror=comment, multiline comments are not allowed.
clang-format could accidentally introduce multiline comments when reflowing.
This adapts clang-format to not introduce multiline comments by not allowing a
break after `\`. Note that this does not apply to comment lines that already are
multiline comments, such as comments in macros.
Reviewed By: sammccall
Differential Revision: https://reviews.llvm.org/D90949
Continue to dump and match on explicit template specializations, but
omit explicit instantiation declarations and definitions.
Differential Revision: https://reviews.llvm.org/D90763
In JavaScript some @tags can be followed by `{`, and machinery that parses
these comments will fail to understand the comment if followed by a line break.
clang-format already handles this case by not breaking before `{` in comments.
However this was not working in cases when the column limit falls within `@tag`
or between `@tag` and `{`. This adapts clang-format for this case.
Reviewed By: mprobst
Differential Revision: https://reviews.llvm.org/D90908
Clang offers a `-f[no]-show-column` flag for hiding the column numbers when
printing diagnostics but there is no option for doing the same with line
numbers.
In LLDB having this option would be useful, as LLDB sometimes only knows the
file name for a SourceLocation and just assigns it the dummy line/column `1:1`.
These fake line/column numbers are confusing to the user and LLDB should be able
to tell clang to hide *both* the column and the line number when rendering text
diagnostics.
This patch adds a flag for also hiding the line numbers. It's not exposed via
the command line flags as it's most likely not very useful for any user and can
lead to ambiguous output when the user decides to only hide either the line or
the column number (where `file:1: ...` could now refer to both line 1 or column
1 depending on the compiler flags). LLDB can just access the DiagnosticOptions
directly when constructing its internal Clang instance.
The effect doesn't apply to Vi/MSVC style diagnostics because it's not defined
how these diagnostic styles would show an omitted line number (MSVC doesn't have
such an option and Vi's line mode is theory only supporting line numbers if I
understand it correctly).
Reviewed By: thakis, MaskRay
Differential Revision: https://reviews.llvm.org/D83038
Summary:
Object of type `Compilation` now can keep a callback that is called
after each execution of `Command`. This must simplify adaptation of
clang in custom distributions and allow facilities like collection of
execution statistics.
Reviewers: rsmith, rjmccall, Eugene.Zelenko
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D78899
Made the isExpandedFromMacro matcher work on Stmt's, TypeLocs and Decls in line with the other macro expansion matchers.
Also tweaked it to take a `std::string` instead of a `StringRef`.
This prevents potential use-after-free bugs if the matcher is created with a string thats destroyed before the matcher finishes matching.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D90303
Summary:
IgnoreUnlessSpelledInSource mode should ignore these because they are
not written in the source. This matters for example when trying to
replace types or values which are templated. The new test in
TransformerTest.cpp in this commit demonstrates the problem.
In existing matcher code, users can write
`unless(isInTemplateInstantiation())` or `unless(isInstantiated())` (the
user must know which to use). The point of the
TK_IgnoreUnlessSpelledInSource mode is to allow the novice to avoid such
details. This patch changes the IgnoreUnlessSpelledInSource mode to
skip over implicit template instantiations.
This patch does not change the TK_AsIs mode.
Note: An obvious attempt at an alternative implementation would simply
change the shouldVisitTemplateInstantiations() in ASTMatchFinder.cpp to
return something conditional on the operational TraversalKind. That
does not work because shouldVisitTemplateInstantiations() is called
before a possible top-level traverse() matcher changes the operational
TraversalKind.
Reviewers: sammccall, aaron.ballman, gribozavr2, ymandel, klimek
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D80961
TokenAnnotator::splitPenalty() was always returning 0 for opening parens if
AlignAfterOpenBracket was set to BAS_DontAlign, so the preferred point for
line breaking was always after the open paren (and was ignoring
PenaltyBreakBeforeFirstCallParameter). This change restricts the zero
penalty to the AllowAllArgumentsOnNextLine case. This results in improved
formatting for FreeBSD where we set AllowAllArgumentsOnNextLine: false
and a high value for PenaltyBreakBeforeFirstCallParameter to avoid breaking
after the open paren.
Before:
```
functionCall(
paramA, paramB, paramC);
void functionDecl(
int A, int B, int C)
```
After:
```
functionCall(paramA, paramB,
paramC);
void functionDecl(int A, int B,
int C)
```
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D90246
This reverts commit 940d0a310d,
effectively reapplying 84e8257937, after
working around the compile errors on the bots that I wasn't seeing
locally. I removed the `constexpr` from `OptionalStorage<FileEntryRef>`
that I had cargo-culted from the generic version, since `FileEntryRef`
isn't relevant in `constexpr` contexts anyway.
The original commit message follows:
Make a few changes to the `FileEntryRef` API in preparation for
propagating it enough to remove `FileEntry::getName()`.
- Allow `FileEntryRef` to degrade implicitly to `const FileEntry*`. This
allows functions currently returning `const FileEntry *` to be updated
to return `FileEntryRef` without requiring all callers to be updated
in the same patch. This helps avoid both (a) massive patches where
many fields and locals are updated simultaneously and (b) noisy
incremental patches where the first patch adds `getFileEntry()` at
call sites and the second patch removes it. (Once `FileEntryRef` is
everywhere, we should remove this API.)
- Change `operator==` to compare the underlying `FileEntry*`, ignoring
any difference in the spelling of the filename. There were 0 users of
the existing function because it's not useful. In case comparing the
exact named reference becomes important, add/test `isSameRef`.
- Add `==` comparisons between `FileEntryRef` and `const FileEntry *`
(compares the `FileEntry*`).
- Customize `OptionalStorage<FileEntryRef>` to be pointer-sized. Add
a private constructor that initializes with `nullptr` and specialize
`OptionalStorage` to use it. This unblocks updating fields in
size-sensitive data structures that currently use `const FileEntry *`.
- Add `OptionalFileEntryRefDegradesToFileEntryPtr`, a wrapper around
`Optional<FileEntryRef>` that degrades to `const FileEntry*`. This
facilitates future incremental patches, like the same operator on
`FileEntryRef`. (Once `FileEntryRef` is everywhere, we should remove
this class.)
- Remove the unncessary `const` from the by-value return of
`FileEntryRef::getName`.
- Delete the unused function `FileEntry::isOpenForTests`.
Note that there are still `FileEntry` APIs that aren't wrapped and I
plan to deal with these separately / incrementally, as they are needed.
Differential Revision: https://reviews.llvm.org/D89834
This reverts commit 5530fb586f.
This reverts commit 010238a296.
This reverts commit 84e8257937.
Having trouble getting the bots compiling. Will try again later.
Make a few changes to the `FileEntryRef` API in preparation for
propagating it enough to remove `FileEntry::getName()`.
- Allow `FileEntryRef` to degrade implicitly to `const FileEntry*`. This
allows functions currently returning `const FileEntry *` to be updated
to return `FileEntryRef` without requiring all callers to be updated
in the same patch. This helps avoid both (a) massive patches where
many fields and locals are updated simultaneously and (b) noisy
incremental patches where the first patch adds `getFileEntry()` at
call sites and the second patch removes it. (Once `FileEntryRef` is
everywhere, we should remove this API.)
- Change `operator==` to compare the underlying `FileEntry*`, ignoring
any difference in the spelling of the filename. There were 0 users of
the existing function because it's not useful. In case comparing the
exact named reference becomes important, add/test `isSameRef`.
- Add `==` comparisons between `FileEntryRef` and `const FileEntry *`
(compares the `FileEntry*`).
- Customize `OptionalStorage<FileEntryRef>` to be pointer-sized. Add
a private constructor that initializes with `nullptr` and specialize
`OptionalStorage` to use it. This unblocks updating fields in
size-sensitive data structures that currently use `const FileEntry *`.
- Add `OptionalFileEntryRefDegradesToFileEntryPtr`, a wrapper around
`Optional<FileEntryRef>` that degrades to `const FileEntry*`. This
facilitates future incremental patches, like the same operator on
`FileEntryRef`. (Once `FileEntryRef` is everywhere, we should remove
this class.)
- Remove the unncessary `const` from the by-value return of
`FileEntryRef::getName`.
- Delete the unused function `FileEntry::isOpenForTests`.
Note that there are still `FileEntry` APIs that aren't wrapped and I
plan to deal with these separately / incrementally, as they are needed.
Differential Revision: https://reviews.llvm.org/D89834
Summary:
Skip over elidable nodes, and ensure that intermediate
CXXFunctionalCastExpr nodes are also skipped if they are semantic.
Reviewers: klimek, ymandel
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D82278
This patch is mainly doing two things:
1. Adding support for parentheses, making the combination of target features
more diverse;
2. Making the priority of ’,‘ is higher than that of '|' by default. So I need
to make some change with PTX Builtin function.
Differential Revision: https://reviews.llvm.org/D89184
This gives us slightly nicer syntax (foreach) for idioms currently expressed
as a loop, and the option to use range algorithms where it makes sense
(e.g. llvm::all_of et al encapsulate the needed flow control in a useful way).
It's also a building block for iteration over filtered views (e.g. iterate over
all Stmt children, with the right type):
for (const Statement &S : filter<Statement>(N.children()))
...
I realize the recent direction has been mostly towards strongly-typed
node-specific facilities, but I think it's important we have convenient
generic facilities too.
Differential Revision: https://reviews.llvm.org/D90023
Shrink `FileEntryRef` to the size of a pointer, by having it directly
reference the `StringMapEntry` the same way that `DirectoryEntryRef`
does. This makes `FileEntryRef::FileEntryRef` private as a side effect
(`FileManager` is a friend!).
There are two helper types added within `FileEntryRef`:
- `FileEntryRef::MapValue` is the type stored in
`FileManager::SeenFileEntries`. It's a replacement for
`SeenFileEntryOrRedirect`, where the second pointer type has been
changed from `StringRef*` to `MapEntry*` (see next bullet).
- `FileEntryRef::MapEntry` is the instantiation of `StringMapEntry<>`
where `MapValue` is stored. This is what `FileEntryRef` has a pointer
to, in order to grab the name in addition to the value.
Differential Revision: https://reviews.llvm.org/D89488
After D86959 the code `#define lambda [](const decltype(x) &ptr) {}`
was formatted as `#define lambda [](const decltype(x) & ptr) {}` due to
now parsing the '&' token as a BinaryOperator. The problem was caused by
the condition `Line.InPPDirective && (!Left->Previous || !Left->Previous->is(tok::identifier))) {`
being matched and therefore not performing the checks for "previous token
is one of decltype/_Atomic/etc.". This patch moves those checks after the
existing if/else chain to ensure the left-parent token classification is
always run after checking whether the contents of the parens is an
expression or not.
This change also introduces a new TokenAnnotatorTest that checks the
token kind and Role of Tokens after analyzing them. This is used to check
for TT_PointerOrReference, in addition to indirectly testing this based
on the resulting formatting.
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D88956
Put the guts of `ComputeLineNumbers` into `LineOffsetMapping::get` and
`LineOffsetMapping::LineOffsetMapping`. As a drive-by, store the number
of lines directly in the bump-ptr-allocated array.
Differential Revision: https://reviews.llvm.org/D89913
`SourceManager::isMainFile` does not use the filename, so it doesn't
need the full `FileEntryRef`; in fact, it's misleading to take the name
because that makes it look relevant. Simplify the API, and in the
process remove some calls to `FileEntryRef::FileEntryRef` in the unit
tests (which were blocking making that private to `SourceManager`).
Differential Revision: https://reviews.llvm.org/D89507
This functionality is commonly needed in clang tidy checks (based on
transformer) that only print warnings, without suggesting any edits. The no-op
edit allows the user to associate a diagnostic message with a source location.
Differential Revision: https://reviews.llvm.org/D89961
Some early errors during the ASTUnit creation were not transferred to the `FailedParseDiagnostic` so when the code in `LoadFromCommandLine` swaps its content with the content of `StoredDiagnostics` they cannot be retrieved by the user in any way.
Reviewed By: andrewrk, dblaikie
Differential Revision: https://reviews.llvm.org/D78658
Add a test demonstrating `getFileRef`'s behaviour, which isn't obvious
from code inspection when it's handling a redirected file.
Differential Revision: https://reviews.llvm.org/D89469
In order to drop the final callers to `SourceManager::getBuffer`, change
`FrontendInputFile` to use `Optional<MemoryBufferRef>`. Also updated
the "unowned" version of `SourceManager::createFileID` to take a
`MemoryBufferRef` (it now calls `MemoryBuffer::getMemBuffer`, which
creates a `MemoryBuffer` that does not own the buffer data).
Differential Revision: https://reviews.llvm.org/D89427
This allows building the clang-format unit tests in only 657 ninja steps
rather than 1257 which allows for much faster incremental builds after a
git pull.
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D89709
This allows removing the clangAST dependency from libclangToolingCore and
therefore allows clang-format to be built without depending on clangAST.
Before 1166 files had to be compiled for clang-format, now only 796.
Reviewed By: bkramer
Differential Revision: https://reviews.llvm.org/D89708
PartialDiagnostic misses some functions compared to DiagnosticBuilder.
This patch refactors DiagnosticBuilder and PartialDiagnostic, extracts
the common functionality so that the streaming << operators are
shared.
Differential Revision: https://reviews.llvm.org/D84362
Some projects (e.g. FreeBSD) align pointers to the right but expect a
space between the '*' and any pointer qualifiers such as const. To handle
these cases this patch adds a new config option SpaceAroundPointerQualifiers
that can be used to configure whether spaces need to be added before/after
pointer qualifiers.
PointerAlignment = Right
SpaceAroundPointerQualifiers = Default/After:
void *const *x = NULL;
SpaceAroundPointerQualifiers = Before/Both
void * const *x = NULL;
PointerAlignment = Left
SpaceAroundPointerQualifiers = Default/Before:
void* const* x = NULL;
SpaceAroundPointerQualifiers = After/Both
void* const * x = NULL;
PointerAlignment = Middle
SpaceAroundPointerQualifiers = Default/Before/After/Both:
void * const * x = NULL;
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D88227
ClangFormat does not correctly handle an Objective-C interface declaration
with both lightweight generics and a protocol conformance.
This simple example:
```
@interface Foo : Bar <Baz> <Blech>
@end
```
means `Foo` extends `Bar` (a lightweight generic class whose type
parameter is `Baz`) and also conforms to the protocol `Blech`.
ClangFormat should not apply any changes to the above example, but
instead it currently formats it quite poorly:
```
@interface Foo : Bar <Baz>
<Blech>
@end
```
The bug is that `UnwrappedLineParser` assumes an open-angle bracket
after a base class name is a protocol list, but it can also be a
lightweight generic specification.
This diff fixes the bug by factoring out the logic to parse
lightweight generics so it can apply both to the declared class
as well as the base class.
Test Plan: New tests added. Ran tests with:
% ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
Confirmed tests failed before diff and passed after diff.
Reviewed By: sammccall, MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D89496
Currently, `after` fails when applied to locations in macro arguments. This
change projects the subrange into a file source range and then applies `after`.
Differential Revision: https://reviews.llvm.org/D89468
Update clang-tools-extra, clang/tools, clang/unittests to migrate from
`SourceManager::getBuffer`, which returns an always dereferenceable
`MemoryBuffer*`, to `getBufferOrNone` or `getBufferOrFake`, both of
which return a `MemoryBufferRef`, depending on whether the call site was
checking for validity of the buffer. No functionality change intended.
Differential Revision: https://reviews.llvm.org/D89416
The argument passed to the preprocessor macros `NS_SWIFT_NAME(x)` and
`CF_SWIFT_NAME(x)` is stringified before passing to
`__attribute__((swift_name("x")))`.
ClangFormat didn't know about this stringification, so its custom parser
tried to parse the argument(s) passed to the macro as if they were
normal function arguments.
That means ClangFormat currently incorrectly inserts whitespace
between `NS_SWIFT_NAME` arguments with colons and dots, so:
```
extern UIWindow *MainWindow(void) NS_SWIFT_NAME(getter:MyHelper.mainWindow());
```
becomes:
```
extern UIWindow *MainWindow(void) NS_SWIFT_NAME(getter : MyHelper.mainWindow());
```
which clang treats as a parser error:
```
error: 'swift_name' attribute has invalid identifier for context name [-Werror,-Wswift-name-attribute]
```
Thankfully, D82620 recently added the ability to treat specific macros
as "whitespace sensitive", meaning their arguments are implicitly
treated as strings (so whitespace is not added anywhere inside).
This diff adds `NS_SWIFT_NAME` and `CF_SWIFT_NAME` to
`WhitespaceSensitiveMacros` so their arguments are implicitly treated
as whitespace-sensitive.
Test Plan:
New tests added. Ran tests with:
% ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewed By: sammccall
Differential Revision: https://reviews.llvm.org/D89425
During the import of attributes we forgot to set the spelling list
index. This caused a segfault when we wanted to traverse the AST
(e.g. by the dump() method).
Differential Revision: https://reviews.llvm.org/D89318
During the import of FormatAttrs we forgot to import the type (e.g
`__scanf__`) of the attribute. This caused a segfault when we wanted to
traverse the AST (e.g. by the dump() method).
Differential Revision: https://reviews.llvm.org/D89319
After D88666, which implemented DirectoryWatcher on Windows, we're
seeing test failures on Chromium's Windows bots.
Try raising the timeout in case the test is failing due to high load on
the machine.
This implements the directory watcher on Windows. It does the most
naive thing for simplicity. ReadDirectoryChangesW is used to monitor
the changes. However, in order to support interruption, we must use
overlapped IO, which allows us to use the blocking, synchronous
mechanism. We create a thread to post the notification to the consumer
to allow the monitoring to continue. The two threads communicate via a
locked queue.
Differential Revision: https://reviews.llvm.org/D88666
Reviewed By: Adrian McCarthy
The Callbacks.cpp test was taking a long time to compile on some build bots
causing timeouts. This patch splits up that test into five separate cpp
files and a header file.
Reviewed By: gribozavr2
Differential Revision: https://reviews.llvm.org/D88886
This patch extracts the ExprMutAnalyzer changes from https://reviews.llvm.org/D54943
into its own revision for simpler review and more atomic changes.
The analysis results are improved. Nested expressions (e.g. conditional
operators) are now detected properly. Some edge cases, especially
template induced imprecisions are improved upon.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D88088
Object of class `Command` contains various properties of a command to
execute, but output file was missed from them. This change adds this
property. It is required for reporting consumed time and memory implemented
in D78903 and may be used in other cases too.
Differential Revision: https://reviews.llvm.org/D78902
While debugging a different clang-format failure, I tried to reuse the
MacroExpander lexer, but was surprised to see that it marks all C++
keywords (e.g. const, decltype) as being of type identifier. After stepping
through the ::format() code, I noticed that the difference between these
two is that the identifier table was not being initialized based on the
FormatStyle, so only basic tokens such as tok::semi, tok::plus, etc. were
being handled.
Reviewed By: klimek
Differential Revision: https://reviews.llvm.org/D88952
After this change all nodes that have a delimited-list are using the
`List` API.
Implementation details:
Let's look at a declaration with multiple declarators:
`int a, b;`
To generate a declarator list node we need to have the range of
declarators: `a, b`:
However, the `ClangAST` actually stores them as separate declarations:
`int a ;`
`int b;`
We solve that by appropriately marking the declarators on each separate
declaration in the `ClangAST` and then for the final declarator `int
b`, shrinking its range to fit to the already marked declarators.
Differential Revision: https://reviews.llvm.org/D88403
Summary:
The MacroExpander allows to expand simple (non-resursive) macro
definitions from a macro identifier token and macro arguments. It
annotates the tokens with a newly introduced MacroContext that keeps
track of the role a token played in expanding the macro in order to
be able to reconstruct the macro expansion from an expanded (formatted)
token stream.
Made Token explicitly copy-able to enable copying tokens from the parsed
macro definition.
Reviewers: sammccall
Subscribers: mgorny, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D83296
For /C++/ constructor initializers `ExprEngine:computeUnderConstruction()`
asserts that they are all member initializers. This is not neccessarily
true when this function is used to get the return value for the
construction context thus attempts to fetch return values of base and
delegating constructor initializers result in assertions. This small
patch fixes this issue.
Differential Revision: https://reviews.llvm.org/D85351
Currently, when marshaling a dynamic AST matchers, we check for the type
and value validity of matcher arguments at the same time for some matchers.
For instance, when marshaling hasAttr("foo"), the argument is first type
checked to ensure it's a string and then checked to see if that string can
locate an attribute with that name. Similar happens for other enumeration
conversions like cast kinds or unary operator kinds. If the type is
correct but the value cannot be looked up, we make a best-effort attempt
to find a nearby name that the user might have meant, but if one cannot
be found, we throw our hands up and claim the types don't match.
This has an unfortunate behavior that when the user enters something of
the correct type but a best guess cannot be located, you get confusing
error messages like:
Incorrect type for arg 1. (Expected = string) != (Actual = String).
This patch splits the argument check into two parts: if the types don't
match, give a type diagnostic. If the type matches but the value cannot
be converted, give a best guess diagnostic or a value could not be
located diagnostic. This addresses PR47057.
There can be Macros that are tagged with `modifiable`. Thus verifying
`canModifyAllDescendants` is not sufficient to avoid macros when deep
copying.
We think the `TokenBuffer` could inform us whether a `Token` comes from
a macro. We'll look into that when we can surface this information
easily, for instance in unit tests for `ComputeReplacements`.
Differential Revision: https://reviews.llvm.org/D88034
* Introduce `TreeTest.cpp` to unit test `Tree.h`
* Add `generateAllTreesWithShape` to generating test cases
* Add tests for `findFirstLeaf` and `findLastLeaf`
* Fix implementations of `findFirstLeaf` and `findLastLeaf` that had
been broken when empty `Tree` were present.
Differential Revision: https://reviews.llvm.org/D87779
There are several `::IsStructurallyEquivalent` overloads for Decl subclasses
that are used for comparing declarations. There is also one overload that takes
just two Decl pointers which ends up queuing the passed Decls to be later
compared in `CheckKindSpecificEquivalence`.
`CheckKindSpecificEquivalence` implements the dispatch logic for the different
Decl subclasses. It is supposed to hand over the queued Decls to the
subclass-specific `::IsStructurallyEquivalent` overload that will actually
compare the Decl instance. It also seems to implement a few pieces of actual
node comparison logic inbetween the dispatch code.
This implementation causes that the different overloads of
`::IsStructurallyEquivalent` do different (and sometimes no) comparisons
depending on which overload of `::IsStructurallyEquivalent` ends up being
called.
For example, if I want to compare two FieldDecl instances, then I could either
call the `::IsStructurallyEquivalent` with `Decl *` or with `FieldDecl *`
parameters. The overload that takes FieldDecls is doing a correct comparison.
However, the `Decl *` overload just queues the Decl pair.
`CheckKindSpecificEquivalence` has no dispatch logic for `FieldDecl`, so it
always returns true and never does any actual comparison.
On the other hand, if I try to compare two FunctionDecl instances the two
possible overloads of `::IsStructurallyEquivalent` have the opposite behaviour:
The overload that takes `FunctionDecl` pointers isn't comparing the names of the
FunctionDecls while the overload taking a plain `Decl` ends up comparing the
function names (as the comparison logic for that is implemented in
`CheckKindSpecificEquivalence`).
This patch tries to make this set of functions more consistent by making
`CheckKindSpecificEquivalence` a pure dispatch function without any
subclass-specific comparison logic. Also the dispatch logic is now autogenerated
so it can no longer miss certain subclasses.
The comparison code from `CheckKindSpecificEquivalence` is moved to the
respective `::IsStructurallyEquivalent` overload so that the comparison result
no longer depends if one calls the `Decl *` overload or the overload for the
specific subclass. The only difference is now that the `Decl *` overload is
queuing the parameter while the subclass-specific overload is directly doing the
comparison.
`::IsStructurallyEquivalent` is an implementation detail and I don't think the
behaviour causes any bugs in the current implementation (as carefully calling
the right overload for the different classes works around the issue), so the
test for this change is that I added some new code for comparing `MemberExpr`.
The new comparison code always calls the dispatching overload and it previously
failed as the dispatch didn't support FieldDecls.
Reviewed By: martong, a_sidorin
Differential Revision: https://reviews.llvm.org/D87619
Currently newer clang-format options cannot be included in .clang-format files, if not all users can be forced to use an updated version.
This patch tries to solve this by adding an option to clang-format, enabling to ignore unknown (newer) options.
Differential Revision: https://reviews.llvm.org/D86137
Some Java style guides and IDEs group Java static imports after
non-static imports. This patch allows clang-format to control
the location of static imports.
Patch by: @bc-lee
Reviewed By: MyDeveloperDay, JakeMerdichAMD
Differential Revision: https://reviews.llvm.org/D87201
https://bugs.llvm.org/show_bug.cgi?id=47461
The following change {D80940} caused a regression in code which ifdef's around the try and catch block cause incorrect brace placement around the catch
```
try
{
}
catch (...) {
// This is not a small function
bar = 1;
}
}
```
The brace after the catch will be placed on a newline
Reviewed By: curdeius
Differential Revision: https://reviews.llvm.org/D87291
//AST Matcher// `hasBody` is a polymorphic matcher that behaves
differently for loop statements and function declarations. The main
difference is the for functions declarations it does not only call
`FunctionDecl::getBody()` but first checks whether the declaration in
question is that specific declaration which has the body by calling
`FunctionDecl::doesThisDeclarationHaveABody()`. This is achieved by
specialization of the template `GetBodyMatcher`. Unfortunately template
specializations do not catch the descendants of the class for which the
template is specialized. Therefore it does not work correcly for the
descendants of `FunctionDecl`, such as `CXXMethodDecl`,
`CXXConstructorDecl`, `CXXDestructorDecl` etc. This patch fixes this
issue by using a template metaprogram.
The patch also introduces a new matcher `hasAnyBody` which matches
declarations which have a body present in the AST but not necessarily
belonging to that particular declaration.
Differential Revision: https://reviews.llvm.org/D87527
The analysis for const-ness of local variables required a view generally useful
matchers that are extracted into its own patch.
They are decompositionDecl and forEachArgumentWithParamType, that works
for calls through function pointers as well.
This is a reupload of https://reviews.llvm.org/D72505, that already landed,
but had to be reverted due to a GCC crash on powerpc
(https://reviews.llvm.org/rG4c48ea68e491cb42f1b5d43ffba89f6a7f0dadc4)
Because this took a long time to adress, i decided to redo this patch and
have a clean workflow.
I try to coordinate with someone that has a PPC to apply this patch and
test for the crash. If everything is fine, I intend to just commit.
If the crash is still happening, i hope to at least find the cause.
Differential Revision: https://reviews.llvm.org/D87588
Right now the ASTImporter assumes for most Expr nodes that they are always equal
which leads to non-compatible declarations ending up being merged. This patch
adds the basic framework for comparing Stmts (and with that also Exprs) and
implements the custom checks for a few Stmt subclasses. I'll implement the
remaining subclasses in follow up patches (mostly because there are a lot of
subclasses and some of them require further changes like having GNU language in
the testing framework)
The motivation for this is that in LLDB we try to import libc++ source code and
some of the types we are importing there contain expressions (e.g. because they
use `enable_if<expr>`), so those declarations are currently merged even if they
are completely different (e.g. `enable_if<value> ...` and `enable_if<!value>
...` are currently considered equal which is clearly not true).
Reviewed By: martong, balazske
Differential Revision: https://reviews.llvm.org/D87444
In a future patch
* Implement helper function to generate Trees for tests
* and test Tree methods, namely `findFirstLeaf` and `findLastLeaf`
Differential Revision: https://reviews.llvm.org/D87533
Summary:
This is the first patch implementing the new Flang driver as outlined in [1],
[2] & [3]. It creates Flang driver (`flang-new`) and Flang frontend driver
(`flang-new -fc1`). These will be renamed as `flang` and `flang -fc1` once the
current Flang throwaway driver, `flang`, can be replaced with `flang-new`.
Currently only 2 options are supported: `-help` and `--version`.
`flang-new` is implemented in terms of libclangDriver, defaulting the driver
mode to `FlangMode` (added to libclangDriver in [4]). This ensures that the
driver runs in Flang mode regardless of the name of the binary inferred from
argv[0].
The design of the new Flang compiler and frontend drivers is inspired by it
counterparts in Clang [3]. Currently, the new Flang compiler and frontend
drivers re-use Clang libraries: clangBasic, clangDriver and clangFrontend.
To identify Flang options, this patch adds FlangOption/FC1Option enums.
Driver::printHelp is updated so that `flang-new` prints only Flang options.
The new Flang driver is disabled by default. To enable it, set
`-DBUILD_FLANG_NEW_DRIVER=ON` when configuring CMake and add clang to
`LLVM_ENABLE_PROJECTS` (e.g. -DLLVM_ENABLE_PROJECTS=“clang;flang;mlir”).
[1] “RFC: new Flang driver - next steps”
http://lists.llvm.org/pipermail/flang-dev/2020-July/000470.html
[2] “RFC: Adding a fortran mode to the clang driver for flang”
http://lists.llvm.org/pipermail/cfe-dev/2019-June/062669.html
[3] “RFC: refactoring libclangDriver/libclangFrontend to share with Flang”
http://lists.llvm.org/pipermail/cfe-dev/2020-July/066393.html
[4] https://reviews.llvm.org/rG6bf55804924d5a1d902925ad080b1a2b57c5c75c
co-authored-by: Andrzej Warzynski <andrzej.warzynski@arm.com>
Reviewed By: richard.barton.arm, sameeranjoshi
Differential Revision: https://reviews.llvm.org/D86089
In some situation shifts can be treated as a template, and is thus formatted as one. So, by doing a couple extra checks to assure that the condition doesn't contain a template, and is in fact a bit shift should solve this problem.
This is a fix for [[ https://bugs.llvm.org/show_bug.cgi?id=46969 | bug 46969 ]]
Reviewed By: MyDeveloperDay
Patch By: Saldivarcher
Differential Revision: https://reviews.llvm.org/D86581
* Do not visit `CXXDefaultArgExpr`
* To build `CallArguments` nodes, just go through non-default arguments
Differential Revision: https://reviews.llvm.org/D87249
MSVC's cl.exe has a few command line arguments which start with -M such
as "-MD", "-MDd", "-MT", "-MTd", "-MP".
These arguments are not dependency file generation related, and these
arguments were being removed by getClangStripDependencyFileAdjuster()
which was wrong.
Differential revision: https://reviews.llvm.org/D86999
Decl::dump is primarily used for debugging to visualise the current state of a
declaration. Usually Decl::dump just displays the current state of the Decl and
doesn't actually change any of its state, however since commit
457226e02a the method actually started loading
additional declarations from the ExternalASTSource. This causes that calling
Decl::dump during a debugging session now actually does permanent changes to the
AST and will cause the debugged program run to deviate from the original run.
The change that caused this behaviour is the addition of
`hasConstexprDestructor` (which is called from the TextNodeDumper) which
performs a lookup into the current CXXRecordDecl to find the destructor. All
other similar methods just return their respective bit in the DefinitionData
(which obviously doesn't have such side effects).
This just changes the node printer to emit "unknown_constexpr" in case a
CXXRecordDecl is dumped that could potentially call into the ExternalASTSource
instead of the usually empty string/"constexpr". For CXXRecordDecls that can
safely be dumped the old behaviour is preserved
Reviewed By: bruno
Differential Revision: https://reviews.llvm.org/D80878
When using the always break after return type setting:
Before:
SomeType funcdecl(LIST(uint64_t));
After:
SomeType
funcdecl(LIST(uint64_t));"
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D87007
Before: _Atomic(uint64_t) * a;
After: _Atomic(uint64_t) *a;
This treats _Atomic the same as the the TypenameMacros and decltype. It
also allows some cleanup by removing checks whether the token before a
paren is kw_decltype and instead checking for TT_TypeDeclarationParen.
While touching this code also extend the decltype test cases to also check
for typeof() and _Atomic(T).
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D86959
This adds a `AttributeMacros` configuration option that causes certain
identifiers to be parsed like a __attribute__((foo)) annotation.
This is motivated by our CHERI C/C++ fork which adds a __capability
qualifier for pointer/reference. Without this change clang-format parses
many type declarations as multiplications/bitwise-and instead.
I initially considered adding "__capability" as a new clang-format keyword,
but having a list of macros that should be treated as attributes is more
flexible since it can be used e.g. for static analyzer annotations or other language
extensions.
Example: std::vector<foo * __capability> -> std::vector<foo *__capability>
Depends on D86775 (to apply cleanly)
Reviewed By: MyDeveloperDay, jrtc27
Differential Revision: https://reviews.llvm.org/D86782
Currently a test failure always reports a line number inside verifyFormat()
which is not very helpful to see which test failed. With this change we now
emit the line number where the verify function was called. When using an
IDE such as CLion, the output now includes a clickable link that points to
the call site.
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D86926
The new overloads apply directly to a node, like the
`clang::ast_matchers::match` functions, Rather than generating an
`EditGenerator` combinator.
Differential Revision: https://reviews.llvm.org/D87031
This patch restores the default traversal for Transformer's `makeRule` to
`TK_AsIs`. The implicit mode has proven problematic.
Differential Revision: https://reviews.llvm.org/D87048