[PATCH] D87080: [AST] Reduce the size of TemplateArgumentLocInfo.

2020-09-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/include/clang/AST/TemplateBase.h:429
+  auto *T = getTemplate();
+  T->Ctx->Deallocate(T);
+}

sammccall wrote:
> sammccall wrote:
> > this is a no-op, and thus not worth stashing a pointer to Ctx for!
> > 
> > It also doesn't delete T, and it's probably best to do that even if it's 
> > (currently) a no-op
> If you're going to destroy T in the destructor, then you can't have trivial 
> copies, as the second one is pointing at deallocated memory.
> (Well, apart from the fact that deallocation does nothing).
> 
> So I think we probably either want:
>  - allocation on ASTContext, trivial copies, no deallocation
>  - allocation on heap, copies reallocate
>  - allocation on heap using shared_ptr
>  - copies disallowed (but I think we rely on them being available)
chose the first one. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87080/new/

https://reviews.llvm.org/D87080

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 70523ec - [Sparc] Select the UltraSPARC instruction set with the external assembler

2020-09-07 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2020-09-07T02:49:05-04:00
New Revision: 70523ecfaca692bf5d0192e466c34ae7514624ea

URL: 
https://github.com/llvm/llvm-project/commit/70523ecfaca692bf5d0192e466c34ae7514624ea
DIFF: 
https://github.com/llvm/llvm-project/commit/70523ecfaca692bf5d0192e466c34ae7514624ea.diff

LOG: [Sparc] Select the UltraSPARC instruction set with the external assembler

Select the UltraSPARC instruction set with the external assembler on
Linux / FreeBSD / OpenBSD, matches GCC.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Arch/Sparc.cpp
clang/test/Driver/freebsd.c
clang/test/Driver/linux-as.c
clang/test/Driver/openbsd.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp 
b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
index 043b7f257c01..70ba8eb2a7d0 100644
--- a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
@@ -21,12 +21,19 @@ using namespace llvm::opt;
 const char *sparc::getSparcAsmModeForCPU(StringRef Name,
  const llvm::Triple &Triple) {
   if (Triple.getArch() == llvm::Triple::sparcv9) {
+const char *DefV9CPU;
+
+if (Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD())
+  DefV9CPU = "-Av9a";
+else
+  DefV9CPU = "-Av9";
+
 return llvm::StringSwitch(Name)
 .Case("niagara", "-Av9b")
 .Case("niagara2", "-Av9b")
 .Case("niagara3", "-Av9d")
 .Case("niagara4", "-Av9d")
-.Default("-Av9");
+.Default(DefV9CPU);
   } else {
 return llvm::StringSwitch(Name)
 .Case("v8", "-Av8")

diff  --git a/clang/test/Driver/freebsd.c b/clang/test/Driver/freebsd.c
index 769bb22da0dc..1bf6dab802a1 100644
--- a/clang/test/Driver/freebsd.c
+++ b/clang/test/Driver/freebsd.c
@@ -176,7 +176,7 @@
 // RUN: %clang -mcpu=ultrasparc -target sparc64-unknown-freebsd8 %s -### 
-no-integrated-as 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-SPARC-CPU %s
 // CHECK-SPARC-CPU: cc1{{.*}}" "-target-cpu" "ultrasparc"
-// CHECK-SPARC-CPU: as{{.*}}" "-Av9
+// CHECK-SPARC-CPU: as{{.*}}" "-Av9a
 
 // Check that -G flags are passed to the linker for mips
 // RUN: %clang -target mips-unknown-freebsd %s -### -G0 2>&1 \

diff  --git a/clang/test/Driver/linux-as.c b/clang/test/Driver/linux-as.c
index 77ac05f30942..0959bd7ba0a1 100644
--- a/clang/test/Driver/linux-as.c
+++ b/clang/test/Driver/linux-as.c
@@ -168,7 +168,7 @@
 // RUN:   | FileCheck -check-prefix=CHECK-SPARCV9 %s
 // CHECK-SPARCV9: as
 // CHECK-SPARCV9: -64
-// CHECK-SPARCV9: -Av9
+// CHECK-SPARCV9: -Av9a
 // CHECK-SPARCV9-NOT: -KPIC
 // CHECK-SPARCV9: -o
 //
@@ -177,7 +177,7 @@
 // RUN:   | FileCheck -check-prefix=CHECK-SPARCV9PIC %s
 // CHECK-SPARCV9PIC: as
 // CHECK-SPARCV9PIC: -64
-// CHECK-SPARCV9PIC: -Av9
+// CHECK-SPARCV9PIC: -Av9a
 // CHECK-SPARCV9PIC: -KPIC
 // CHECK-SPARCV9PIC: -o
 //

diff  --git a/clang/test/Driver/openbsd.c b/clang/test/Driver/openbsd.c
index 203b4b4a2ff0..ae1aa6441690 100644
--- a/clang/test/Driver/openbsd.c
+++ b/clang/test/Driver/openbsd.c
@@ -70,7 +70,7 @@
 // RUN:   | FileCheck -check-prefix=CHECK-MIPS64EL-PIC %s
 // CHECK-AMD64-M32: as{{.*}}" "--32"
 // CHECK-POWERPC: as{{.*}}" "-mppc" "-many"
-// CHECK-SPARC64: as{{.*}}" "-64" "-Av9"
+// CHECK-SPARC64: as{{.*}}" "-64" "-Av9a"
 // CHECK-MIPS64: as{{.*}}" "-mabi" "64" "-EB"
 // CHECK-MIPS64-PIC: as{{.*}}" "-mabi" "64" "-EB" "-KPIC"
 // CHECK-MIPS64EL: as{{.*}}" "-mabi" "64" "-EL"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b3205e2 - [scan-view] Explicitly use utf-8 in send_string

2020-09-07 Thread via cfe-commits

Author: Tomas Rix
Date: 2020-09-07T09:26:38+02:00
New Revision: b3205e2ace4378600dedba0cc5a42b481c4e22c9

URL: 
https://github.com/llvm/llvm-project/commit/b3205e2ace4378600dedba0cc5a42b481c4e22c9
DIFF: 
https://github.com/llvm/llvm-project/commit/b3205e2ace4378600dedba0cc5a42b481c4e22c9.diff

LOG: [scan-view] Explicitly use utf-8 in send_string

send_patched_file decodes with utf-8.
The default encoder for python 2 is ascii.

So it is necessary to also change send_string to use utf-8.

Differential Revision: https://reviews.llvm.org/D83984

Added: 


Modified: 
clang/tools/scan-view/share/ScanView.py

Removed: 




diff  --git a/clang/tools/scan-view/share/ScanView.py 
b/clang/tools/scan-view/share/ScanView.py
index a6cc7692ffe0..5a5d15e85b30 100644
--- a/clang/tools/scan-view/share/ScanView.py
+++ b/clang/tools/scan-view/share/ScanView.py
@@ -744,7 +744,7 @@ def send_file(self, f, ctype):
 return f
 
 def send_string(self, s, ctype='text/html', headers=True, mtime=None):
-encoded_s = s.encode()
+encoded_s = s.encode('utf-8')
 if headers:
 self.send_response(200)
 self.send_header("Content-type", ctype)



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83984: Explicitly use utf-8 in send_string

2020-09-07 Thread serge via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb3205e2ace43: [scan-view] Explicitly use utf-8 in 
send_string (authored by Tomas Rix , committed by 
serge-sans-paille).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D83984/new/

https://reviews.llvm.org/D83984

Files:
  clang/tools/scan-view/share/ScanView.py


Index: clang/tools/scan-view/share/ScanView.py
===
--- clang/tools/scan-view/share/ScanView.py
+++ clang/tools/scan-view/share/ScanView.py
@@ -744,7 +744,7 @@
 return f
 
 def send_string(self, s, ctype='text/html', headers=True, mtime=None):
-encoded_s = s.encode()
+encoded_s = s.encode('utf-8')
 if headers:
 self.send_response(200)
 self.send_header("Content-type", ctype)


Index: clang/tools/scan-view/share/ScanView.py
===
--- clang/tools/scan-view/share/ScanView.py
+++ clang/tools/scan-view/share/ScanView.py
@@ -744,7 +744,7 @@
 return f
 
 def send_string(self, s, ctype='text/html', headers=True, mtime=None):
-encoded_s = s.encode()
+encoded_s = s.encode('utf-8')
 if headers:
 self.send_response(200)
 self.send_header("Content-type", ctype)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83984: Explicitly use utf-8 in send_string

2020-09-07 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

Commited on your behalf using what I expect to be your official email address 
:-)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D83984/new/

https://reviews.llvm.org/D83984

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-09-07 Thread James Henderson via Phabricator via cfe-commits
jhenderson added a comment.

Not that I have anything particularly against this, but won't this likely rot 
fairly rapidly? It's not like LLVM is even on C++17 let alone C++20 yet, so 
trying to make it work like the latter when it's just going to break again 
seems a bit like wasted effort to me.




Comment at: llvm/tools/llvm-objdump/llvm-objdump.cpp:805-817
+  return IsASCII ? "^" : (const char *)u8"\u2548";
 case LineChar::RangeMid:
-  return IsASCII ? "|" : u8"\u2503";
+  return IsASCII ? "|" : (const char *)u8"\u2503";
 case LineChar::RangeEnd:
-  return IsASCII ? "v" : u8"\u253b";
+  return IsASCII ? "v" : (const char *)u8"\u253b";
 case LineChar::LabelVert:
+  return IsASCII ? "|" : (const char *)u8"\u2502";

This seems unrelated to comparison checking?



Comment at: llvm/unittests/ADT/STLExtrasTest.cpp:465
   // Check fancy pointer overload for unique_ptr
+  // Parenthesizing to_address to avoid ADL finding std::to_address
   std::unique_ptr V2 = std::make_unique(0);

Nit: trailing full stop.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D78938/new/

https://reviews.llvm.org/D78938

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87081: [analyzer][StdLibraryFunctionsChecker] Elaborate the summary of fread and fwrite

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D87081#2256636 , @balazske wrote:

> This checker will make an additional assumption on `fread` and `fwrite` with 
> the ReturnValueCondition.

There is nothing new in that. This assumption described by the `.Case` has been 
here since the inception of this Checker. This patch does not change it. This 
patch adds two new argument constraints.

> The return value is constrained by `StreamChecker` too but it splits the 
> error (if returned value is less that arg 3) and non-error cases into 
> separate branches. I think this causes no problem because it will refine the 
> assumption made here (if this assumption is made first) or the assumption 
> here has no effect (if the split happened already).

Either way, this is not a problem. However, in a similar case with the 
CallAndMessage Checker, we decided to list the more specific Checker as a 
dependency. We could do that with StreamChecker too, if you think that's better 
that way. But I'd rather keep that as it is now, since as you suggests, it 
works now and will work even after this patch.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87081/new/

https://reviews.llvm.org/D87081

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 04ea680 - [cmake] Fix build of attribute plugin example on Windows

2020-09-07 Thread Kristina Bessonova via cfe-commits

Author: Kristina Bessonova
Date: 2020-09-07T10:04:32+02:00
New Revision: 04ea680a8ccc4f9a4d7333cd712333960348c35b

URL: 
https://github.com/llvm/llvm-project/commit/04ea680a8ccc4f9a4d7333cd712333960348c35b
DIFF: 
https://github.com/llvm/llvm-project/commit/04ea680a8ccc4f9a4d7333cd712333960348c35b.diff

LOG: [cmake] Fix build of attribute plugin example on Windows

Seems '${cmake_2_8_12_PRIVATE}' was removed a long time ago, so it should
be just PRIVATE keyword here.

Reviewed By: john.brawn

Differential Revision: https://reviews.llvm.org/D86091

Added: 


Modified: 
clang/examples/Attribute/CMakeLists.txt

Removed: 




diff  --git a/clang/examples/Attribute/CMakeLists.txt 
b/clang/examples/Attribute/CMakeLists.txt
index ed02f5e5992f..42f04f5039bc 100644
--- a/clang/examples/Attribute/CMakeLists.txt
+++ b/clang/examples/Attribute/CMakeLists.txt
@@ -1,7 +1,7 @@
 add_llvm_library(Attribute MODULE Attribute.cpp PLUGIN_TOOL clang)
 
 if(LLVM_ENABLE_PLUGINS AND (WIN32 OR CYGWIN))
-  target_link_libraries(Attribute ${cmake_2_8_12_PRIVATE}
+  target_link_libraries(Attribute PRIVATE
 clangAST
 clangBasic
 clangFrontend



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-07 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/Headers/intrin.h:435
 #if defined(__i386__) || defined(__x86_64__)
-static __inline__ void __DEFAULT_FN_ATTRS
-__movsb(unsigned char *__dst, unsigned char const *__src, size_t __n) {
+void __DEFAULT_FN_ATTRS __movsb(unsigned char *__dst,
+unsigned char const *__src, size_t __n) {

The functions with inline definitions should still be `static inline` so that 
we don't emit them as strong external defintiions.



Comment at: clang/lib/Sema/SemaDecl.cpp:9672-9673
+  if (unsigned BuiltinID = II->getBuiltinID()) {
+const auto *LinkageDecl =
+dyn_cast(NewFD->getDeclContext());
+

This will give the wrong answer for
```
extern "C" {
namespace X {
void __builtin_foo();
}
}
```
... which does have C language linkage. Instead, please call 
`FunctionDecl::getLanguageLinkage()`, which knows how to handle these cases.



Comment at: clang/lib/Sema/SemaDecl.cpp:9690-9691
+if (!Error && !BuiltinType.isNull()) {
+  // We want noexcept declarations to match. Create an identical
+  // function type, but remove the exception spec.
+  const FunctionProtoType *Type =

Please use `ASTContext::hasSameTypeIgnoringExceptionSpec` instead.



Comment at: clang/lib/Serialization/ASTReader.cpp:914
+  return II.hadMacroDefinition() || II.isPoisoned() ||
+ II.getObjCOrBuiltinID() || II.hasRevertedTokenIDToIdentifier() ||
  (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&

We now consider `getObjCOrBuiltinID()` here for the `IsModule` case, where we 
didn't before. Is that an intentional change?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77491/new/

https://reviews.llvm.org/D77491

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86091: [cmake] Fix build of attribute plugin example on Windows

2020-09-07 Thread Kristina Bessonova via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG04ea680a8ccc: [cmake] Fix build of attribute plugin example 
on Windows (authored by krisb).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86091/new/

https://reviews.llvm.org/D86091

Files:
  clang/examples/Attribute/CMakeLists.txt


Index: clang/examples/Attribute/CMakeLists.txt
===
--- clang/examples/Attribute/CMakeLists.txt
+++ clang/examples/Attribute/CMakeLists.txt
@@ -1,7 +1,7 @@
 add_llvm_library(Attribute MODULE Attribute.cpp PLUGIN_TOOL clang)
 
 if(LLVM_ENABLE_PLUGINS AND (WIN32 OR CYGWIN))
-  target_link_libraries(Attribute ${cmake_2_8_12_PRIVATE}
+  target_link_libraries(Attribute PRIVATE
 clangAST
 clangBasic
 clangFrontend


Index: clang/examples/Attribute/CMakeLists.txt
===
--- clang/examples/Attribute/CMakeLists.txt
+++ clang/examples/Attribute/CMakeLists.txt
@@ -1,7 +1,7 @@
 add_llvm_library(Attribute MODULE Attribute.cpp PLUGIN_TOOL clang)
 
 if(LLVM_ENABLE_PLUGINS AND (WIN32 OR CYGWIN))
-  target_link_libraries(Attribute ${cmake_2_8_12_PRIVATE}
+  target_link_libraries(Attribute PRIVATE
 clangAST
 clangBasic
 clangFrontend
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87081: [analyzer][StdLibraryFunctionsChecker] Elaborate the summary of fread and fwrite

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

The patch looks great, in fact, it demonstrates how well thought out your 
summary crafting machinery is.

In D87081#2258579 , @martong wrote:

> However, in a similar case with the CallAndMessage Checker, we decided to 
> list the more specific Checker as a dependency.

We got the answer to D77061#2057063 ! 
We should turn it into a weak dependency though (D80905 
).

In D87081#2256636 , @balazske wrote:

> This checker will make an additional assumption on `fread` and `fwrite` with 
> the ReturnValueCondition. The return value is constrained by `StreamChecker` 
> too but it splits the error (if returned value is less that arg 3) and 
> non-error cases into separate branches. I think this causes no problem 
> because it will refine the assumption made here (if this assumption is made 
> first) or the assumption here has no effect (if the split happened already).

Be sure to triple check whether the `ExplodedGraph` looks okay with both 
checkers enabled.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87081/new/

https://reviews.llvm.org/D87081

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85351: [Analyzer] Fix for `ExprEngine::computeObjectUnderConstruction()` for base and delegating consturctor initializers

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

The tests look great, thanks! I still lack the confidence to accept, 
unfortunately.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85351/new/

https://reviews.llvm.org/D85351

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87201: [clang-format] Add a option for the position of Java static import

2020-09-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay requested changes to this revision.
MyDeveloperDay added a comment.
This revision now requires changes to proceed.

Thanks for the patch, You need to generate a fill context diff (see 
Contributing to LLVM)

ensure the diff is clang-formatted itself (can't quite tell if it is or not)




Comment at: clang/docs/ClangFormatStyleOptions.rst:2027
+
+ .. code-block:: java
+ true:

The ClangFormatStyleOptions.rst is generated using 
doc/tools/dump_format_style.py which reads Format.h and generates this,

If this code block in not in the Format.h it will get removed the next time the 
script is run, please don't change ClangFormatStyleOption.rst by hand use the 
script, so add the code block to the Format.h file (see others options for now 
to do this)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87201/new/

https://reviews.llvm.org/D87201

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86137: Add ignore-unknown-options flag to clang-format.

2020-09-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added subscribers: sammccall, JDevlieghere, aaron.ballman.
MyDeveloperDay added a comment.

> Regarding not touching the LLVM support library: I'd love to find a way, but 
> as clang-format uses the >> operator

We need to find some reviewers who look after a wider area of LLVM, if you want 
to make a change out there in LLVM/support, but it above my pay grade to 
approve ;-) maybe one of the more experienced devs could help identify the 
correct person @aaron.ballman @sammccall or alternatively take a look via git 
log as to who has been maintaining that file @JDevlieghere, they may have an 
opinion about how this should be done.




Comment at: clang/tools/clang-format/ClangFormat.cpp:108
+static cl::opt
+IgnoreUnkownOptions("ignore-unknown-options",
+cl::desc("If set, unknown format options are 
ignored."),

feels like a mouthful is there nothing shorter we could use?  -Wignore (or 
something)



Comment at: llvm/include/llvm/Support/YAMLTraits.h:792
   virtual void setError(const Twine &) = 0;
+  virtual void setIgnoreUnknown(bool) = 0;
 

I'm not a massive fan of functions with out parameter names, but I see your 
following the local style.



Comment at: llvm/include/llvm/Support/YAMLTraits.h:1520
   boolScalarMatchFound = false;
+  bool IgnoreUnkown = false;
 };

is this clang-formatted?



Comment at: llvm/lib/Support/YAMLTraits.cpp:199
+  if (IgnoreUnkown)
+return;
   for (const auto &NN : MN->Mapping) {

do we want to flat out ignore or just report but not fatally. (just a thought) 
silent failures are hard to diagnose


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86137/new/

https://reviews.llvm.org/D86137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87028: [clang-format] Improve heuristic for detecting function declarations

2020-09-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thanks for the patch, I think this looks like a comprehensive improvement, a 
new nits only




Comment at: clang/lib/Format/TokenAnnotator.cpp:2427
+  // inside a function this should always be treated as a variable.
+  return CouldBeTypeList && Line.Level == 0;
 }

how hard would it be to do the TODO?



Comment at: clang/unittests/Format/FormatTest.cpp:5507
+  Google);
   verifyGoogleFormat(
   "bool aa GUARDED_BY() =\n"

I want to approve this change, but I HATE changing unit tests (Beyonce rule), 
I'm struggling to see if we are changing anything here? or if you are just 
qualifying it a little better because the usage is different depending on where 
its used  (as a function,as a variable)




Comment at: clang/unittests/Format/FormatTest.cpp:6715
+   "funcdecl(SomeType param1, OtherType param2);\n"
+   // Also handle parameter lists declaration without names (but
+   // only at the top level, not inside functions

if you have to put a comment in the test then you probably should have broken 
the verifyFormat



Comment at: clang/unittests/Format/FormatTest.cpp:6730
+   "SomeType x = var * funcdecl(var, otherVar);\n"
+   "void\n"
+   "function_scope() {\n"

break it here



Comment at: clang/unittests/Format/FormatTest.cpp:6740
+   "  SomeType *funcdecl(SomeType, OtherType);\n"
+   "}\n"
+   "namespace namspace_scope {\n"

break it here.



Comment at: clang/unittests/Format/FormatTest.cpp:6762
+   "} // namespace namspace_scope\n",
+   Style);
   verifyFormat("class E {\n"

Nit that is a mother of an assert, but when it fails.. how easy is it going to 
be to debug where it goes wrong exactly.

Could we break it up a little?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87028/new/

https://reviews.llvm.org/D87028

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87028: [clang-format] Improve heuristic for detecting function declarations

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:2427
+  // inside a function this should always be treated as a variable.
+  return CouldBeTypeList && Line.Level == 0;
 }

MyDeveloperDay wrote:
> how hard would it be to do the TODO?
I am not that familiar with the clang-format codebase yet, but it appears to me 
that this information is not tracked at all. It should be quite easy to add 
another `Scope` (or similar) member that is an enum for 
global/function/namespace/class/other and then update that in all cases that 
also change the level member.



Comment at: clang/unittests/Format/FormatTest.cpp:5507
+  Google);
   verifyGoogleFormat(
   "bool aa GUARDED_BY() =\n"

MyDeveloperDay wrote:
> I want to approve this change, but I HATE changing unit tests (Beyonce rule), 
> I'm struggling to see if we are changing anything here? or if you are just 
> qualifying it a little better because the usage is different depending on 
> where its used  (as a function,as a variable)
> 
Before a non-empty `()` with a single indentifier inside was always treated as 
a variable, with this change it's (in this case incorrectly) parsed as function.



Comment at: clang/unittests/Format/FormatTest.cpp:6762
+   "} // namespace namspace_scope\n",
+   Style);
   verifyFormat("class E {\n"

MyDeveloperDay wrote:
> Nit that is a mother of an assert, but when it fails.. how easy is it going 
> to be to debug where it goes wrong exactly.
> 
> Could we break it up a little?
`I agree this is too long. I was just trying to avoid repeating the `namespace 
{}/void fn()` prefix. Will try to break it up for next version of this patch.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87028/new/

https://reviews.llvm.org/D87028

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 56fa7d1 - [clang-format] Fix formatting of _Atomic() qualifier

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 56fa7d1dc6a8d23111ff84171036f333cf9cddf2

URL: 
https://github.com/llvm/llvm-project/commit/56fa7d1dc6a8d23111ff84171036f333cf9cddf2
DIFF: 
https://github.com/llvm/llvm-project/commit/56fa7d1dc6a8d23111ff84171036f333cf9cddf2.diff

LOG: [clang-format] Fix formatting of _Atomic() qualifier

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

Added: 


Modified: 
clang/lib/Format/FormatToken.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index 4bc865b043fd..8e4994f4c0d5 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -62,6 +62,7 @@ bool FormatToken::isSimpleTypeSpecifier() const {
   case tok::kw_char32_t:
   case tok::kw_typeof:
   case tok::kw_decltype:
+  case tok::kw__Atomic:
 return true;
   default:
 return false;

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index a9aeef5e9e52..8253bf18fc66 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -101,8 +101,8 @@ namespace format {
   TYPE(TrailingAnnotation) 
\
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
+  TYPE(TypeDeclarationParen)   
\
   TYPE(TypenameMacro)  
\
-  TYPE(TypenameMacroParen) 
\
   TYPE(UnaryOperator)  
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\
@@ -526,6 +526,7 @@ struct FormatToken {
 case tok::kw_decltype:
 case tok::kw_noexcept:
 case tok::kw_static_assert:
+case tok::kw__Atomic:
 case tok::kw___attribute:
   return true;
 default:

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 097843bdca84..0239dbd63d94 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -185,6 +185,8 @@ class AnnotatingParser {
 if (!CurrentToken)
   return false;
 FormatToken *Left = CurrentToken->Previous;
+FormatToken *PrevNonComment =
+Left ? Left->getPreviousNonComment() : nullptr;
 Left->ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
@@ -216,9 +218,8 @@ class AnnotatingParser {
   // export type X = (...);
   Contexts.back().IsExpression = false;
 } else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, 
tok::kw_decltype,
-tok::kw_while, tok::l_paren,
-tok::comma) ||
+   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
+tok::l_paren, tok::comma) ||
 Left->Previous->isIf() ||
 Left->Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
@@ -242,10 +243,15 @@ class AnnotatingParser {
 } else if (Contexts[Contexts.size() - 2].CaretFound) {
   // This is the parameter list of an ObjC block.
   Contexts.back().IsExpression = false;
-} else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
+} else if (PrevNonComment && PrevNonComment->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
-} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
-  Left->setType(TT_TypenameMacroParen);
+} else if (PrevNonComment &&
+   PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
+   tok::kw_typeof, tok::kw__Atomic)) {
+  Left->setType(TT_TypeDeclarationParen);
+  // decltype() and typeof() usually contain expressions.
+  if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
+Contexts.back().IsExpression = true;
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The fi

[PATCH] D86950: [clang-format] Check that */& after typename macros are pointers/references

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd01eec14bc0: [clang-format] Check that */& after 
typename macros are pointers/references (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86950/new/

https://reviews.llvm.org/D86950

Files:
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8041,6 +8041,14 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  FormatStyle TypeMacros = getLLVMStyle();
+  TypeMacros.TypenameMacros = {"LIST"};
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros); // multiplication
+
   FormatStyle CustomQualifier = getLLVMStyle();
   // Add indentifers that should not be parsed as a qualifier by default.
   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
@@ -8105,6 +8113,9 @@
   // a type declaration:
   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+  // Also check that TypenameMacros prevents parsing it as multiplication:
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
 
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
@@ -16553,12 +16564,15 @@
   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
+  verifyFormat("vector x;", Macros);
+  verifyFormat("vector f(LIST(uint64_t) *arg);", 
Macros);
 
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
+  verifyFormat("vector x;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8041,6 +8041,14 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  FormatStyle TypeMacros = getLLVMStyle();
+  TypeMacros.TypenameMacros = {"LIST"};
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros); // multiplication
+
   FormatStyle CustomQualifier = getLLVMStyle();
   // Add indentifers that should not be parsed as a qualifier by default.
   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
@@ -8105,6 +8113,9 @@
   // a type declaration:
   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+  // Also check that TypenameMacros prevents parsing it as multiplication:
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
 
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
@@ -16553,12 +16564,15 @@
   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
+  verifyFormat("vector x;", Macros);
+  verifyFormat("vector f(LIST(uint64_t) *arg);", Macros);
 
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
+  verifyFormat("vector x;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86959: [clang-format] Fix formatting of _Atomic() qualifier

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG56fa7d1dc6a8: [clang-format] Fix formatting of _Atomic() 
qualifier (authored by arichardson).

Changed prior to commit:
  https://reviews.llvm.org/D86959?vs=289509&id=290211#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86959/new/

https://reviews.llvm.org/D86959

Files:
  clang/lib/Format/FormatToken.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -168,6 +168,8 @@
   verifyFormat("vector<::Type> v;");
   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
+  verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
+  verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
   verifyFormat("bool a = 2 < ::SomeFunction();");
   verifyFormat("ALWAYS_INLINE ::std::string getName();");
   verifyFormat("some::string getName();");
@@ -7904,7 +7906,10 @@
   verifyFormat("auto PointerBinding = [](const char *S) {};");
   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
   verifyFormat("[](const decltype(*a) &value) {}");
+  verifyFormat("[](const typeof(*a) &value) {}");
+  verifyFormat("[](const _Atomic(a *) &value) {}");
   verifyFormat("decltype(a * b) F();");
+  verifyFormat("typeof(a * b) F();");
   verifyFormat("#define MACRO() [](A *a) { return 1; }");
   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
   verifyIndependentOfContext("typedef void (*f)(int *a);");
@@ -7970,6 +7975,8 @@
   verifyFormat("delete *x;", Left);
   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
+  verifyFormat("[](const typeof(*a)* ptr) {}", Left);
+  verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
@@ -8066,6 +8073,8 @@
   verifyFormat("foo();");
   verifyFormat("foo();");
   verifyFormat("decltype(*::std::declval()) void F();");
+  verifyFormat("typeof(*::std::declval()) void F();");
+  verifyFormat("_Atomic(*::std::declval()) void F();");
   verifyFormat(
   "template ::value &&\n"
@@ -8089,6 +8098,9 @@
   verifyIndependentOfContext("MACRO(int *i);");
   verifyIndependentOfContext("MACRO(auto *a);");
   verifyIndependentOfContext("MACRO(const A *a);");
+  verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
+  verifyIndependentOfContext("MACRO(decltype(A) *a);");
+  verifyIndependentOfContext("MACRO(typeof(A) *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
   verifyIndependentOfContext("MACRO(A *restrict a);");
   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
@@ -8639,6 +8651,10 @@
"LooongFunctionDefinition() {}");
   verifyFormat("decltype(LngName)\n"
"LooongFunctionDefinition() {}");
+  verifyFormat("typeof(LoongName)\n"
+   "LooongFunctionDefinition() {}");
+  verifyFormat("_Atomic(LongName)\n"
+   "LooongFunctionDefinition() {}");
   verifyFormat("LngReturnType\n"
"LooongFunctionDeclaration(T... t);");
   verifyFormat("LngReturnType\n"
@@ -8988,6 +9004,8 @@
   verifyFormat("int foo(int i) { return fo1{}(i); }");
   verifyFormat("int foo(int i) { return fo1{}(i); }");
   verifyFormat("auto i = decltype(x){};");
+  verifyFormat("auto i = typeof(x){};");
+  verifyFormat("auto i = _Atomic(x){};");
   verifyFormat("std::vector v = {1, 0 /* comment */};");
   verifyFormat("Node n{1, Node{1000}, //\n"
"   2};");
@@ -11580,6 +11598,8 @@
   verifyFormat("auto i = std::make_unique(5);", NoSpace);
   verifyFormat("size_t x = sizeof(x);", NoSpace);
   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
+  verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
+  verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
   verifyFormat("alignas(128) char a[128];", NoSpace);
   verifyFormat("size_t x = alignof(MyType);", NoSpace);
@@ -11628,6 +11648,8 @@
   verifyFormat("auto i = std::make_unique (5);", Space);
   verifyFormat("size_t x = sizeof (x);", Space);
   verifyFormat("auto f (int x) -> decltype (x);", Space)

[clang] e7bd058 - [clang-format] Allow configuring list of macros that map to attributes

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:17+01:00
New Revision: e7bd058c7e2cb2c675a4b78ec770ea725bff8c64

URL: 
https://github.com/llvm/llvm-project/commit/e7bd058c7e2cb2c675a4b78ec770ea725bff8c64
DIFF: 
https://github.com/llvm/llvm-project/commit/e7bd058c7e2cb2c675a4b78ec770ea725bff8c64.diff

LOG: [clang-format] Allow configuring list of macros that map to attributes

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 -> std::vector

Depends on D86775 (to apply cleanly)

Reviewed By: MyDeveloperDay, jrtc27

Differential Revision: https://reviews.llvm.org/D86782

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c35718b51248..72a25032151f 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -758,7 +758,24 @@ the configuration (without a prefix: ``Auto``).
  int b) {
}
 
+**AttributeMacros** (``std::vector``)
+  A vector of strings that should be interpreted as attributes/qualifiers
+  instead of identifiers. This can be useful for language extensions or
+  static analyzer annotations:
 
+  .. code-block:: c++
+
+x = (char *__capability)&y;
+int function(void) __ununsed;
+void only_writes_to_buffer(char *__output buffer);
+
+  In the .clang-format configuration file, this can be configured like:
+
+  .. code-block:: yaml
+
+AttributeMacros: ['__capability', '__output', '__ununsed']
+
+  For example: __capability.
 
 **BinPackArguments** (``bool``)
   If ``false``, a function call's arguments will either be all on the

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 269eab971a2c..6bb828d60071 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -583,6 +583,24 @@ struct FormatStyle {
   /// The template declaration breaking style to use.
   BreakTemplateDeclarationsStyle AlwaysBreakTemplateDeclarations;
 
+  /// A vector of strings that should be interpreted as attributes/qualifiers
+  /// instead of identifiers. This can be useful for language extensions or
+  /// static analyzer annotations.
+  ///
+  /// For example:
+  /// \code
+  ///   x = (char *__capability)&y;
+  ///   int function(void) __ununsed;
+  ///   void only_writes_to_buffer(char *__output buffer);
+  /// \endcode
+  ///
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   AttributeMacros: ['__capability', '__output', '__ununsed']
+  /// \endcode
+  ///
+  std::vector AttributeMacros;
+
   /// If ``false``, a function call's arguments will either be all on the
   /// same line or will have one line each.
   /// \code
@@ -2351,6 +2369,7 @@ struct FormatStyle {
R.AlwaysBreakBeforeMultilineStrings &&
AlwaysBreakTemplateDeclarations ==
R.AlwaysBreakTemplateDeclarations &&
+   AttributeMacros == R.AttributeMacros &&
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index fe11cba9bfdf..5dda2bda06b5 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -475,6 +475,7 @@ template <> struct MappingTraits {
Style.AlwaysBreakBeforeMultilineStrings);
 IO.mapOptional("AlwaysBreakTemplateDeclarations",
Style.AlwaysBreakTemplateDeclarations);
+IO.mapOptional("AttributeMacros", Style.AttributeMacros);
 IO.mapOptional("BinPackArguments", Style.BinPackArguments);
 IO.mapOptional("BinPackParameters", Style.BinPackParameters);
 IO.mapOptional("BraceWrapping", Style.BraceWrapping);
@@ -842,6 +843,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false

[PATCH] D86930: [clang-format] Handle typename macros inside cast expressions

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8aa3b8da5db2: [clang-format] Handle typename macros inside 
cast expressions (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86930/new/

https://reviews.llvm.org/D86930

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -16557,6 +16557,8 @@
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -244,6 +244,8 @@
   Contexts.back().IsExpression = false;
 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
+} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
+  Left->setType(TT_TypenameMacroParen);
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The first argument to a foreach macro is a declaration.
   Contexts.back().IsForEachMacro = true;
@@ -335,6 +337,8 @@
 
 if (Left->is(TT_AttributeParen))
   CurrentToken->setType(TT_AttributeParen);
+if (Left->is(TT_TypenameMacroParen))
+  CurrentToken->setType(TT_TypenameMacroParen);
 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
   CurrentToken->setType(TT_JavaAnnotation);
 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
@@ -1855,9 +1859,11 @@
   }
   return T && T->is(TT_PointerOrReference);
 };
-bool ParensAreType = !Tok.Previous || Tok.Previous->is(TT_TemplateCloser) 
||
- Tok.Previous->isSimpleTypeSpecifier() ||
- IsQualifiedPointerOrReference(Tok.Previous);
+bool ParensAreType =
+!Tok.Previous ||
+Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypenameMacroParen) ||
+Tok.Previous->isSimpleTypeSpecifier() ||
+IsQualifiedPointerOrReference(Tok.Previous);
 bool ParensCouldEndDecl =
 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
 if (ParensAreType && !ParensCouldEndDecl)
Index: clang/lib/Format/FormatToken.h
===
--- clang/lib/Format/FormatToken.h
+++ clang/lib/Format/FormatToken.h
@@ -102,6 +102,7 @@
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
   TYPE(TypenameMacro)  
\
+  TYPE(TypenameMacroParen) 
\
   TYPE(UnaryOperator)  
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -16557,6 +16557,8 @@
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -244,6 +244,8 @@
   Contexts.back().IsExpression = false;
 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
+} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
+  Left->setType(TT_TypenameMacroParen);
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The first argument to a foreach macro is a declaration.
   Contexts.back().IsForEachMacro = true;
@@ -335,6 +337,8 @@
 
 if (Left->is(TT_AttributeParen))
   CurrentToken->setType(TT_AttributeParen);
+if (Left->is(TT_TypenameMacroParen))
+  CurrentToken->setType(TT_TypenameMacroParen);
 if (Left->Prev

[clang] 9a22eba - [clang-format] Parse __underlying_type(T) as a type

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 9a22eba15091ea849fa78c09ac4c9f7260071790

URL: 
https://github.com/llvm/llvm-project/commit/9a22eba15091ea849fa78c09ac4c9f7260071790
DIFF: 
https://github.com/llvm/llvm-project/commit/9a22eba15091ea849fa78c09ac4c9f7260071790.diff

LOG: [clang-format] Parse __underlying_type(T) as a type

Before: MACRO(__underlying_type(A) * a);
After:  MACRO(__underlying_type(A) *a);

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D86960

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 8253bf18fc66..76ef99e72d58 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -528,6 +528,7 @@ struct FormatToken {
 case tok::kw_static_assert:
 case tok::kw__Atomic:
 case tok::kw___attribute:
+case tok::kw___underlying_type:
   return true;
 default:
   return false;

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 0239dbd63d94..4867f9e3d6c1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -247,7 +247,8 @@ class AnnotatingParser {
   Left->setType(TT_AttributeParen);
 } else if (PrevNonComment &&
PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
-   tok::kw_typeof, tok::kw__Atomic)) {
+   tok::kw_typeof, tok::kw__Atomic,
+   tok::kw___underlying_type)) {
   Left->setType(TT_TypeDeclarationParen);
   // decltype() and typeof() usually contain expressions.
   if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a5943847882f..b1d46a27ef43 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -169,6 +169,7 @@ TEST_F(FormatTest, NestedNameSpecifiers) {
   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
+  verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
   verifyFormat("bool a = 2 < ::SomeFunction();");
   verifyFormat("ALWAYS_INLINE ::std::string getName();");
@@ -7908,6 +7909,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("[](const decltype(*a) &value) {}");
   verifyFormat("[](const typeof(*a) &value) {}");
   verifyFormat("[](const _Atomic(a *) &value) {}");
+  verifyFormat("[](const __underlying_type(a) &value) {}");
   verifyFormat("decltype(a * b) F();");
   verifyFormat("typeof(a * b) F();");
   verifyFormat("#define MACRO() [](A *a) { return 1; }");
@@ -7977,6 +7979,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
+  verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
@@ -8075,6 +8078,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("decltype(*::std::declval()) void F();");
   verifyFormat("typeof(*::std::declval()) void F();");
   verifyFormat("_Atomic(*::std::declval()) void F();");
+  verifyFormat("__underlying_type(*::std::declval()) void F();");
   verifyFormat(
   "template ::value &&\n"
@@ -8101,6 +8105,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
   verifyIndependentOfContext("MACRO(decltype(A) *a);");
   verifyIndependentOfContext("MACRO(typeof(A) *a);");
+  verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
   verifyIndependentOfContext("MACRO(A *restrict a);");
   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
@@ -8655,6 +8660,8 @@ TEST_F(FormatTest, BreaksLongDeclarations) {
"LooongFunctionDefinition() 
{}");
   verifyFormat("_Atomic(LongName)\n"
"LooongFunctionDefinition() 
{}");
+  verifyFormat("__underlying_type(LooongName)\n"
+   "LooongFunctionDefinition() 
{}");
   verifyFormat

[clang] cd01eec - [clang-format] Check that */& after typename macros are pointers/references

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: cd01eec14bc045a8616604cadf94dba025090ba5

URL: 
https://github.com/llvm/llvm-project/commit/cd01eec14bc045a8616604cadf94dba025090ba5
DIFF: 
https://github.com/llvm/llvm-project/commit/cd01eec14bc045a8616604cadf94dba025090ba5.diff

LOG: [clang-format] Check that */& after typename macros are pointers/references

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D86950

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index be68da6f2ef6..978c22c6ee69 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8041,6 +8041,14 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  FormatStyle TypeMacros = getLLVMStyle();
+  TypeMacros.TypenameMacros = {"LIST"};
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros);
+  verifyFormat("vector v;", TypeMacros); // multiplication
+
   FormatStyle CustomQualifier = getLLVMStyle();
   // Add indentifers that should not be parsed as a qualifier by default.
   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
@@ -8105,6 +8113,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   // a type declaration:
   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+  // Also check that TypenameMacros prevents parsing it as multiplication:
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
+  verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
 
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
@@ -16553,12 +16564,15 @@ TEST_F(FormatTest, TypenameMacros) {
   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
+  verifyFormat("vector x;", Macros);
+  verifyFormat("vector f(LIST(uint64_t) *arg);", 
Macros);
 
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
+  verifyFormat("vector x;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 05147d3 - [clang-format] Correctly parse function declarations with TypenameMacros

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:18+01:00
New Revision: 05147d33091720e2df929d6fea3b0fd2a657ac61

URL: 
https://github.com/llvm/llvm-project/commit/05147d33091720e2df929d6fea3b0fd2a657ac61
DIFF: 
https://github.com/llvm/llvm-project/commit/05147d33091720e2df929d6fea3b0fd2a657ac61.diff

LOG: [clang-format] Correctly parse function declarations with TypenameMacros

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 4867f9e3d6c1..5dd6a7a9da40 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2400,6 +2400,8 @@ static bool isFunctionDeclarationName(const FormatToken 
&Current,
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
+if (Tok->is(TT_TypeDeclarationParen))
+  return true;
 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b1d46a27ef43..b198efa4af9e 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -6681,9 +6681,12 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
Style);
 
   // All declarations and definitions should have the return type moved to its
-  // own
-  // line.
+  // own line.
   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
+  Style.TypenameMacros = {"LIST"};
+  verifyFormat("SomeType\n"
+   "funcdecl(LIST(uint64_t));",
+   Style);
   verifyFormat("class E {\n"
"  int\n"
"  f() {\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8aa3b8d - [clang-format] Handle typename macros inside cast expressions

2020-09-07 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2020-09-07T10:09:17+01:00
New Revision: 8aa3b8da5db2ae73bf536b630915eb9f0ddc15cb

URL: 
https://github.com/llvm/llvm-project/commit/8aa3b8da5db2ae73bf536b630915eb9f0ddc15cb
DIFF: 
https://github.com/llvm/llvm-project/commit/8aa3b8da5db2ae73bf536b630915eb9f0ddc15cb.diff

LOG: [clang-format] Handle typename macros inside cast expressions

Before: x = (STACK_OF(uint64_t)) & a;
After:  x = (STACK_OF(uint64_t))&a;

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D86930

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 795c26889629..a9aeef5e9e52 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -102,6 +102,7 @@ namespace format {
   TYPE(TrailingReturnArrow)
\
   TYPE(TrailingUnaryOperator)  
\
   TYPE(TypenameMacro)  
\
+  TYPE(TypenameMacroParen) 
\
   TYPE(UnaryOperator)  
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index fc6a226dc4a1..097843bdca84 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -244,6 +244,8 @@ class AnnotatingParser {
   Contexts.back().IsExpression = false;
 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
   Left->setType(TT_AttributeParen);
+} else if (Left->Previous && Left->Previous->is(TT_TypenameMacro)) {
+  Left->setType(TT_TypenameMacroParen);
 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
   // The first argument to a foreach macro is a declaration.
   Contexts.back().IsForEachMacro = true;
@@ -335,6 +337,8 @@ class AnnotatingParser {
 
 if (Left->is(TT_AttributeParen))
   CurrentToken->setType(TT_AttributeParen);
+if (Left->is(TT_TypenameMacroParen))
+  CurrentToken->setType(TT_TypenameMacroParen);
 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
   CurrentToken->setType(TT_JavaAnnotation);
 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
@@ -1855,9 +1859,11 @@ class AnnotatingParser {
   }
   return T && T->is(TT_PointerOrReference);
 };
-bool ParensAreType = !Tok.Previous || Tok.Previous->is(TT_TemplateCloser) 
||
- Tok.Previous->isSimpleTypeSpecifier() ||
- IsQualifiedPointerOrReference(Tok.Previous);
+bool ParensAreType =
+!Tok.Previous ||
+Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypenameMacroParen) ||
+Tok.Previous->isSimpleTypeSpecifier() ||
+IsQualifiedPointerOrReference(Tok.Previous);
 bool ParensCouldEndDecl =
 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
 if (ParensAreType && !ParensCouldEndDecl)

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f224ab03271d..be68da6f2ef6 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16557,6 +16557,8 @@ TEST_F(FormatTest, TypenameMacros) {
   Macros.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("STACK_OF(int)* a;", Macros);
   verifyFormat("STACK_OF(int*)* a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
+  verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
 }
 
 TEST_F(FormatTest, AmbersandInLamda) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86782: [clang-format] Allow configuring list of macros that map to attributes

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe7bd058c7e2c: [clang-format] Allow configuring list of 
macros that map to attributes (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86782/new/

https://reviews.llvm.org/D86782

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -8040,7 +8040,20 @@
   verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  FormatStyle CustomQualifier = getLLVMStyle();
+  // Add indentifers that should not be parsed as a qualifier by default.
+  CustomQualifier.AttributeMacros.push_back("__my_qualifier");
+  CustomQualifier.AttributeMacros.push_back("_My_qualifier");
+  CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
+  verifyFormat("vector parse_as_multiply;");
+  verifyFormat("vector v;", CustomQualifier);
   verifyFormat("vector v;");
+  verifyFormat("vector v;");
   verifyFormat("vector v;");
   verifyFormat("foo();");
   verifyFormat("foo();");
@@ -8084,10 +8097,23 @@
   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
+  verifyIndependentOfContext("MACRO(A *__capability);");
+  verifyIndependentOfContext("MACRO(A &__capability);");
+  verifyFormat("MACRO(A *__my_qualifier);");   // type declaration
+  verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
+  // If we add __my_qualifier to AttributeMacros it should always be parsed as
+  // a type declaration:
+  verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
+  verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
+
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   // FIXME: Is there a way to make this work?
   // verifyIndependentOfContext("MACRO(A *a);");
+  verifyFormat("MACRO(A &B);");
+  verifyFormat("MACRO(A *B);");
+  verifyFormat("void f() { MACRO(A * B); }");
+  verifyFormat("void f() { MACRO(A & B); }");
 
   verifyFormat("DatumHandle const *operator->() const { return input_; }");
   verifyFormat("return options != nullptr && operator==(*options);");
@@ -8137,10 +8163,47 @@
   verifyFormat("a __attribute__((unused))\n"
"aaa(int i);");
   FormatStyle AfterType = getLLVMStyle();
-  AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
+  AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
   verifyFormat("__attribute__((nodebug)) void\n"
"foo() {}\n",
AfterType);
+  verifyFormat("__unused void\n"
+   "foo() {}",
+   AfterType);
+
+  FormatStyle CustomAttrs = getLLVMStyle();
+  CustomAttrs.AttributeMacros.push_back("__unused");
+  CustomAttrs.AttributeMacros.push_back("__attr1");
+  CustomAttrs.AttributeMacros.push_back("__attr2");
+  CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  // Check that it is parsed as a multiplication without AttributeMacros and
+  // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;");
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+  verifyFormat("vector v;", CustomAttrs);
+
+  // Check that these are not parsed as function declarations:
+  CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+  CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
+  verifyFormat("SomeType s(InitValue);", CustomAttrs);
+  verifyFormat("SomeType s{InitValue};", CustomAttrs);
+  verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
+  verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
+  verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
+  verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
+  verify

[PATCH] D86960: [clang-format] Parse __underlying_type(T) as a type

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9a22eba15091: [clang-format] Parse __underlying_type(T) as a 
type (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86960/new/

https://reviews.llvm.org/D86960

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -169,6 +169,7 @@
   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
+  verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
   verifyFormat("bool a = 2 < ::SomeFunction();");
   verifyFormat("ALWAYS_INLINE ::std::string getName();");
@@ -7908,6 +7909,7 @@
   verifyFormat("[](const decltype(*a) &value) {}");
   verifyFormat("[](const typeof(*a) &value) {}");
   verifyFormat("[](const _Atomic(a *) &value) {}");
+  verifyFormat("[](const __underlying_type(a) &value) {}");
   verifyFormat("decltype(a * b) F();");
   verifyFormat("typeof(a * b) F();");
   verifyFormat("#define MACRO() [](A *a) { return 1; }");
@@ -7977,6 +7979,7 @@
   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
+  verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
@@ -8075,6 +8078,7 @@
   verifyFormat("decltype(*::std::declval()) void F();");
   verifyFormat("typeof(*::std::declval()) void F();");
   verifyFormat("_Atomic(*::std::declval()) void F();");
+  verifyFormat("__underlying_type(*::std::declval()) void F();");
   verifyFormat(
   "template ::value &&\n"
@@ -8101,6 +8105,7 @@
   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
   verifyIndependentOfContext("MACRO(decltype(A) *a);");
   verifyIndependentOfContext("MACRO(typeof(A) *a);");
+  verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
   verifyIndependentOfContext("MACRO(A *const a);");
   verifyIndependentOfContext("MACRO(A *restrict a);");
   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
@@ -8655,6 +8660,8 @@
"LooongFunctionDefinition() {}");
   verifyFormat("_Atomic(LongName)\n"
"LooongFunctionDefinition() {}");
+  verifyFormat("__underlying_type(LooongName)\n"
+   "LooongFunctionDefinition() {}");
   verifyFormat("LngReturnType\n"
"LooongFunctionDeclaration(T... t);");
   verifyFormat("LngReturnType\n"
@@ -11600,6 +11607,7 @@
   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
+  verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
   verifyFormat("alignas(128) char a[128];", NoSpace);
   verifyFormat("size_t x = alignof(MyType);", NoSpace);
@@ -11650,6 +11658,7 @@
   verifyFormat("auto f (int x) -> decltype (x);", Space);
   verifyFormat("auto f (int x) -> typeof (x);", Space);
   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
+  verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
   verifyFormat("int f (T x) noexcept (x.create ());", Space);
   verifyFormat("alignas (128) char a[128];", Space);
   verifyFormat("size_t x = alignof (MyType);", Space);
@@ -11704,6 +11713,7 @@
   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
+  verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
   verifyFormat("alignas (128) char a[128];", SomeSpace);
   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
@@ -14960,6 +14970,7 @@
"  SomeFunction([](decltype(x), A *a) {});\n"
"  SomeFunction([](typeof(x), A *a) {});\n"
"  SomeFunction([](_Atomic(x), A *a) {});\n"
+   "  SomeFunction([](__underlying_type(x), A *a) {});\n"
"}");
   veri

[PATCH] D87007: [clang-format] Correctly parse function declarations with TypenameMacros

2020-09-07 Thread Alexander Richardson via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG05147d330917: [clang-format] Correctly parse function 
declarations with TypenameMacros (authored by arichardson).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87007/new/

https://reviews.llvm.org/D87007

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6681,9 +6681,12 @@
Style);
 
   // All declarations and definitions should have the return type moved to its
-  // own
-  // line.
+  // own line.
   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
+  Style.TypenameMacros = {"LIST"};
+  verifyFormat("SomeType\n"
+   "funcdecl(LIST(uint64_t));",
+   Style);
   verifyFormat("class E {\n"
"  int\n"
"  f() {\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2400,6 +2400,8 @@
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
+if (Tok->is(TT_TypeDeclarationParen))
+  return true;
 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6681,9 +6681,12 @@
Style);
 
   // All declarations and definitions should have the return type moved to its
-  // own
-  // line.
+  // own line.
   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
+  Style.TypenameMacros = {"LIST"};
+  verifyFormat("SomeType\n"
+   "funcdecl(LIST(uint64_t));",
+   Style);
   verifyFormat("class E {\n"
"  int\n"
"  f() {\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2400,6 +2400,8 @@
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
+if (Tok->is(TT_TypeDeclarationParen))
+  return true;
 if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
   Tok = Tok->MatchingParen;
   continue;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87118: Add an explicit toggle for the static analyzer in clang-tidy

2020-09-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Cool!




Comment at: clang-tools-extra/CMakeLists.txt:4
+option(CLANG_TIDY_ENABLE_STATIC_ANALYZER
+  "Include static analyzer checks in clang-tidy" ON)
+

Should this default to CLANG_ENABLE_STATIC_ANALYZER instead of ON?



Comment at: clang/lib/CMakeLists.txt:24
 add_subdirectory(IndexSerialization)
-if(CLANG_ENABLE_STATIC_ANALYZER)
-  add_subdirectory(StaticAnalyzer)

Why does removing the condition here work?



Comment at: llvm/utils/gn/secondary/clang-tools-extra/clang-tidy/BUILD.gn:18
+  } else {
+values += [ "CLANG_TIDY_ENABLE_STATIC_ANALYZER=" ]
+  }

Why not =0?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87118/new/

https://reviews.llvm.org/D87118

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84415: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.
This revision is now accepted and ready to land.

@balazske seems to be very involved, he might have some closing words -- from 
my end, LGTM!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84415/new/

https://reviews.llvm.org/D84415

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86880: [Ignore Expressions][NFC] Refactor to better use `IgnoreExpr.h` and nits

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1a7a2cd7474e: [Ignore Expressions][NFC] Refactor to better 
use `IgnoreExpr.h` and nits (authored by eduucaldas).

Changed prior to commit:
  https://reviews.llvm.org/D86880?vs=288961&id=290222#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86880/new/

https://reviews.llvm.org/D86880

Files:
  clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang/include/clang/AST/Expr.h
  clang/lib/AST/Expr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -687,7 +687,7 @@
 // base class decl, rather than the class of the instance which needs to be
 // checked for mutable fields.
 // TODO: We might as well look at the dynamic type of the object.
-const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
+const Expr *Ex = getCXXThisExpr()->IgnoreParenBaseCasts();
 QualType T = Ex->getType();
 if (T->isPointerType()) // Arrow or implicit-this syntax?
   T = T->getPointeeType();
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -8372,7 +8372,7 @@
Expr **RHSExprs) {
   // Don't strip parenthesis: we should not warn if E is in parenthesis.
   E = E->IgnoreImpCasts();
-  E = E->IgnoreConversionOperator();
+  E = E->IgnoreConversionOperatorSingleStep();
   E = E->IgnoreImpCasts();
   if (auto *MTE = dyn_cast(E)) {
 E = MTE->getSubExpr();
Index: clang/lib/CodeGen/CGExprCXX.cpp
===
--- clang/lib/CodeGen/CGExprCXX.cpp
+++ clang/lib/CodeGen/CGExprCXX.cpp
@@ -220,7 +220,7 @@
 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
 assert(DevirtualizedMethod);
 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
-const Expr *Inner = Base->ignoreParenBaseCasts();
+const Expr *Inner = Base->IgnoreParenBaseCasts();
 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
 MD->getReturnType().getCanonicalType())
   // If the return types are not the same, this might be a case where more
Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -40,7 +40,7 @@
 const Expr *Expr::getBestDynamicClassTypeExpr() const {
   const Expr *E = this;
   while (true) {
-E = E->ignoreParenBaseCasts();
+E = E->IgnoreParenBaseCasts();
 
 // Follow the RHS of a comma operator.
 if (auto *BO = dyn_cast(E)) {
@@ -2780,29 +2780,6 @@
   return QualType();
 }
 
-static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
-  if (auto *CE = dyn_cast(E)) {
-// We ignore integer <-> casts that are of the same width, ptr<->ptr and
-// ptr<->int casts of the same width. We also ignore all identity casts.
-Expr *SubExpr = CE->getSubExpr();
-bool IsIdentityCast =
-Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
-bool IsSameWidthCast =
-(E->getType()->isPointerType() || E->getType()->isIntegralType(Ctx)) &&
-(SubExpr->getType()->isPointerType() ||
- SubExpr->getType()->isIntegralType(Ctx)) &&
-(Ctx.getTypeSize(E->getType()) == Ctx.getTypeSize(SubExpr->getType()));
-
-if (IsIdentityCast || IsSameWidthCast)
-  return SubExpr;
-  }
-
-  else if (auto *NTTP = dyn_cast(E))
-return NTTP->getReplacement();
-
-  return E;
-}
-
 Expr *Expr::IgnoreImpCasts() {
   return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
 }
@@ -2832,7 +2809,7 @@
   return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
 }
 
-Expr *Expr::IgnoreConversionOperator() {
+Expr *Expr::IgnoreConversionOperatorSingleStep() {
   if (auto *MCE = dyn_cast(this)) {
 if (MCE->getMethodDecl() && isa(MCE->getMethodDecl()))
   return MCE->getImplicitObjectArgument();
@@ -2845,58 +2822,72 @@
  IgnoreLValueCastsSingleStep);
 }
 
-Expr *Expr::ignoreParenBaseCasts() {
+Expr *Expr::IgnoreParenBaseCasts() {
   return IgnoreExprNodes(this, IgnoreParensSingleStep,
  IgnoreBaseCastsSingleStep);
 }
 
 Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
-  return IgnoreExprNodes(this, IgnoreParensSingleStep, [&Ctx](Expr *E) {
-return IgnoreNoopCastsSingleStep(Ctx, E);
-  });
+  auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
+if 

[PATCH] D86778: Extract infrastructure to ignore intermediate expressions into `clang/AST/IgnoreExpr.h`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG81aa66f65f50: Extract infrastructure to ignore intermediate 
expressions into… (authored by eduucaldas).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86778/new/

https://reviews.llvm.org/D86778

Files:
  clang/include/clang/AST/IgnoreExpr.h
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Expr.cpp
  clang/lib/AST/IgnoreExpr.cpp

Index: clang/lib/AST/IgnoreExpr.cpp
===
--- /dev/null
+++ clang/lib/AST/IgnoreExpr.cpp
@@ -0,0 +1,129 @@
+//===--- IgnoreExpr.cpp - Ignore intermediate Expressions -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements common functions to ignore intermediate expression nodes
+//
+//===--===//
+
+#include "clang/AST/IgnoreExpr.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+
+using namespace clang;
+
+Expr *clang::IgnoreImplicitCastsSingleStep(Expr *E) {
+  if (auto *ICE = dyn_cast(E))
+return ICE->getSubExpr();
+
+  if (auto *FE = dyn_cast(E))
+return FE->getSubExpr();
+
+  return E;
+}
+
+Expr *clang::IgnoreImplicitCastsExtraSingleStep(Expr *E) {
+  // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
+  // addition to what IgnoreImpCasts() skips to account for the current
+  // behaviour of IgnoreParenImpCasts().
+  Expr *SubE = IgnoreImplicitCastsSingleStep(E);
+  if (SubE != E)
+return SubE;
+
+  if (auto *MTE = dyn_cast(E))
+return MTE->getSubExpr();
+
+  if (auto *NTTP = dyn_cast(E))
+return NTTP->getReplacement();
+
+  return E;
+}
+
+Expr *clang::IgnoreCastsSingleStep(Expr *E) {
+  if (auto *CE = dyn_cast(E))
+return CE->getSubExpr();
+
+  if (auto *FE = dyn_cast(E))
+return FE->getSubExpr();
+
+  if (auto *MTE = dyn_cast(E))
+return MTE->getSubExpr();
+
+  if (auto *NTTP = dyn_cast(E))
+return NTTP->getReplacement();
+
+  return E;
+}
+
+Expr *clang::IgnoreLValueCastsSingleStep(Expr *E) {
+  // Skip what IgnoreCastsSingleStep skips, except that only
+  // lvalue-to-rvalue casts are skipped.
+  if (auto *CE = dyn_cast(E))
+if (CE->getCastKind() != CK_LValueToRValue)
+  return E;
+
+  return IgnoreCastsSingleStep(E);
+}
+
+Expr *clang::IgnoreBaseCastsSingleStep(Expr *E) {
+  if (auto *CE = dyn_cast(E))
+if (CE->getCastKind() == CK_DerivedToBase ||
+CE->getCastKind() == CK_UncheckedDerivedToBase ||
+CE->getCastKind() == CK_NoOp)
+  return CE->getSubExpr();
+
+  return E;
+}
+
+Expr *clang::IgnoreImplicitSingleStep(Expr *E) {
+  Expr *SubE = IgnoreImplicitCastsSingleStep(E);
+  if (SubE != E)
+return SubE;
+
+  if (auto *MTE = dyn_cast(E))
+return MTE->getSubExpr();
+
+  if (auto *BTE = dyn_cast(E))
+return BTE->getSubExpr();
+
+  return E;
+}
+
+Expr *clang::IgnoreImplicitAsWrittenSingleStep(Expr *E) {
+  if (auto *ICE = dyn_cast(E))
+return ICE->getSubExprAsWritten();
+
+  return IgnoreImplicitSingleStep(E);
+}
+
+Expr *clang::IgnoreParensOnlySingleStep(Expr *E) {
+  if (auto *PE = dyn_cast(E))
+return PE->getSubExpr();
+  return E;
+}
+
+Expr *clang::IgnoreParensSingleStep(Expr *E) {
+  if (auto *PE = dyn_cast(E))
+return PE->getSubExpr();
+
+  if (auto *UO = dyn_cast(E)) {
+if (UO->getOpcode() == UO_Extension)
+  return UO->getSubExpr();
+  }
+
+  else if (auto *GSE = dyn_cast(E)) {
+if (!GSE->isResultDependent())
+  return GSE->getResultExpr();
+  }
+
+  else if (auto *CE = dyn_cast(E)) {
+if (!CE->isConditionDependent())
+  return CE->getChosenSubExpr();
+  }
+
+  return E;
+}
Index: clang/lib/AST/Expr.cpp
===
--- clang/lib/AST/Expr.cpp
+++ clang/lib/AST/Expr.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/DependenceFlags.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/IgnoreExpr.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/StmtVisitor.h"
@@ -2779,118 +2780,6 @@
   return QualType();
 }
 
-static Expr *IgnoreImpCastsSingleStep(Expr *E) {
-  if (auto *ICE = dyn_cast(E))
-return ICE->getSubExpr();
-
-  if (auto *FE = dyn_cast(E))
-return FE->getSubExpr();
-
-  return E;
-}
-
-static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
-  // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
-  // addition to what IgnoreImpCasts() skips to account for the current
-  // behaviour of IgnoreParenImpCasts().
-  Expr *SubE = IgnoreImpCastsSingleStep(E);
-  if (SubE != E)
-return SubE;
-
-  

[clang-tools-extra] 1a7a2cd - [Ignore Expressions][NFC] Refactor to better use `IgnoreExpr.h` and nits

2020-09-07 Thread Eduardo Caldas via cfe-commits

Author: Eduardo Caldas
Date: 2020-09-07T09:32:30Z
New Revision: 1a7a2cd7474e6d321120ffe7ca9c52163eb228f0

URL: 
https://github.com/llvm/llvm-project/commit/1a7a2cd7474e6d321120ffe7ca9c52163eb228f0
DIFF: 
https://github.com/llvm/llvm-project/commit/1a7a2cd7474e6d321120ffe7ca9c52163eb228f0.diff

LOG: [Ignore Expressions][NFC] Refactor to better use `IgnoreExpr.h` and nits

This change groups
* Rename: `ignoreParenBaseCasts` -> `IgnoreParenBaseCasts` for uniformity
* Rename: `IgnoreConversionOperator` -> `IgnoreConversionOperatorSingleStep` 
for uniformity
* Inline `IgnoreNoopCastsSingleStep` into a lambda inside `IgnoreNoopCasts`
* Refactor `IgnoreUnlessSpelledInSource` to make adequate use of 
`IgnoreExprNodes`

Differential Revision: https://reviews.llvm.org/D86880

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
clang/include/clang/AST/Expr.h
clang/lib/AST/Expr.cpp
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
index 04dc61f02df1..44ae380b63b2 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp
@@ -338,7 +338,7 @@ void UseAutoCheck::replaceIterators(const DeclStmt *D, 
ASTContext *Context) {
 
 // Drill down to the as-written initializer.
 const Expr *E = (*Construct->arg_begin())->IgnoreParenImpCasts();
-if (E != E->IgnoreConversionOperator()) {
+if (E != E->IgnoreConversionOperatorSingleStep()) {
   // We hit a conversion operator. Early-out now as they imply an implicit
   // conversion from a 
diff erent type. Could also mean an explicit
   // conversion from the same type but that's pretty rare.

diff  --git 
a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index 9dcb10b9d20c..7e8ba4eb90c6 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -205,7 +205,7 @@ std::string compareExpressionToZero(const 
MatchFinder::MatchResult &Result,
 
 std::string replacementExpression(const MatchFinder::MatchResult &Result,
   bool Negated, const Expr *E) {
-  E = E->ignoreParenBaseCasts();
+  E = E->IgnoreParenBaseCasts();
   if (const auto *EC = dyn_cast(E))
 E = EC->getSubExpr();
 

diff  --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 5edca2593789..26e52ad367f8 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -867,9 +867,9 @@ class Expr : public ValueStmt {
 
   /// Skip conversion operators. If this Expr is a call to a conversion
   /// operator, return the argument.
-  Expr *IgnoreConversionOperator() LLVM_READONLY;
-  const Expr *IgnoreConversionOperator() const {
-return const_cast(this)->IgnoreConversionOperator();
+  Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
+  const Expr *IgnoreConversionOperatorSingleStep() const {
+return const_cast(this)->IgnoreConversionOperatorSingleStep();
   }
 
   /// Skip past any parentheses and lvalue casts which might surround this
@@ -901,9 +901,9 @@ class Expr : public ValueStmt {
   /// * What IgnoreParens() skips
   /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
   ///   CK_UncheckedDerivedToBase and CK_NoOp)
-  Expr *ignoreParenBaseCasts() LLVM_READONLY;
-  const Expr *ignoreParenBaseCasts() const {
-return const_cast(this)->ignoreParenBaseCasts();
+  Expr *IgnoreParenBaseCasts() LLVM_READONLY;
+  const Expr *IgnoreParenBaseCasts() const {
+return const_cast(this)->IgnoreParenBaseCasts();
   }
 
   /// Determine whether this expression is a default function argument.

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 1029acbf68cd..15f3df0fd216 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -40,7 +40,7 @@ using namespace clang;
 const Expr *Expr::getBestDynamicClassTypeExpr() const {
   const Expr *E = this;
   while (true) {
-E = E->ignoreParenBaseCasts();
+E = E->IgnoreParenBaseCasts();
 
 // Follow the RHS of a comma operator.
 if (auto *BO = dyn_cast(E)) {
@@ -2780,29 +2780,6 @@ QualType Expr::findBoundMemberType(const Expr *expr) {
   return QualType();
 }
 
-static Expr *IgnoreNoopCastsSingleStep(const ASTContext &Ctx, Expr *E) {
-  if (auto *CE = dyn_cast(E)) {
-// We ignore integer <-> casts that are of the same width, ptr<->ptr and
-// ptr<->int casts of the same width. We also ignore all identity casts.
-Expr *SubExpr = CE->g

[clang] 81aa66f - Extract infrastructure to ignore intermediate expressions into `clang/AST/IgnoreExpr.h`

2020-09-07 Thread Eduardo Caldas via cfe-commits

Author: Eduardo Caldas
Date: 2020-09-07T09:32:30Z
New Revision: 81aa66f65f504af18982baa078a5f3f7d2aa88fa

URL: 
https://github.com/llvm/llvm-project/commit/81aa66f65f504af18982baa078a5f3f7d2aa88fa
DIFF: 
https://github.com/llvm/llvm-project/commit/81aa66f65f504af18982baa078a5f3f7d2aa88fa.diff

LOG: Extract infrastructure to ignore intermediate expressions into 
`clang/AST/IgnoreExpr.h`

Rationale:
This allows users to use `IgnoreExprNodes` and `Ignore*SingleStep` outside of
`clang/AST/Expr.cpp`.

Minor:
Rename `IgnoreImp...SingleStep`  into `IgnoreImplicit...SingleStep`.

Differential Revision: https://reviews.llvm.org/D86778

Added: 
clang/include/clang/AST/IgnoreExpr.h
clang/lib/AST/IgnoreExpr.cpp

Modified: 
clang/lib/AST/CMakeLists.txt
clang/lib/AST/Expr.cpp

Removed: 




diff  --git a/clang/include/clang/AST/IgnoreExpr.h 
b/clang/include/clang/AST/IgnoreExpr.h
new file mode 100644
index ..15d31f3af995
--- /dev/null
+++ b/clang/include/clang/AST/IgnoreExpr.h
@@ -0,0 +1,61 @@
+//===--- IgnoreExpr.h - Ignore intermediate Expressions -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file defines common functions to ignore intermediate expression nodes
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_IGNOREEXPR_H
+#define LLVM_CLANG_AST_IGNOREEXPR_H
+
+#include "clang/AST/Expr.h"
+
+namespace clang {
+namespace detail {
+/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
+/// Return Fn_n(...(Fn_1(E)))
+inline Expr *IgnoreExprNodesImpl(Expr *E) { return E; };
+template 
+Expr *IgnoreExprNodesImpl(Expr *E, FnTy &&Fn, FnTys &&... Fns) {
+  return IgnoreExprNodesImpl(Fn(E), std::forward(Fns)...);
+}
+} // namespace detail
+
+/// Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *,
+/// Recursively apply each of the functions to E until reaching a fixed point.
+/// Note that a null E is valid; in this case nothing is done.
+template  Expr *IgnoreExprNodes(Expr *E, FnTys &&... Fns) {
+  Expr *LastE = nullptr;
+  while (E != LastE) {
+LastE = E;
+E = detail::IgnoreExprNodesImpl(E, std::forward(Fns)...);
+  }
+  return E;
+}
+
+Expr *IgnoreImplicitCastsSingleStep(Expr *E);
+
+Expr *IgnoreImplicitCastsExtraSingleStep(Expr *E);
+
+Expr *IgnoreCastsSingleStep(Expr *E);
+
+Expr *IgnoreLValueCastsSingleStep(Expr *E);
+
+Expr *IgnoreBaseCastsSingleStep(Expr *E);
+
+Expr *IgnoreImplicitSingleStep(Expr *E);
+
+Expr *IgnoreImplicitAsWrittenSingleStep(Expr *E);
+
+Expr *IgnoreParensOnlySingleStep(Expr *E);
+
+Expr *IgnoreParensSingleStep(Expr *E);
+
+} // namespace clang
+
+#endif // LLVM_CLANG_AST_IGNOREEXPR_H

diff  --git a/clang/lib/AST/CMakeLists.txt b/clang/lib/AST/CMakeLists.txt
index 35099fd0dacf..dfd26fd97bc6 100644
--- a/clang/lib/AST/CMakeLists.txt
+++ b/clang/lib/AST/CMakeLists.txt
@@ -55,6 +55,7 @@ add_clang_library(clangAST
   ExternalASTMerger.cpp
   ExternalASTSource.cpp
   FormatString.cpp
+  IgnoreExpr.cpp
   InheritViz.cpp
   Interp/ByteCodeEmitter.cpp
   Interp/ByteCodeExprGen.cpp

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 8efd6837c541..1029acbf68cd 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -21,6 +21,7 @@
 #include "clang/AST/DependenceFlags.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/IgnoreExpr.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/StmtVisitor.h"
@@ -2779,118 +2780,6 @@ QualType Expr::findBoundMemberType(const Expr *expr) {
   return QualType();
 }
 
-static Expr *IgnoreImpCastsSingleStep(Expr *E) {
-  if (auto *ICE = dyn_cast(E))
-return ICE->getSubExpr();
-
-  if (auto *FE = dyn_cast(E))
-return FE->getSubExpr();
-
-  return E;
-}
-
-static Expr *IgnoreImpCastsExtraSingleStep(Expr *E) {
-  // FIXME: Skip MaterializeTemporaryExpr and SubstNonTypeTemplateParmExpr in
-  // addition to what IgnoreImpCasts() skips to account for the current
-  // behaviour of IgnoreParenImpCasts().
-  Expr *SubE = IgnoreImpCastsSingleStep(E);
-  if (SubE != E)
-return SubE;
-
-  if (auto *MTE = dyn_cast(E))
-return MTE->getSubExpr();
-
-  if (auto *NTTP = dyn_cast(E))
-return NTTP->getReplacement();
-
-  return E;
-}
-
-static Expr *IgnoreCastsSingleStep(Expr *E) {
-  if (auto *CE = dyn_cast(E))
-return CE->getSubExpr();
-
-  if (auto *FE = dyn_cast(E))
-return FE->getSubExpr();
-
-  if (auto *MTE = dyn_cast(E))
-return MTE->getSubExpr();
-
-  if (auto *NTTP = dyn_cast(E))
-return NTTP->getReplacement();
-
-  return E;
-}
-
-static 

[PATCH] D86699: [SyntaxTree] Ignore implicit non-leaf `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290223.
eduucaldas added a comment.

Add more tests, not extract `IgnoreImplicitConstructorSingleStep`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86699/new/

https://reviews.llvm.org/D86699

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp

Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -1745,19 +1745,15 @@
 struct X {
   friend X operator+(X, const X&);
 };
-// FIXME: Remove additional `UnknownExpression` wrapping `x`. For that, ignore
-// implicit copy constructor called on `x`. This should've been ignored already,
-// as we `IgnoreImplicit` when traversing an `Stmt`.
 void test(X x, X y) {
   [[x + y]];
 }
 )cpp",
   {R"txt(
 BinaryOperatorExpression Expression
-|-UnknownExpression LeftHandSide
-| `-IdExpression
-|   `-UnqualifiedId UnqualifiedId
-| `-'x'
+|-IdExpression LeftHandSide
+| `-UnqualifiedId UnqualifiedId
+|   `-'x'
 |-'+' OperatorToken
 `-IdExpression RightHandSide
   `-UnqualifiedId UnqualifiedId
@@ -3821,26 +3817,135 @@
 )txt"));
 }
 
+TEST_P(SyntaxTreeTest, InitDeclarator_Equal) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { S(int);};
+void test() {
+  [[S s = 1]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s'
+  |-'='
+  `-IntegerLiteralExpression
+`-'1' LiteralToken
+)txt"}));
+}
+
 TEST_P(SyntaxTreeTest, InitDeclarator_Brace) {
   if (!GetParam().isCXX11OrLater()) {
 return;
   }
-  EXPECT_TRUE(treeDumpEqual(
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
   R"cpp(
-int a {};
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test(){
+  [[S s0{}]];
+  [[S s1{1}]];
+  [[S s2{1, 2.}]];
+}
 )cpp",
-  R"txt(
-TranslationUnit Detached
-`-SimpleDeclaration
-  |-'int'
-  |-SimpleDeclarator Declarator
-  | |-'a'
-  | `-UnknownExpression
-  |   `-UnknownExpression
-  | |-'{'
-  | `-'}'
-  `-';'
-)txt"));
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s0'
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s1'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s2'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, InitDeclarator_EqualBrace) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test() {
+  [[S s0 = {}]];
+  [[S s1 = {1}]];
+  [[S s2 = {1, 2.}]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s0'
+  |-'='
+  `-UnknownExpression
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s1'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s2'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
 }
 
 TEST_P(SyntaxTreeTest, InitDeclarator_Paren) {
@@ -3851,15 +3956,132 @@
   R"cpp(
 struct S {
   S(int);
+  S(int, float);
 };
-[[S s(1);]]
+[[S s1(1);]]
+[[S s2(1, 2.);]]
 )cpp",
   {R"txt(
 SimpleDeclaration
 |-'S'
 |-SimpleDeclarator Declarator
 | `-UnknownExpression
-|   |-'s'
+|   |-'s1'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   `-')'
+`-';'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+|-SimpleDeclarator Declarator
+| `-UnknownExpression
+|   |-'s2'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   |-','
+|   |-FloatingLiteralExpression
+|   | `-'2.' LiteralToken
+|   `-')'
+`-';'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, ImplicitConversion_Argument) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct X {
+  X(int);
+};
+void TakeX(const X&);
+void test() {
+  [[TakeX(1)]];
+}
+)cpp",
+  {R"txt(
+CallExpression Expression
+|-IdExpression Callee
+| `-UnqualifiedId UnqualifiedId
+|   `-'TakeX'
+|-'(' OpenParen
+|-CallArguments Arguments
+| `-IntegerLiteralExpression ListElement
+|   `-'1' LiteralToken
+`-')' CloseParen
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, Implic

[PATCH] D86700: [SyntaxTree] Ignore leaf implicit `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290224.
eduucaldas marked an inline comment as done.
eduucaldas added a comment.

Add FIXME for `CXXFunctionalCastExpr`


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86700/new/

https://reviews.llvm.org/D86700

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -4073,6 +4066,7 @@
   X(int);
 };
 X test() {
+  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1129,6 +1129,12 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+if (S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -4073,6 +4066,7 @@
   X(int);
 };
 X test() {
+  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1129,6 +1129,12 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+if (S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87229: [SyntaxTree] Ignore implicit `CXXFunctionalCastExpr` wrapping constructor

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
eduucaldas requested review of this revision.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87229

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -4066,7 +4066,6 @@
   X(int);
 };
 X test() {
-  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
@@ -4074,12 +4073,11 @@
 ReturnStatement Statement
 |-'return' IntroducerKeyword
 |-UnknownExpression ReturnValue
-| `-UnknownExpression
-|   |-'X'
-|   |-'('
-|   |-IntegerLiteralExpression
-|   | `-'1' LiteralToken
-|   `-')'
+| |-'X'
+| |-'('
+| |-IntegerLiteralExpression
+| | `-'1' LiteralToken
+| `-')'
 `-';'
 )txt"}));
 }
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/IgnoreExpr.h"
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TypeLoc.h"
@@ -57,9 +58,18 @@
   return E;
 }
 
+static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
+  if (auto *F = dyn_cast(E)) {
+if (F->getCastKind() == CK_ConstructorConversion)
+  return F->getSubExpr();
+  }
+  return E;
+}
+
 static Expr *IgnoreImplicit(Expr *E) {
   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
- IgnoreImplicitConstructorSingleStep);
+ IgnoreImplicitConstructorSingleStep,
+ IgnoreCXXFunctionalCastExprWrappingConstructor);
 }
 
 LLVM_ATTRIBUTE_UNUSED


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -4066,7 +4066,6 @@
   X(int);
 };
 X test() {
-  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
@@ -4074,12 +4073,11 @@
 ReturnStatement Statement
 |-'return' IntroducerKeyword
 |-UnknownExpression ReturnValue
-| `-UnknownExpression
-|   |-'X'
-|   |-'('
-|   |-IntegerLiteralExpression
-|   | `-'1' LiteralToken
-|   `-')'
+| |-'X'
+| |-'('
+| |-IntegerLiteralExpression
+| | `-'1' LiteralToken
+| `-')'
 `-';'
 )txt"}));
 }
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/IgnoreExpr.h"
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TypeLoc.h"
@@ -57,9 +58,18 @@
   return E;
 }
 
+static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
+  if (auto *F = dyn_cast(E)) {
+if (F->getCastKind() == CK_ConstructorConversion)
+  return F->getSubExpr();
+  }
+  return E;
+}
+
 static Expr *IgnoreImplicit(Expr *E) {
   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
- IgnoreImplicitConstructorSingleStep);
+ IgnoreImplicitConstructorSingleStep,
+ IgnoreCXXFunctionalCastExprWrappingConstructor);
 }
 
 LLVM_ATTRIBUTE_UNUSED
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84415: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

2020-09-07 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko accepted this revision.
vsavchenko added a comment.

LGTM!
Thanks!


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84415/new/

https://reviews.llvm.org/D84415

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86699: [SyntaxTree] Ignore implicit non-leaf `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290227.
eduucaldas added a comment.

.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86699/new/

https://reviews.llvm.org/D86699

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp

Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -1745,19 +1745,15 @@
 struct X {
   friend X operator+(X, const X&);
 };
-// FIXME: Remove additional `UnknownExpression` wrapping `x`. For that, ignore
-// implicit copy constructor called on `x`. This should've been ignored already,
-// as we `IgnoreImplicit` when traversing an `Stmt`.
 void test(X x, X y) {
   [[x + y]];
 }
 )cpp",
   {R"txt(
 BinaryOperatorExpression Expression
-|-UnknownExpression LeftHandSide
-| `-IdExpression
-|   `-UnqualifiedId UnqualifiedId
-| `-'x'
+|-IdExpression LeftHandSide
+| `-UnqualifiedId UnqualifiedId
+|   `-'x'
 |-'+' OperatorToken
 `-IdExpression RightHandSide
   `-UnqualifiedId UnqualifiedId
@@ -3821,26 +3817,135 @@
 )txt"));
 }
 
+TEST_P(SyntaxTreeTest, InitDeclarator_Equal) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { S(int);};
+void test() {
+  [[S s = 1]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s'
+  |-'='
+  `-IntegerLiteralExpression
+`-'1' LiteralToken
+)txt"}));
+}
+
 TEST_P(SyntaxTreeTest, InitDeclarator_Brace) {
   if (!GetParam().isCXX11OrLater()) {
 return;
   }
-  EXPECT_TRUE(treeDumpEqual(
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
   R"cpp(
-int a {};
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test(){
+  [[S s0{}]];
+  [[S s1{1}]];
+  [[S s2{1, 2.}]];
+}
 )cpp",
-  R"txt(
-TranslationUnit Detached
-`-SimpleDeclaration
-  |-'int'
-  |-SimpleDeclarator Declarator
-  | |-'a'
-  | `-UnknownExpression
-  |   `-UnknownExpression
-  | |-'{'
-  | `-'}'
-  `-';'
-)txt"));
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s0'
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s1'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s2'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, InitDeclarator_EqualBrace) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test() {
+  [[S s0 = {}]];
+  [[S s1 = {1}]];
+  [[S s2 = {1, 2.}]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s0'
+  |-'='
+  `-UnknownExpression
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s1'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s2'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
 }
 
 TEST_P(SyntaxTreeTest, InitDeclarator_Paren) {
@@ -3851,15 +3956,133 @@
   R"cpp(
 struct S {
   S(int);
+  S(int, float);
 };
-[[S s(1);]]
+[[S s1(1);]]
+[[S s2(1, 2.);]]
 )cpp",
   {R"txt(
 SimpleDeclaration
 |-'S'
 |-SimpleDeclarator Declarator
 | `-UnknownExpression
-|   |-'s'
+|   |-'s1'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   `-')'
+`-';'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+|-SimpleDeclarator Declarator
+| `-UnknownExpression
+|   |-'s2'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   |-','
+|   |-FloatingLiteralExpression
+|   | `-'2.' LiteralToken
+|   `-')'
+`-';'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, ImplicitConversion_Argument) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct X {
+  X(int);
+};
+void TakeX(const X&);
+void test() {
+  [[TakeX(1)]];
+}
+)cpp",
+  {R"txt(
+CallExpression Expression
+|-IdExpression Callee
+| `-UnqualifiedId UnqualifiedId
+|   `-'TakeX'
+|-'(' OpenParen
+|-CallArguments Arguments
+| `-IntegerLiteralExpression ListElement
+|   `-'1' LiteralToken
+`-')' CloseParen
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, ImplicitConversion_Return) {
+  if (!GetParam().isCXX()) {
+return

[PATCH] D86700: [SyntaxTree] Ignore leaf implicit `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290228.
eduucaldas added a comment.

.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86700/new/

https://reviews.llvm.org/D86700

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1129,6 +1129,12 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+if (S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1129,6 +1129,12 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+if (S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86700: [SyntaxTree] Ignore leaf implicit `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added inline comments.



Comment at: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp:552
   [[::n::S s1]];
   [[n::S s2]];
 }

gribozavr2 wrote:
> Do we have tests for calling constructors with arguments?
> 
> `n::S s3(1, 2, 3);`
> `n::S s3{1, 2, 3};`
> 
> If not, please add them.
We have. I improved their coverage in the parent patch


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86700/new/

https://reviews.llvm.org/D86700

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-07 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 290229.
tambre marked 3 inline comments as done.
tambre added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77491/new/

https://reviews.llvm.org/D77491

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/IdentifierTable.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Headers/intrin.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-attr.cpp
  clang/test/CodeGen/builtin-redeclaration.c
  clang/test/CodeGen/callback_pthread_create.c
  clang/test/CodeGenCXX/builtins.cpp
  clang/test/Sema/implicit-builtin-decl.c
  clang/test/Sema/warn-fortify-source.c
  clang/test/SemaCXX/cxx11-compat.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp

Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -67,10 +67,10 @@
 
 void test() {
   typedef signed long int superint; // no diag
-  printf("%f", (superint) 42);
+  printf("%ld", (superint)42);
 
   typedef signed long int superint2; // no diag
-  printf("%f", static_cast(42));
+  printf("%ld", static_cast(42));
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/test/SemaCXX/cxx11-compat.cpp
===
--- clang/test/SemaCXX/cxx11-compat.cpp
+++ clang/test/SemaCXX/cxx11-compat.cpp
@@ -31,7 +31,7 @@
 s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++11}} expected-note {{explicit cast}}
 t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++11}} expected-warning {{changes value}} expected-note {{explicit cast}}
 
-#define PRIuS "uS"
+#define PRIuS "zu"
 int printf(const char *, ...);
 typedef __typeof(sizeof(int)) size_t;
 void h(size_t foo, size_t bar) {
Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 
 typedef unsigned long size_t;
@@ -13,13 +11,7 @@
 
 extern int sprintf(char *str, const char *format, ...);
 
-#if defined(USE_PASS_OBJECT_SIZE)
-void *memcpy(void *dst, const void *src, size_t c);
-static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) __asm__("merp");
-static void *memcpy(void *const dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) {
-  return 0;
-}
-#elif defined(USE_BUILTINS)
+#if defined(USE_BUILTINS)
 #define memcpy(x,y,z) __builtin_memcpy(x,y,z)
 #else
 void *memcpy(void *dst, const void *src, size_t c);
@@ -45,14 +37,7 @@
   };
   struct pair p;
   char buf[20];
-  memcpy(&p.first, buf, 20);
-#ifdef USE_PASS_OBJECT_SIZE
-  // Use the more strict checking mode on the pass_object_size attribute:
-  // expected-warning@-3 {{memcpy' will always overflow; destination buffer has size 4, but size argument is 20}}
-#else
-  // Or just fallback to type 0:
-  // expected-warning@-6 {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
-#endif
+  memcpy(&p.first, buf, 20); // expected-warning {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
 }
 
 void call_strncat() {
Index: clang/test/Sema/implicit-builtin-decl.c
===
--- clang/test/Sema/implicit-builtin-decl.c
+++ clang/test/Sema/implicit-builtin-decl.c
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// RUN: not %clang_cc1 -fsyntax-only -ast-dump %s | FileCheck %s
 
 void f() {
   int *ptr = malloc(sizeof(int) * 10); // expected-warning{{implicitly declaring library function 'malloc' with type}} \
@@ -63,9 +62,5 @@
 struct __jmp_buf_tag {};
 void sigsetjmp(struct __jmp_buf_tag[1], int); // expected-warning{{declaration of built-in function 'sigsetjmp' requires the declaration of the 'jmp_buf' type, commonly provided in

[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-07 Thread Raul Tambre via Phabricator via cfe-commits
tambre updated this revision to Diff 290232.
tambre marked an inline comment as done.
tambre added a comment.

Remove now obsolete FIXME.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77491/new/

https://reviews.llvm.org/D77491

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/IdentifierTable.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Headers/intrin.h
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/AST/ast-dump-attr.cpp
  clang/test/CodeGen/builtin-redeclaration.c
  clang/test/CodeGen/callback_pthread_create.c
  clang/test/CodeGenCXX/builtins.cpp
  clang/test/Sema/implicit-builtin-decl.c
  clang/test/Sema/warn-fortify-source.c
  clang/test/SemaCXX/cxx11-compat.cpp
  clang/test/SemaCXX/warn-unused-local-typedef.cpp

Index: clang/test/SemaCXX/warn-unused-local-typedef.cpp
===
--- clang/test/SemaCXX/warn-unused-local-typedef.cpp
+++ clang/test/SemaCXX/warn-unused-local-typedef.cpp
@@ -67,10 +67,10 @@
 
 void test() {
   typedef signed long int superint; // no diag
-  printf("%f", (superint) 42);
+  printf("%ld", (superint)42);
 
   typedef signed long int superint2; // no diag
-  printf("%f", static_cast(42));
+  printf("%ld", static_cast(42));
 
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wunused-local-typedef"
Index: clang/test/SemaCXX/cxx11-compat.cpp
===
--- clang/test/SemaCXX/cxx11-compat.cpp
+++ clang/test/SemaCXX/cxx11-compat.cpp
@@ -31,7 +31,7 @@
 s = { n }, // expected-warning {{non-constant-expression cannot be narrowed from type 'int' to 'char' in initializer list in C++11}} expected-note {{explicit cast}}
 t = { 1234 }; // expected-warning {{constant expression evaluates to 1234 which cannot be narrowed to type 'char' in C++11}} expected-warning {{changes value}} expected-note {{explicit cast}}
 
-#define PRIuS "uS"
+#define PRIuS "zu"
 int printf(const char *, ...);
 typedef __typeof(sizeof(int)) size_t;
 void h(size_t foo, size_t bar) {
Index: clang/test/Sema/warn-fortify-source.c
===
--- clang/test/Sema/warn-fortify-source.c
+++ clang/test/Sema/warn-fortify-source.c
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify
-// RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_PASS_OBJECT_SIZE
 // RUN: %clang_cc1 -xc++ -triple x86_64-apple-macosx10.14.0 %s -verify -DUSE_BUILTINS
 
 typedef unsigned long size_t;
@@ -13,13 +11,7 @@
 
 extern int sprintf(char *str, const char *format, ...);
 
-#if defined(USE_PASS_OBJECT_SIZE)
-void *memcpy(void *dst, const void *src, size_t c);
-static void *memcpy(void *dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) __asm__("merp");
-static void *memcpy(void *const dst __attribute__((pass_object_size(1))), const void *src, size_t c) __attribute__((overloadable)) {
-  return 0;
-}
-#elif defined(USE_BUILTINS)
+#if defined(USE_BUILTINS)
 #define memcpy(x,y,z) __builtin_memcpy(x,y,z)
 #else
 void *memcpy(void *dst, const void *src, size_t c);
@@ -45,14 +37,7 @@
   };
   struct pair p;
   char buf[20];
-  memcpy(&p.first, buf, 20);
-#ifdef USE_PASS_OBJECT_SIZE
-  // Use the more strict checking mode on the pass_object_size attribute:
-  // expected-warning@-3 {{memcpy' will always overflow; destination buffer has size 4, but size argument is 20}}
-#else
-  // Or just fallback to type 0:
-  // expected-warning@-6 {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
-#endif
+  memcpy(&p.first, buf, 20); // expected-warning {{memcpy' will always overflow; destination buffer has size 8, but size argument is 20}}
 }
 
 void call_strncat() {
Index: clang/test/Sema/implicit-builtin-decl.c
===
--- clang/test/Sema/implicit-builtin-decl.c
+++ clang/test/Sema/implicit-builtin-decl.c
@@ -1,5 +1,4 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
-// RUN: not %clang_cc1 -fsyntax-only -ast-dump %s | FileCheck %s
 
 void f() {
   int *ptr = malloc(sizeof(int) * 10); // expected-warning{{implicitly declaring library function 'malloc' with type}} \
@@ -63,9 +62,5 @@
 struct __jmp_buf_tag {};
 void sigsetjmp(struct __jmp_buf_tag[1], int); // expected-warning{{declaration of built-in function 'sigsetjmp' requires the declaration of the 'jmp_buf' type, commonly provided 

[PATCH] D77491: [Sema] Introduce BuiltinAttr, per-declaration builtin-ness

2020-09-07 Thread Raul Tambre via Phabricator via cfe-commits
tambre added a comment.

Thanks for the review. All tests still pass, should be good for another round.




Comment at: clang/lib/Sema/SemaDecl.cpp:9672-9673
+  if (unsigned BuiltinID = II->getBuiltinID()) {
+const auto *LinkageDecl =
+dyn_cast(NewFD->getDeclContext());
+

rsmith wrote:
> This will give the wrong answer for
> ```
> extern "C" {
> namespace X {
> void __builtin_foo();
> }
> }
> ```
> ... which does have C language linkage. Instead, please call 
> `FunctionDecl::getLanguageLinkage()`, which knows how to handle these cases.
Good suggestion. This fixes the long-standing FIXME inherited from 
`getBuiltinID()`. I've added a test for this.



Comment at: clang/lib/Serialization/ASTReader.cpp:914
+  return II.hadMacroDefinition() || II.isPoisoned() ||
+ II.getObjCOrBuiltinID() || II.hasRevertedTokenIDToIdentifier() ||
  (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&

rsmith wrote:
> We now consider `getObjCOrBuiltinID()` here for the `IsModule` case, where we 
> didn't before. Is that an intentional change?
Unintentional, fixed.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D77491/new/

https://reviews.llvm.org/D77491

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

I'm in favor of most, if not all of the changes, though I will admit that this 
patch seems pretty cluttered, you are doing a lot of refactoring under the same 
hood. You're moving, adding, removing and changing helper functions and their 
invocations. Would be possible to make this patch a bit leaner?




Comment at: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp:36
+  void handleAssignment(CheckerContext &C, const Expr *CE, SVal Cont,
+Optional = None) const;
+

Hmm, this was changed to an optional, unnamed parameter without docs... Might 
be a bit cryptic :) Also, this seems to be orthogonal to the patch, is it not? 
Does the modeling of `empty()` change something that affects this function?



Comment at: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp:420
+
+  // We cannot make assumpotions on `UnknownVal`. Let us conjure a symbol
+  // instead.

assumpotions > assumptions



Comment at: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp:420-427
+  // We cannot make assumpotions on `UnknownVal`. Let us conjure a symbol
+  // instead.
+  if (RetVal.isUnknown()) {
+auto &SymMgr = C.getSymbolManager();
+RetVal = nonloc::SymbolVal(SymMgr.conjureSymbol(
+CE, LCtx, C.getASTContext().BoolTy, C.blockCount()));
+State = State->BindExpr(CE, LCtx, RetVal);

Szelethus wrote:
> assumpotions > assumptions
You will have to help me out here -- if the analyzer couldn't return a sensible 
symbol, is it okay to just create one? When does `UnknownVal` even happen, does 
it ever happen? Also, if we're doing this anyways, wouldn't using `evalCall` be 
more appropriate?



Comment at: 
clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp:71
+
+  EXPECT_TRUE(runCheckerOnCode(
+  R"(class C {

Did you mean to upload changed to this file from D85351 to this patch as well?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76590/new/

https://reviews.llvm.org/D76590

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85424: [Analyzer] Crash fix for alpha.cplusplus.IteratorRange

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

OK, after a few hours of debugging, the test code simplifies to this:

  // RUN: %clang_analyze_cc1 -std=c++11 
-analyzer-checker=core,cplusplus,alpha.cplusplus.IteratorRange -analyzer-config 
aggressive-binary-operation-simplification=true %s -verify
  
  void foo(int x) {
int uninit;
x - uninit; // will-crash
  }

The investigation showed that the 
`IteratorRangeChecker::verifyRandomIncrOrDecr` will get an `Undefined` sval for 
this example, resulting in a crash.
How should I continue this?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85424/new/

https://reviews.llvm.org/D85424

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87118: Add an explicit toggle for the static analyzer in clang-tidy

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a reviewer: NoQ.
Szelethus added a comment.
Herald added a subscriber: Charusso.

NoQ in particular has been working hard on the common infrastructure in between 
the static analyzer and clang-tidy, I'll add him :)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87118/new/

https://reviews.llvm.org/D87118

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80878: [clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further declarations.

2020-09-07 Thread Raphael Isemann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0478720157f6: [clang] Prevent that Decl::dump on a 
CXXRecordDecl deserialises further… (authored by teemperor).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D80878/new/

https://reviews.llvm.org/D80878

Files:
  clang/lib/AST/TextNodeDumper.cpp
  clang/test/AST/ast-dump-lambda.cpp
  clang/test/AST/ast-dump-records.cpp
  clang/unittests/AST/ASTDumpTest.cpp
  clang/unittests/AST/CMakeLists.txt

Index: clang/unittests/AST/CMakeLists.txt
===
--- clang/unittests/AST/CMakeLists.txt
+++ clang/unittests/AST/CMakeLists.txt
@@ -6,6 +6,7 @@
 
 add_clang_unittest(ASTTests
   ASTContextParentMapTest.cpp
+  ASTDumpTest.cpp
   ASTImporterFixtures.cpp
   ASTImporterTest.cpp
   ASTImporterGenericRedeclTest.cpp
Index: clang/unittests/AST/ASTDumpTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/ASTDumpTest.cpp
@@ -0,0 +1,140 @@
+//===- unittests/AST/ASTDumpTest.cpp --- Declaration tests ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Tests Decl::dump().
+//
+//===--===//
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/SourceManager.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace clang {
+namespace ast {
+
+namespace {
+/// An ExternalASTSource that asserts if it is queried for information about
+/// any declaration.
+class TrappingExternalASTSource : public ExternalASTSource {
+  ~TrappingExternalASTSource() override = default;
+  bool FindExternalVisibleDeclsByName(const DeclContext *,
+  DeclarationName) override {
+assert(false && "Unexpected call to FindExternalVisibleDeclsByName");
+return true;
+  }
+
+  void FindExternalLexicalDecls(const DeclContext *,
+llvm::function_ref,
+SmallVectorImpl &) override {
+assert(false && "Unexpected call to FindExternalLexicalDecls");
+  }
+
+  void completeVisibleDeclsMap(const DeclContext *) override {
+assert(false && "Unexpected call to completeVisibleDeclsMap");
+  }
+
+  void CompleteRedeclChain(const Decl *) override {
+assert(false && "Unexpected call to CompleteRedeclChain");
+  }
+
+  void CompleteType(TagDecl *) override {
+assert(false && "Unexpected call to CompleteType(Tag Decl*)");
+  }
+
+  void CompleteType(ObjCInterfaceDecl *) override {
+assert(false && "Unexpected call to CompleteType(ObjCInterfaceDecl *)");
+  }
+};
+
+/// Tests that Decl::dump doesn't load additional declarations from the
+/// ExternalASTSource.
+class ExternalASTSourceDumpTest : public ::testing::Test {
+protected:
+  ExternalASTSourceDumpTest()
+  : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()),
+Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), Idents(LangOpts, nullptr),
+Ctxt(LangOpts, SourceMgr, Idents, Sels, Builtins) {
+Ctxt.setExternalSource(new TrappingExternalASTSource());
+  }
+
+  FileSystemOptions FileMgrOpts;
+  FileManager FileMgr;
+  IntrusiveRefCntPtr DiagID;
+  DiagnosticsEngine Diags;
+  SourceManager SourceMgr;
+  LangOptions LangOpts;
+  IdentifierTable Idents;
+  SelectorTable Sels;
+  Builtin::Context Builtins;
+  ASTContext Ctxt;
+};
+} // unnamed namespace
+
+/// Set all flags that activate queries to the ExternalASTSource.
+static void setExternalStorageFlags(DeclContext *DC) {
+  DC->setHasExternalLexicalStorage();
+  DC->setHasExternalVisibleStorage();
+  DC->setMustBuildLookupTable();
+}
+
+/// Dumps the given Decl.
+static void dumpDecl(Decl *D) {
+  // Try dumping the decl which shouldn't trigger any calls to the
+  // ExternalASTSource.
+
+  std::string Out;
+  llvm::raw_string_ostream OS(Out);
+  D->dump(OS);
+}
+
+TEST_F(ExternalASTSourceDumpTest, DumpObjCInterfaceDecl) {
+  // Define an Objective-C interface.
+  ObjCInterfaceDecl *I = ObjCInterfaceDecl::Create(
+  Ctxt, Ctxt.getTranslationUnitDecl(), SourceLocation(),
+  &Ctxt.Idents.get("c"), nullptr, nullptr);
+  Ctxt.getTranslationUnitDecl()->addDecl(I);
+
+  setExternalStorageFlags(I);
+  dumpDecl(I);
+}
+
+TEST_F(ExternalASTSourceDumpTest, DumpRecordDecl) {
+  // Define a struct.
+  RecordDecl *R = RecordDecl::Create(
+  Ctxt, TagDecl::TagKind::TTK_Cla

[clang] 0478720 - [clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further declarations.

2020-09-07 Thread Raphael Isemann via cfe-commits

Author: Raphael Isemann
Date: 2020-09-07T12:31:30+02:00
New Revision: 0478720157f6413fad7595b8eff9c70d2d99b637

URL: 
https://github.com/llvm/llvm-project/commit/0478720157f6413fad7595b8eff9c70d2d99b637
DIFF: 
https://github.com/llvm/llvm-project/commit/0478720157f6413fad7595b8eff9c70d2d99b637.diff

LOG: [clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further 
declarations.

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
457226e02a6e8533eaaa864a3fd7c8eeccd2bf58 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

Added: 
clang/unittests/AST/ASTDumpTest.cpp

Modified: 
clang/lib/AST/TextNodeDumper.cpp
clang/test/AST/ast-dump-lambda.cpp
clang/test/AST/ast-dump-records.cpp
clang/unittests/AST/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/AST/TextNodeDumper.cpp 
b/clang/lib/AST/TextNodeDumper.cpp
index 16c4c3736a4a..19b7b4c801d5 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1960,7 +1960,11 @@ void TextNodeDumper::VisitCXXRecordDecl(const 
CXXRecordDecl *D) {
   FLAG(hasTrivialDestructor, trivial);
   FLAG(hasNonTrivialDestructor, non_trivial);
   FLAG(hasUserDeclaredDestructor, user_declared);
-  FLAG(hasConstexprDestructor, constexpr);
+  // Avoid calls to the external source.
+  if (!D->hasExternalVisibleStorage()) {
+FLAG(hasConstexprDestructor, constexpr);
+  } else
+OS << " maybe_constexpr";
   FLAG(needsImplicitDestructor, needs_implicit);
   FLAG(needsOverloadResolutionForDestructor, needs_overload_resolution);
   if (!D->needsOverloadResolutionForDestructor())

diff  --git a/clang/test/AST/ast-dump-lambda.cpp 
b/clang/test/AST/ast-dump-lambda.cpp
index 37fb62ef9930..302b93734459 100644
--- a/clang/test/AST/ast-dump-lambda.cpp
+++ b/clang/test/AST/ast-dump-lambda.cpp
@@ -48,7 +48,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:|   | |-MoveConstructor exists simple trivial needs_implicit
 // CHECK-NEXT:|   | |-CopyAssignment simple trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:|   | |-MoveAssignment exists simple trivial needs_implicit
-// CHECK-NEXT:|   | `-Destructor simple irrelevant trivial needs_implicit
+// CHECK-NEXT:|   | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
 // CHECK-NEXT:|   |-CXXRecordDecl {{.*}}  col:10{{( 
imported)?}} implicit struct V
 // CHECK-NEXT:|   `-CXXMethodDecl {{.*}}  
line:17:10{{( imported)?}} f 'void ()'
 // CHECK-NEXT:| `-CompoundStmt {{.*}} 
@@ -60,7 +60,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:|   | | | |-MoveConstructor exists simple trivial 
needs_implicit
 // CHECK-NEXT:|   | | | |-CopyAssignment trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:|   | | | |-MoveAssignment
-// CHECK-NEXT:|   | | | `-Destructor simple irrelevant trivial 
needs_implicit
+// CHECK-NEXT:|   | | | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
 // CHECK-NEXT:|   | | |-CXXMethodDecl {{.*}}  col:7{{( 
imported)?}} operator() 'auto () const -> auto' inline
 // CHECK-NEXT:|   | | | `-CompoundStmt {{.*}} 
 // CHECK-NEXT:|   | | `-FieldDecl {{.*}}  col:8{{( imported)?}} 
implicit 'V *'
@@ -75,7 +75,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:| | | |-MoveConstructor exists simple trivial 
needs_implicit
 // CHECK-NEXT:| | | |-CopyAssignment trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:| | | |-MoveAssignment
-// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial 
needs_implicit
+// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_

[PATCH] D80878: [clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further declarations.

2020-09-07 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

And what if deserialization is forced?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D80878/new/

https://reviews.llvm.org/D80878

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86632: [Fixed Point] Add codegen for conversion between fixed-point and floating point.

2020-09-07 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan updated this revision to Diff 290245.
ebevhan added a comment.

Added promotion mechanism.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86632/new/

https://reviews.llvm.org/D86632

Files:
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/Frontend/fixed_point_compound.c
  clang/test/Frontend/fixed_point_conversions.c
  clang/test/Frontend/fixed_point_conversions_half.c
  llvm/include/llvm/IR/FixedPointBuilder.h

Index: llvm/include/llvm/IR/FixedPointBuilder.h
===
--- llvm/include/llvm/IR/FixedPointBuilder.h
+++ llvm/include/llvm/IR/FixedPointBuilder.h
@@ -120,6 +120,17 @@
 C.isSigned(), C.isSaturated(), BothPadded);
   }
 
+  /// Given a floating point type and a fixed-point semantic, return a floating
+  /// point type which can accommodate the fixed-point semantic. This is either
+  /// \p Ty, or a floating point type with a larger exponent than Ty.
+  Type *getAccommodatingFloatType(Type *Ty, const FixedPointSemantics &Sema) {
+const fltSemantics *FloatSema = &Ty->getFltSemantics();
+while (!Sema.canAccommodateFloatSemantics(*FloatSema))
+  FloatSema = APFixedPoint::promoteFloatSemantics(FloatSema);
+// There's seemingly no way to convert fltSemantics to Type.
+return ConstantFP::get(Ty->getContext(), APFloat(*FloatSema))->getType();
+  }
+
 public:
   FixedPointBuilder(IRBuilderTy &Builder) : B(Builder) {}
 
@@ -159,6 +170,55 @@
DstSema, false);
   }
 
+  Value *CreateFixedToFloating(Value *Src, const FixedPointSemantics &SrcSema,
+   Type *DstTy) {
+Value *Result;
+Type *OpTy = getAccommodatingFloatType(DstTy, SrcSema);
+// Convert the raw fixed-point value directly to floating point. If the
+// value is too large to fit, it will be rounded, not truncated.
+Result = SrcSema.isSigned() ? B.CreateSIToFP(Src, OpTy)
+: B.CreateUIToFP(Src, OpTy);
+// Rescale the integral-in-floating point by the scaling factor. This is
+// lossless, except for overflow to infinity which is unlikely.
+Result = B.CreateFMul(Result,
+ConstantFP::get(OpTy, std::pow(2, -(int)SrcSema.getScale(;
+if (OpTy != DstTy)
+  Result = B.CreateFPTrunc(Result, DstTy);
+return Result;
+  }
+
+  Value *CreateFloatingToFixed(Value *Src, const FixedPointSemantics &DstSema) {
+bool UseSigned = DstSema.isSigned() || DstSema.hasUnsignedPadding();
+Value *Result = Src;
+Type *OpTy = getAccommodatingFloatType(Src->getType(), DstSema);
+if (OpTy != Src->getType())
+  Result = B.CreateFPExt(Result, OpTy);
+// Rescale the floating point value so that its significant bits (for the
+// purposes of the conversion) are in the integral range.
+Result = B.CreateFMul(Result,
+ConstantFP::get(OpTy, std::pow(2, DstSema.getScale(;
+
+Type *ResultTy = B.getIntNTy(DstSema.getWidth());
+if (DstSema.isSaturated()) {
+  Intrinsic::ID IID =
+  UseSigned ? Intrinsic::fptosi_sat : Intrinsic::fptoui_sat;
+  Result = B.CreateIntrinsic(IID, {ResultTy, OpTy}, {Result});
+} else {
+  Result = UseSigned ? B.CreateFPToSI(Result, ResultTy)
+ : B.CreateFPToUI(Result, ResultTy);
+}
+
+// When saturating unsigned-with-padding using signed operations, we may
+// get negative values. Emit an extra clamp to zero.
+if (DstSema.isSaturated() && DstSema.hasUnsignedPadding()) {
+  Constant *Zero = Constant::getNullValue(Result->getType());
+  Result =
+  B.CreateSelect(B.CreateICmpSLT(Result, Zero), Zero, Result, "satmin");
+}
+
+return Result;
+  }
+
   /// Add two fixed-point values and return the result in their common semantic.
   /// \p LHS - The left hand side
   /// \p LHSSema - The semantic of the left hand side
Index: clang/test/Frontend/fixed_point_conversions_half.c
===
--- /dev/null
+++ clang/test/Frontend/fixed_point_conversions_half.c
@@ -0,0 +1,309 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -ffixed-point -triple arm64-unknown-linux-gnu -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,SIGNED
+// RUN: %clang_cc1 -ffixed-point -triple arm64-unknown-linux-gnu -S -emit-llvm %s -o - -fpadding-on-unsigned-fixed-point | FileCheck %s --check-prefixes=CHECK,UNSIGNED
+
+short _Fract sf;
+long _Fract lf;
+
+short _Accum sa;
+long _Accum la;
+
+unsigned short _Accum usa;
+unsigned long _Accum ula;
+
+_Sat short _Fract sf_sat;
+_Sat long _Fract lf_sat;
+
+_Sat short _Accum sa_sat;
+_Sat long _Accum la_sat;
+
+_Sat unsigned short _Accum usa_sat;
+_Sat unsigned long _Accum ula_sat;
+
+_Float16 h;
+
+
+// CHECK-LABEL: @half_fix1(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load half, half* @h, align 2
+// CHECK-NEXT:[[

[PATCH] D87201: [clang-format] Add a option for the position of Java static import

2020-09-07 Thread Byoungchan Lee via Phabricator via cfe-commits
bc-lee updated this revision to Diff 290246.
bc-lee added a comment.

Modify the comment of Format.h to sync ClangFormatStyleOptions.rst


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87201/new/

https://reviews.llvm.org/D87201

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/unittests/Format/SortImportsTestJava.cpp

Index: clang/unittests/Format/SortImportsTestJava.cpp
===
--- clang/unittests/Format/SortImportsTestJava.cpp
+++ clang/unittests/Format/SortImportsTestJava.cpp
@@ -250,6 +250,30 @@
  "import org.c;\n"));
 }
 
+TEST_F(SortImportsTestJava, FormatJavaStaticImportAfterImport) {
+  FmtStyle.JavaStaticImportAfterImport = true;
+
+  EXPECT_EQ("import com.test.b;\n"
+"import com.test.c;\n"
+"\n"
+"import org.b;\n"
+"\n"
+"import com.b;\n"
+"\n"
+"import static com.test.a;\n"
+"\n"
+"import static org.a;\n"
+"\n"
+"import static com.a;\n",
+sort("import static com.test.a;\n"
+ "import static org.a;\n"
+ "import static com.a;\n"
+ "import com.test.b;\n"
+ "import org.b;\n"
+ "import com.b;\n"
+ "import com.test.c;\n"));
+}
+
 TEST_F(SortImportsTestJava, DeduplicateImports) {
   EXPECT_EQ("import org.a;\n", sort("import org.a;\n"
 "import org.a;\n"));
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -544,6 +544,8 @@
 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
 IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
 IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
+IO.mapOptional("JavaStaticImportAfterImport",
+   Style.JavaStaticImportAfterImport);
 IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
Style.KeepEmptyLinesAtTheStartOfBlocks);
 IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
@@ -901,6 +903,7 @@
   LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
   LLVMStyle.JavaScriptWrapImports = true;
+  LLVMStyle.JavaStaticImportAfterImport = false;
   LLVMStyle.TabWidth = 8;
   LLVMStyle.MaxEmptyLinesToKeep = 1;
   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
@@ -2312,12 +2315,15 @@
 JavaImportGroups.push_back(
 findJavaImportGroup(Style, Imports[i].Identifier));
   }
+  bool StaticImportAfterNormalImport = Style.JavaStaticImportAfterImport;
   llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
 // Negating IsStatic to push static imports above non-static imports.
-return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
-   Imports[LHSI].Identifier) <
-   std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
-   Imports[RHSI].Identifier);
+return std::make_tuple(!Imports[LHSI].IsStatic ^
+   StaticImportAfterNormalImport,
+   JavaImportGroups[LHSI], Imports[LHSI].Identifier) <
+   std::make_tuple(!Imports[RHSI].IsStatic ^
+   StaticImportAfterNormalImport,
+   JavaImportGroups[RHSI], Imports[RHSI].Identifier);
   });
 
   // Deduplicate imports.
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -1689,6 +1689,21 @@
   bool JavaScriptWrapImports;
   // clang-format on
 
+  /// If true, clang-format will put Java static imports after all non-static
+  /// imports.
+  /// \code{.java}
+  ///   true:
+  ///   import static org.example.function1;
+  ///
+  ///   import org.example.ClassA;
+  ///
+  ///   false:
+  ///   import org.example.ClassA;
+  ///
+  ///   import static org.example.function1;
+  /// \endcode
+  bool JavaStaticImportAfterImport;
+
   /// If true, the empty line at the start of blocks is kept.
   /// \code
   ///true:  false:
@@ -2410,6 +2425,7 @@
JavaImportGroups == R.JavaImportGroups &&
JavaScriptQuotes == R.JavaScriptQuotes &&
JavaScriptWrapImports == R.JavaScriptWrapImports &&
+   JavaStaticImportAfterImport == R.JavaStaticImportAfterImport &&
KeepEmptyLinesAtTheStartOfBlocks ==
R.KeepEmptyLinesAtTheStartOfBlocks &&
MacroBlockBegin == R.MacroBlockBegin &&
Index: clang/docs/ClangFormatStyleOptions.rst
=

[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-09-07 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 290248.
baloghadamsoftware added a comment.

Wrong diff uploaded previously. (Accidentally compared to //master// instead of 
the prerequisite.)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76590/new/

https://reviews.llvm.org/D76590

Files:
  clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.cpp
  clang/lib/StaticAnalyzer/Checkers/Iterator.h
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/container-modeling.cpp
  clang/test/Analysis/diagnostics/explicit-suppression.cpp
  clang/test/Analysis/smart-ptr-text-output.cpp

Index: clang/test/Analysis/smart-ptr-text-output.cpp
===
--- clang/test/Analysis/smart-ptr-text-output.cpp
+++ clang/test/Analysis/smart-ptr-text-output.cpp
@@ -80,7 +80,7 @@
 void derefOnStdSwappedNullPtr() {
   std::unique_ptr P; // expected-note {{Default constructed smart pointer 'P' is null}}
   std::unique_ptr PNull; // expected-note {{Default constructed smart pointer 'PNull' is null}}
-  std::swap(P, PNull); // expected-note@Inputs/system-header-simulator-cxx.h:979 {{Swapped null smart pointer 'PNull' with smart pointer 'P'}}
+  std::swap(P, PNull); // expected-note@Inputs/system-header-simulator-cxx.h:987 {{Swapped null smart pointer 'PNull' with smart pointer 'P'}}
   // expected-note@-1 {{Calling 'swap'}}
   // expected-note@-2 {{Returning from 'swap'}}
   P->foo(); // expected-warning {{Dereference of null smart pointer 'P' [alpha.cplusplus.SmartPtr]}}
Index: clang/test/Analysis/diagnostics/explicit-suppression.cpp
===
--- clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:709 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:717 {{Called C++ object pointer is null}}
 #endif
 }
Index: clang/test/Analysis/container-modeling.cpp
===
--- clang/test/Analysis/container-modeling.cpp
+++ clang/test/Analysis/container-modeling.cpp
@@ -16,6 +16,12 @@
 void clang_analyzer_eval(bool);
 void clang_analyzer_warnIfReached();
 
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
 void begin(const std::vector &V) {
   V.begin();
 
@@ -56,6 +62,40 @@
// expected-note@-1{{TRUE}}
 }
 
+
+///
+/// C O N T A I N E R   C A P A C I T Y
+///
+
+
+/// empty()
+
+void empty(const std::vector &V) {
+  for (auto n: V) {}
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{TRUE}} expected-warning@-2{{FALSE}}
+  // expected-note@-3   {{TRUE}} expected-note@-3   {{FALSE}}
+}
+
+void non_empty1(const std::vector &V) {
+  assert(!V.empty()); // expected-note{{'?' condition is true}}
+  for (auto n: V) {}
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{FALSE}}
+  // expected-note@-3   {{FALSE}}
+}
+
+void non_empty2(const std::vector &V) {
+  for (auto n: V) {}
+  assert(!V.empty()); // expected-note{{'?' condition is true}}
+  clang_analyzer_eval(clang_analyzer_container_begin(V) ==
+  clang_analyzer_container_end(V));
+  // expected-warning@-2{{FALSE}}
+  // expected-note@-3   {{FALSE}}
+}
+
 
 ///
 /// C O N T A I N E R   M O D I F I E R S
Index: clang/test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- clang/test/Analysis/Inputs/system-header-simulator-cxx.h
+++ clang/test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -344,6 +344,8 @@
 const T& front() const { return *begin(); }
 T& back() { return *(end() - 1); }
 const T& back() const { return *(end() - 1); }
+
+bool empty() const;
   };
   
   template
@@ -415,6 +417,8 @@
 const T& front() const { return *begin(); }
 T& back() { return *--end(); }
 const T& back() const { return *--end(); }
+
+bool empty() const;
   };
 
   template
@@ -496,6 +500,8 @@
 const T& front() 

[PATCH] D76590: [Analyzer] Model `empty()` member function of containers

2020-09-07 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked an inline comment as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp:36
+  void handleAssignment(CheckerContext &C, const Expr *CE, SVal Cont,
+Optional = None) const;
+

Szelethus wrote:
> Hmm, this was changed to an optional, unnamed parameter without docs... Might 
> be a bit cryptic :) Also, this seems to be orthogonal to the patch, is it 
> not? Does the modeling of `empty()` change something that affects this 
> function?
We discussed with @NoQ a few patches earlier that `UnknownVal` is not a 
`nullptr`-like value for `SVal`s. That time I changed this bad practice in my 
code everywhere, only forgot this particular place. I do not think that this 
deserves its own patch, it is really a tiny thing.



Comment at: clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp:420-427
+  // We cannot make assumpotions on `UnknownVal`. Let us conjure a symbol
+  // instead.
+  if (RetVal.isUnknown()) {
+auto &SymMgr = C.getSymbolManager();
+RetVal = nonloc::SymbolVal(SymMgr.conjureSymbol(
+CE, LCtx, C.getASTContext().BoolTy, C.blockCount()));
+State = State->BindExpr(CE, LCtx, RetVal);

Szelethus wrote:
> Szelethus wrote:
> > assumpotions > assumptions
> You will have to help me out here -- if the analyzer couldn't return a 
> sensible symbol, is it okay to just create one? When does `UnknownVal` even 
> happen, does it ever happen? Also, if we're doing this anyways, wouldn't 
> using `evalCall` be more appropriate?
Actually, both `UnknownVal` and `SymbolVal` containing a `SymbolConjured` 
without constraints are unknown. The main difference (for us) is that we cannot 
assign constraints to `UnknownVal` but we can for `SymbolConjured`. This is the 
reason for replacing it. However, this is not new. We do it in comparison too. 
The best would be to change the infrastructure to never return `UnknownVal` but 
conjure a new symbol instead if we known nothing about the return value. Maybe 
I will put a `FIXME` there. `evalCall()` is not an option, because we do not 
want to lose the possibility that the implementation of `empty()` is inlined by 
the engine.



Comment at: 
clang/unittests/StaticAnalyzer/TestReturnValueUnderConstruction.cpp:71
+
+  EXPECT_TRUE(runCheckerOnCode(
+  R"(class C {

Szelethus wrote:
> Did you mean to upload changed to this file from D85351 to this patch as well?
No, I just uploaded the wrong diff here.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D76590/new/

https://reviews.llvm.org/D76590

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85426: [clangd] Implement FileFilter for the indexer

2020-09-07 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 290256.
kbobyrev added a comment.

"Fail" early.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85426/new/

https://reviews.llvm.org/D85426

Files:
  clang-tools-extra/clangd/index/SymbolCollector.cpp


Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -256,6 +256,9 @@
   assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
   assert(CompletionAllocator && CompletionTUInfo);
   assert(ASTNode.OrigD);
+  auto &SM = ASTCtx->getSourceManager();
+  if (!shouldIndexFile(SM.getFileID(Loc)))
+return true;
   // Indexing API puts canonical decl into D, which might not have a valid
   // source location for implicit/built-in decls. Fallback to original decl in
   // such cases.
@@ -298,7 +301,6 @@
 
   // Mark D as referenced if this is a reference coming from the main file.
   // D may not be an interesting symbol, but it's cheaper to check at the end.
-  auto &SM = ASTCtx->getSourceManager();
   if (Opts.CountReferences &&
   (Roles & static_cast(index::SymbolRole::Reference)) &&
   SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
@@ -405,6 +407,9 @@
 return true;
 
   const auto &SM = PP->getSourceManager();
+  if (!shouldIndexFile(SM.getFileID(Loc)))
+return true;
+
   auto DefLoc = MI->getDefinitionLoc();
   // Also avoid storing predefined macros like __DBL_MIN__.
   if (SM.isWrittenInBuiltinFile(DefLoc))


Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -256,6 +256,9 @@
   assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
   assert(CompletionAllocator && CompletionTUInfo);
   assert(ASTNode.OrigD);
+  auto &SM = ASTCtx->getSourceManager();
+  if (!shouldIndexFile(SM.getFileID(Loc)))
+return true;
   // Indexing API puts canonical decl into D, which might not have a valid
   // source location for implicit/built-in decls. Fallback to original decl in
   // such cases.
@@ -298,7 +301,6 @@
 
   // Mark D as referenced if this is a reference coming from the main file.
   // D may not be an interesting symbol, but it's cheaper to check at the end.
-  auto &SM = ASTCtx->getSourceManager();
   if (Opts.CountReferences &&
   (Roles & static_cast(index::SymbolRole::Reference)) &&
   SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
@@ -405,6 +407,9 @@
 return true;
 
   const auto &SM = PP->getSourceManager();
+  if (!shouldIndexFile(SM.getFileID(Loc)))
+return true;
+
   auto DefLoc = MI->getDefinitionLoc();
   // Also avoid storing predefined macros like __DBL_MIN__.
   if (SM.isWrittenInBuiltinFile(DefLoc))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a8a9153 - [X86] Replace EmitX86AddSubSatExpr with EmitX86BinaryIntrinsic generic helper. NFCI.

2020-09-07 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-09-07T13:33:48+01:00
New Revision: a8a91533dd65041ced68ed5b9348b5d023837488

URL: 
https://github.com/llvm/llvm-project/commit/a8a91533dd65041ced68ed5b9348b5d023837488
DIFF: 
https://github.com/llvm/llvm-project/commit/a8a91533dd65041ced68ed5b9348b5d023837488.diff

LOG: [X86] Replace EmitX86AddSubSatExpr with EmitX86BinaryIntrinsic generic 
helper. NFCI.

Feed the Intrinsic::ID value directly instead of via the IsSigned/IsAddition 
bool flags.

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 1192fbdc1c9d..42fab29ab8aa 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -11543,13 +11543,9 @@ static Value *EmitX86SExtMask(CodeGenFunction &CGF, 
Value *Op,
   return CGF.Builder.CreateSExt(Mask, DstTy, "vpmovm2");
 }
 
-// Emit addition or subtraction with signed/unsigned saturation.
-static Value *EmitX86AddSubSatExpr(CodeGenFunction &CGF,
-   ArrayRef Ops, bool IsSigned,
-   bool IsAddition) {
-  Intrinsic::ID IID =
-  IsSigned ? (IsAddition ? Intrinsic::sadd_sat : Intrinsic::ssub_sat)
-   : (IsAddition ? Intrinsic::uadd_sat : Intrinsic::usub_sat);
+// Emit binary intrinsic with the same type used in result/args.
+static Value *EmitX86BinaryIntrinsic(CodeGenFunction &CGF,
+ ArrayRef Ops, Intrinsic::ID IID) 
{
   llvm::Function *F = CGF.CGM.getIntrinsic(IID, Ops[0]->getType());
   return CGF.Builder.CreateCall(F, {Ops[0], Ops[1]});
 }
@@ -14033,28 +14029,28 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   case X86::BI__builtin_ia32_paddsw256:
   case X86::BI__builtin_ia32_paddsb128:
   case X86::BI__builtin_ia32_paddsw128:
-return EmitX86AddSubSatExpr(*this, Ops, true, true);
+return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::sadd_sat);
   case X86::BI__builtin_ia32_paddusb512:
   case X86::BI__builtin_ia32_paddusw512:
   case X86::BI__builtin_ia32_paddusb256:
   case X86::BI__builtin_ia32_paddusw256:
   case X86::BI__builtin_ia32_paddusb128:
   case X86::BI__builtin_ia32_paddusw128:
-return EmitX86AddSubSatExpr(*this, Ops, false, true);
+return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::uadd_sat);
   case X86::BI__builtin_ia32_psubsb512:
   case X86::BI__builtin_ia32_psubsw512:
   case X86::BI__builtin_ia32_psubsb256:
   case X86::BI__builtin_ia32_psubsw256:
   case X86::BI__builtin_ia32_psubsb128:
   case X86::BI__builtin_ia32_psubsw128:
-return EmitX86AddSubSatExpr(*this, Ops, true, false);
+return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::ssub_sat);
   case X86::BI__builtin_ia32_psubusb512:
   case X86::BI__builtin_ia32_psubusw512:
   case X86::BI__builtin_ia32_psubusb256:
   case X86::BI__builtin_ia32_psubusw256:
   case X86::BI__builtin_ia32_psubusb128:
   case X86::BI__builtin_ia32_psubusw128:
-return EmitX86AddSubSatExpr(*this, Ops, false, false);
+return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::usub_sat);
   }
 }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87101: [X86] Update SSE/AVX ABS intrinsics to emit llvm.abs.* (PR46851)

2020-09-07 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

In D87101#2256557 , @spatel wrote:

> I noticed one other LLVM codegen test that might want to be updated to use 
> the IR intrinsics to be more relevant -- 
> llvm-project/llvm/test/CodeGen/X86/combine-abs.ll. That can be done with this 
> patch or later.

I'm going to address that one in a followup that cleans up the x86 PABS 
intrinsic handling in AutoUpgrade.cpp


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87101/new/

https://reviews.llvm.org/D87101

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86699: [SyntaxTree] Ignore implicit non-leaf `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290259.
eduucaldas added a comment.

Add comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86699/new/

https://reviews.llvm.org/D86699

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp

Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -1745,19 +1745,15 @@
 struct X {
   friend X operator+(X, const X&);
 };
-// FIXME: Remove additional `UnknownExpression` wrapping `x`. For that, ignore
-// implicit copy constructor called on `x`. This should've been ignored already,
-// as we `IgnoreImplicit` when traversing an `Stmt`.
 void test(X x, X y) {
   [[x + y]];
 }
 )cpp",
   {R"txt(
 BinaryOperatorExpression Expression
-|-UnknownExpression LeftHandSide
-| `-IdExpression
-|   `-UnqualifiedId UnqualifiedId
-| `-'x'
+|-IdExpression LeftHandSide
+| `-UnqualifiedId UnqualifiedId
+|   `-'x'
 |-'+' OperatorToken
 `-IdExpression RightHandSide
   `-UnqualifiedId UnqualifiedId
@@ -3821,26 +3817,135 @@
 )txt"));
 }
 
+TEST_P(SyntaxTreeTest, InitDeclarator_Equal) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { S(int);};
+void test() {
+  [[S s = 1]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s'
+  |-'='
+  `-IntegerLiteralExpression
+`-'1' LiteralToken
+)txt"}));
+}
+
 TEST_P(SyntaxTreeTest, InitDeclarator_Brace) {
   if (!GetParam().isCXX11OrLater()) {
 return;
   }
-  EXPECT_TRUE(treeDumpEqual(
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
   R"cpp(
-int a {};
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test(){
+  [[S s0{}]];
+  [[S s1{1}]];
+  [[S s2{1, 2.}]];
+}
 )cpp",
-  R"txt(
-TranslationUnit Detached
-`-SimpleDeclaration
-  |-'int'
-  |-SimpleDeclarator Declarator
-  | |-'a'
-  | `-UnknownExpression
-  |   `-UnknownExpression
-  | |-'{'
-  | `-'}'
-  `-';'
-)txt"));
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s0'
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s1'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  `-UnknownExpression
+|-'s2'
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, InitDeclarator_EqualBrace) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct S { 
+  S();
+  S(int);
+  S(int, float);
+};
+void test() {
+  [[S s0 = {}]];
+  [[S s1 = {1}]];
+  [[S s2 = {1, 2.}]];
+}
+)cpp",
+  {R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s0'
+  |-'='
+  `-UnknownExpression
+|-'{'
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s1'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+`-'}'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+`-SimpleDeclarator Declarator
+  |-'s2'
+  |-'='
+  `-UnknownExpression
+|-'{'
+|-IntegerLiteralExpression
+| `-'1' LiteralToken
+|-','
+|-FloatingLiteralExpression
+| `-'2.' LiteralToken
+`-'}'
+)txt"}));
 }
 
 TEST_P(SyntaxTreeTest, InitDeclarator_Paren) {
@@ -3851,15 +3956,133 @@
   R"cpp(
 struct S {
   S(int);
+  S(int, float);
 };
-[[S s(1);]]
+[[S s1(1);]]
+[[S s2(1, 2.);]]
 )cpp",
   {R"txt(
 SimpleDeclaration
 |-'S'
 |-SimpleDeclarator Declarator
 | `-UnknownExpression
-|   |-'s'
+|   |-'s1'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   `-')'
+`-';'
+  )txt",
+   R"txt(
+SimpleDeclaration
+|-'S'
+|-SimpleDeclarator Declarator
+| `-UnknownExpression
+|   |-'s2'
+|   |-'('
+|   |-IntegerLiteralExpression
+|   | `-'1' LiteralToken
+|   |-','
+|   |-FloatingLiteralExpression
+|   | `-'2.' LiteralToken
+|   `-')'
+`-';'
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, ImplicitConversion_Argument) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqualOnAnnotations(
+  R"cpp(
+struct X {
+  X(int);
+};
+void TakeX(const X&);
+void test() {
+  [[TakeX(1)]];
+}
+)cpp",
+  {R"txt(
+CallExpression Expression
+|-IdExpression Callee
+| `-UnqualifiedId UnqualifiedId
+|   `-'TakeX'
+|-'(' OpenParen
+|-CallArguments Arguments
+| `-IntegerLiteralExpression ListElement
+|   `-'1' LiteralToken
+`-')' CloseParen
+)txt"}));
+}
+
+TEST_P(SyntaxTreeTest, ImplicitConversion_Return) {
+  if (!GetParam().isCXX()) {

[PATCH] D86700: [SyntaxTree] Ignore leaf implicit `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290260.
eduucaldas added a comment.

Add comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86700/new/

https://reviews.llvm.org/D86700

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1132,6 +1132,14 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+// Ignore the implicit default constructs.
+if ((S->getNumArgs() == 0 || isa(S->getArg(0))) &&
+S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -548,9 +548,6 @@
   struct S { };
 }
 void test() {
-  // FIXME: Remove the `UnknownExpression` wrapping `s1` and `s2`. This
-  // `UnknownExpression` comes from a leaf `CXXConstructExpr` in the
-  // ClangAST. We need to ignore leaf implicit nodes.
   [[::n::S s1]];
   [[n::S s2]];
 }
@@ -564,8 +561,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -575,8 +571,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
@@ -608,8 +603,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s1'
+  `-'s1'
 )txt",
R"txt(
 SimpleDeclaration
@@ -623,8 +617,7 @@
 | `-'::' ListDelimiter
 |-'S'
 `-SimpleDeclarator Declarator
-  `-UnknownExpression
-`-'s2'
+  `-'s2'
 )txt"}));
 }
 
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -1132,6 +1132,14 @@
 return true;
   }
 
+  bool WalkUpFromCXXConstructExpr(CXXConstructExpr *S) {
+// Ignore the implicit default constructs.
+if ((S->getNumArgs() == 0 || isa(S->getArg(0))) &&
+S->getParenOrBraceRange().isInvalid())
+  return true;
+return RecursiveASTVisitor::WalkUpFromCXXConstructExpr(S);
+  }
+
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 // To construct a syntax tree of the same shape for calls to built-in and
 // user-defined operators, ignore the `DeclRefExpr` that refers to the
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87229: [SyntaxTree] Ignore implicit `CXXFunctionalCastExpr` wrapping constructor

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 290261.
eduucaldas added a comment.

Add comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87229/new/

https://reviews.llvm.org/D87229

Files:
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/unittests/Tooling/Syntax/BuildTreeTest.cpp


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -4066,7 +4066,6 @@
   X(int);
 };
 X test() {
-  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
@@ -4074,12 +4073,11 @@
 ReturnStatement Statement
 |-'return' IntroducerKeyword
 |-UnknownExpression ReturnValue
-| `-UnknownExpression
-|   |-'X'
-|   |-'('
-|   |-IntegerLiteralExpression
-|   | `-'1' LiteralToken
-|   `-')'
+| |-'X'
+| |-'('
+| |-IntegerLiteralExpression
+| | `-'1' LiteralToken
+| `-')'
 `-';'
 )txt"}));
 }
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/IgnoreExpr.h"
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TypeLoc.h"
@@ -60,9 +61,25 @@
   return E;
 }
 
+// In:
+// struct X {
+//   X(int)
+// };
+// X x = X(1);
+// Ignores the implicit `CXXFunctionalCastExpr` that wraps
+// `CXXConstructExpr X(1)`.
+static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
+  if (auto *F = dyn_cast(E)) {
+if (F->getCastKind() == CK_ConstructorConversion)
+  return F->getSubExpr();
+  }
+  return E;
+}
+
 static Expr *IgnoreImplicit(Expr *E) {
   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
- IgnoreImplicitConstructorSingleStep);
+ IgnoreImplicitConstructorSingleStep,
+ IgnoreCXXFunctionalCastExprWrappingConstructor);
 }
 
 LLVM_ATTRIBUTE_UNUSED


Index: clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
+++ clang/unittests/Tooling/Syntax/BuildTreeTest.cpp
@@ -4066,7 +4066,6 @@
   X(int);
 };
 X test() {
-  // FIXME: Remove `UnknownExpression` due to implicit `CXXFunctionalCastExpr`
   [[return X(1);]]
 }
 )cpp",
@@ -4074,12 +4073,11 @@
 ReturnStatement Statement
 |-'return' IntroducerKeyword
 |-UnknownExpression ReturnValue
-| `-UnknownExpression
-|   |-'X'
-|   |-'('
-|   |-IntegerLiteralExpression
-|   | `-'1' LiteralToken
-|   `-')'
+| |-'X'
+| |-'('
+| |-IntegerLiteralExpression
+| | `-'1' LiteralToken
+| `-')'
 `-';'
 )txt"}));
 }
Index: clang/lib/Tooling/Syntax/BuildTree.cpp
===
--- clang/lib/Tooling/Syntax/BuildTree.cpp
+++ clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -14,6 +14,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/IgnoreExpr.h"
+#include "clang/AST/OperationKinds.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TypeLoc.h"
@@ -60,9 +61,25 @@
   return E;
 }
 
+// In:
+// struct X {
+//   X(int)
+// };
+// X x = X(1);
+// Ignores the implicit `CXXFunctionalCastExpr` that wraps
+// `CXXConstructExpr X(1)`.
+static Expr *IgnoreCXXFunctionalCastExprWrappingConstructor(Expr *E) {
+  if (auto *F = dyn_cast(E)) {
+if (F->getCastKind() == CK_ConstructorConversion)
+  return F->getSubExpr();
+  }
+  return E;
+}
+
 static Expr *IgnoreImplicit(Expr *E) {
   return IgnoreExprNodes(E, IgnoreImplicitSingleStep,
- IgnoreImplicitConstructorSingleStep);
+ IgnoreImplicitConstructorSingleStep,
+ IgnoreCXXFunctionalCastExprWrappingConstructor);
 }
 
 LLVM_ATTRIBUTE_UNUSED
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86699: [SyntaxTree] Ignore implicit non-leaf `CXXConstructExpr`

2020-09-07 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:48-50
+// Ignores the implicit `CXXConstructExpr` for copy/move constructors generated
+// by the compiler, as well as in implicit conversions like the one wrapping 
`1`
+// in `X x = 1;`.

Please give feedback on this comments and should I comment the rest of the 
function?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86699/new/

https://reviews.llvm.org/D86699

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86632: [Fixed Point] Add codegen for conversion between fixed-point and floating point.

2020-09-07 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan updated this revision to Diff 290267.
ebevhan added a comment.

Rebased.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86632/new/

https://reviews.llvm.org/D86632

Files:
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/Frontend/fixed_point_compound.c
  clang/test/Frontend/fixed_point_conversions.c
  clang/test/Frontend/fixed_point_conversions_half.c
  llvm/include/llvm/IR/FixedPointBuilder.h

Index: llvm/include/llvm/IR/FixedPointBuilder.h
===
--- llvm/include/llvm/IR/FixedPointBuilder.h
+++ llvm/include/llvm/IR/FixedPointBuilder.h
@@ -120,6 +120,17 @@
 C.isSigned(), C.isSaturated(), BothPadded);
   }
 
+  /// Given a floating point type and a fixed-point semantic, return a floating
+  /// point type which can accommodate the fixed-point semantic. This is either
+  /// \p Ty, or a floating point type with a larger exponent than Ty.
+  Type *getAccommodatingFloatType(Type *Ty, const FixedPointSemantics &Sema) {
+const fltSemantics *FloatSema = &Ty->getFltSemantics();
+while (!Sema.canAccommodateFloatSemantics(*FloatSema))
+  FloatSema = APFixedPoint::promoteFloatSemantics(FloatSema);
+// There's seemingly no way to convert fltSemantics to Type.
+return ConstantFP::get(Ty->getContext(), APFloat(*FloatSema))->getType();
+  }
+
 public:
   FixedPointBuilder(IRBuilderTy &Builder) : B(Builder) {}
 
@@ -159,6 +170,55 @@
DstSema, false);
   }
 
+  Value *CreateFixedToFloating(Value *Src, const FixedPointSemantics &SrcSema,
+   Type *DstTy) {
+Value *Result;
+Type *OpTy = getAccommodatingFloatType(DstTy, SrcSema);
+// Convert the raw fixed-point value directly to floating point. If the
+// value is too large to fit, it will be rounded, not truncated.
+Result = SrcSema.isSigned() ? B.CreateSIToFP(Src, OpTy)
+: B.CreateUIToFP(Src, OpTy);
+// Rescale the integral-in-floating point by the scaling factor. This is
+// lossless, except for overflow to infinity which is unlikely.
+Result = B.CreateFMul(Result,
+ConstantFP::get(OpTy, std::pow(2, -(int)SrcSema.getScale(;
+if (OpTy != DstTy)
+  Result = B.CreateFPTrunc(Result, DstTy);
+return Result;
+  }
+
+  Value *CreateFloatingToFixed(Value *Src, const FixedPointSemantics &DstSema) {
+bool UseSigned = DstSema.isSigned() || DstSema.hasUnsignedPadding();
+Value *Result = Src;
+Type *OpTy = getAccommodatingFloatType(Src->getType(), DstSema);
+if (OpTy != Src->getType())
+  Result = B.CreateFPExt(Result, OpTy);
+// Rescale the floating point value so that its significant bits (for the
+// purposes of the conversion) are in the integral range.
+Result = B.CreateFMul(Result,
+ConstantFP::get(OpTy, std::pow(2, DstSema.getScale(;
+
+Type *ResultTy = B.getIntNTy(DstSema.getWidth());
+if (DstSema.isSaturated()) {
+  Intrinsic::ID IID =
+  UseSigned ? Intrinsic::fptosi_sat : Intrinsic::fptoui_sat;
+  Result = B.CreateIntrinsic(IID, {ResultTy, OpTy}, {Result});
+} else {
+  Result = UseSigned ? B.CreateFPToSI(Result, ResultTy)
+ : B.CreateFPToUI(Result, ResultTy);
+}
+
+// When saturating unsigned-with-padding using signed operations, we may
+// get negative values. Emit an extra clamp to zero.
+if (DstSema.isSaturated() && DstSema.hasUnsignedPadding()) {
+  Constant *Zero = Constant::getNullValue(Result->getType());
+  Result =
+  B.CreateSelect(B.CreateICmpSLT(Result, Zero), Zero, Result, "satmin");
+}
+
+return Result;
+  }
+
   /// Add two fixed-point values and return the result in their common semantic.
   /// \p LHS - The left hand side
   /// \p LHSSema - The semantic of the left hand side
Index: clang/test/Frontend/fixed_point_conversions_half.c
===
--- /dev/null
+++ clang/test/Frontend/fixed_point_conversions_half.c
@@ -0,0 +1,309 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -ffixed-point -triple arm64-unknown-linux-gnu -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,SIGNED
+// RUN: %clang_cc1 -ffixed-point -triple arm64-unknown-linux-gnu -S -emit-llvm %s -o - -fpadding-on-unsigned-fixed-point | FileCheck %s --check-prefixes=CHECK,UNSIGNED
+
+short _Fract sf;
+long _Fract lf;
+
+short _Accum sa;
+long _Accum la;
+
+unsigned short _Accum usa;
+unsigned long _Accum ula;
+
+_Sat short _Fract sf_sat;
+_Sat long _Fract lf_sat;
+
+_Sat short _Accum sa_sat;
+_Sat long _Accum la_sat;
+
+_Sat unsigned short _Accum usa_sat;
+_Sat unsigned long _Accum ula_sat;
+
+_Float16 h;
+
+
+// CHECK-LABEL: @half_fix1(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = load half, half* @h, align 2
+// CHECK-NEXT:[[TMP1:%.*]] = fmul 

[PATCH] D86631: [Fixed Point] Add fixed-point to floating point cast types and consteval.

2020-09-07 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan updated this revision to Diff 290266.
ebevhan added a comment.

Rebased.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86631/new/

https://reviews.llvm.org/D86631

Files:
  clang/include/clang/AST/OperationKinds.def
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGExprComplex.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Edit/RewriteObjCFoundationAPI.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
  clang/test/Frontend/fixed_point_conversions_const.c
  clang/test/Frontend/fixed_point_errors.c
  clang/test/Frontend/fixed_point_unknown_conversions.c

Index: clang/test/Frontend/fixed_point_unknown_conversions.c
===
--- clang/test/Frontend/fixed_point_unknown_conversions.c
+++ clang/test/Frontend/fixed_point_unknown_conversions.c
@@ -22,16 +22,12 @@
   _Fract fract = accum; // ok
   _Accum *accum_ptr;
 
-  accum = f;   // expected-error{{conversion between fixed point and 'float' is not yet supported}}
-  accum = d;   // expected-error{{conversion between fixed point and 'double' is not yet supported}}
   accum = dc;  // expected-error{{conversion between fixed point and '_Complex double' is not yet supported}}
   accum = ic;  // expected-error{{conversion between fixed point and '_Complex int' is not yet supported}}
   accum = s;   // expected-error{{assigning to '_Accum' from incompatible type 'struct S'}}
   accum = ptr; // expected-error{{assigning to '_Accum' from incompatible type 'int *'}}
   accum_ptr = ptr; // expected-warning{{incompatible pointer types assigning to '_Accum *' from 'int *'}}
 
-  f = accum;   // expected-error{{conversion between fixed point and 'float' is not yet supported}}
-  d = accum;   // expected-error{{conversion between fixed point and 'double' is not yet supported}}
   dc = accum;  // expected-error{{conversion between fixed point and '_Complex double' is not yet supported}}
   ic = accum;  // expected-error{{conversion between fixed point and '_Complex int' is not yet supported}}
   s = accum;   // expected-error{{assigning to 'struct S' from incompatible type '_Accum'}}
Index: clang/test/Frontend/fixed_point_errors.c
===
--- clang/test/Frontend/fixed_point_errors.c
+++ clang/test/Frontend/fixed_point_errors.c
@@ -286,8 +286,3 @@
 
 // Division by zero
 short _Accum div_zero = 4.5k / 0.0lr;  // expected-error {{initializer element is not a compile-time constant}}
-
-void foo(void) {
-  _Accum x = 0.5k;
-  if (x == 0.5) {} // expected-error{{invalid operands to binary expression ('_Accum' and 'double')}}
-}
Index: clang/test/Frontend/fixed_point_conversions_const.c
===
--- clang/test/Frontend/fixed_point_conversions_const.c
+++ clang/test/Frontend/fixed_point_conversions_const.c
@@ -43,6 +43,37 @@
 short _Accum sa_const7 = -256;
 // CHECK-DAG: @sa_const7 = {{.*}}global i16 -32768, align 2
 
+// Fixed point to floating point
+float fl_const = 1.0hk;
+// CHECK-DAG: @fl_const = {{.*}}global float 1.00e+00, align 4
+float fl_const2 = -128.0k;
+// CHECK-DAG: @fl_const2 = {{.*}}global float -1.28e+02, align 4
+float fl_const3 = 0.0872802734375k;
+// CHECK-DAG: @fl_const3 = {{.*}}global float 0x3FB65800, align 4
+float fl_const4 = 192.5k;
+// CHECK-DAG: @fl_const4 = {{.*}}global float 1.925000e+02, align 4
+float fl_const5 = -192.5k;
+// CHECK-DAG: @fl_const5 = {{.*}}global float -1.925000e+02, align 4
+
+// Floating point to fixed point
+_Accum a_fl_const = 1.0f;
+// CHECK-DAG: @a_fl_const = {{.*}}global i32 32768, align 4
+_Accum a_fl_const2 = -128.0f;
+// CHECK-DAG: @a_fl_const2 = {{.*}}global i32 -4194304, align 4
+_Accum a_fl_const3 = 0.0872802734375f;
+// CHECK-DAG: @a_fl_const3 = {{.*}}global i32 2860, align 4
+_Accum a_fl_const4 = 0.0872802734375;
+// CHECK-DAG: @a_fl_const4 = {{.*}}global i32 2860, align 4
+_Accum a_fl_const5 = -0.0872802734375f;
+// CHECK-DAG: @a_fl_const5 = {{.*}}global i32 -2860, align 4
+_Fract f_fl_const = 0.5f;
+// CHECK-DAG: @f_fl_const = {{.*}}global i16 16384, align 2
+_Fract f_fl_const2 = -0.75;
+// CHECK-DAG: @f_fl_const2 = {{.*}}global i16 -24576, align 2
+unsigned short _Accum usa_fl_const = 48.75f;
+// SIGNED-DAG: @usa_fl_const = {{.*}}global i16 12480, align 2
+// UNSIGNED-DAG: @usa_fl_const = {{.*}}global i16 6240, align 2
+
 // Signedness
 unsigned short _Accum usa_const2 = 2.5hk;
 // SIGNED-DAG: @usa_const2  = {{.*}}global i16 640, align 2
Index: clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -4

[PATCH] D80878: [clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further declarations.

2020-09-07 Thread Raphael Isemann via Phabricator via cfe-commits
teemperor reopened this revision.
teemperor added a comment.
This revision is now accepted and ready to land.

In D80878#2258942 , @riccibruno wrote:

> And what if deserialization is forced?

That's a good point. That should indeed continue to work with the ASTDumper and 
now (potentially) doesn't. I'll revert.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D80878/new/

https://reviews.llvm.org/D80878

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 23f700c - Revert "[clang] Prevent that Decl::dump on a CXXRecordDecl deserialises further declarations."

2020-09-07 Thread Raphael Isemann via cfe-commits

Author: Raphael Isemann
Date: 2020-09-07T14:50:13+02:00
New Revision: 23f700c785a141355fa6d022552aafc73135bf5d

URL: 
https://github.com/llvm/llvm-project/commit/23f700c785a141355fa6d022552aafc73135bf5d
DIFF: 
https://github.com/llvm/llvm-project/commit/23f700c785a141355fa6d022552aafc73135bf5d.diff

LOG: Revert "[clang] Prevent that Decl::dump on a CXXRecordDecl deserialises 
further declarations."

This reverts commit 0478720157f6413fad7595b8eff9c70d2d99b637. This probably
doesn't work when forcing deserialising while dumping (which the ASTDumper
optionally supports).

Added: 


Modified: 
clang/lib/AST/TextNodeDumper.cpp
clang/test/AST/ast-dump-lambda.cpp
clang/test/AST/ast-dump-records.cpp
clang/unittests/AST/CMakeLists.txt

Removed: 
clang/unittests/AST/ASTDumpTest.cpp



diff  --git a/clang/lib/AST/TextNodeDumper.cpp 
b/clang/lib/AST/TextNodeDumper.cpp
index 19b7b4c801d5..16c4c3736a4a 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1960,11 +1960,7 @@ void TextNodeDumper::VisitCXXRecordDecl(const 
CXXRecordDecl *D) {
   FLAG(hasTrivialDestructor, trivial);
   FLAG(hasNonTrivialDestructor, non_trivial);
   FLAG(hasUserDeclaredDestructor, user_declared);
-  // Avoid calls to the external source.
-  if (!D->hasExternalVisibleStorage()) {
-FLAG(hasConstexprDestructor, constexpr);
-  } else
-OS << " maybe_constexpr";
+  FLAG(hasConstexprDestructor, constexpr);
   FLAG(needsImplicitDestructor, needs_implicit);
   FLAG(needsOverloadResolutionForDestructor, needs_overload_resolution);
   if (!D->needsOverloadResolutionForDestructor())

diff  --git a/clang/test/AST/ast-dump-lambda.cpp 
b/clang/test/AST/ast-dump-lambda.cpp
index 302b93734459..37fb62ef9930 100644
--- a/clang/test/AST/ast-dump-lambda.cpp
+++ b/clang/test/AST/ast-dump-lambda.cpp
@@ -48,7 +48,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:|   | |-MoveConstructor exists simple trivial needs_implicit
 // CHECK-NEXT:|   | |-CopyAssignment simple trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:|   | |-MoveAssignment exists simple trivial needs_implicit
-// CHECK-NEXT:|   | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
+// CHECK-NEXT:|   | `-Destructor simple irrelevant trivial needs_implicit
 // CHECK-NEXT:|   |-CXXRecordDecl {{.*}}  col:10{{( 
imported)?}} implicit struct V
 // CHECK-NEXT:|   `-CXXMethodDecl {{.*}}  
line:17:10{{( imported)?}} f 'void ()'
 // CHECK-NEXT:| `-CompoundStmt {{.*}} 
@@ -60,7 +60,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:|   | | | |-MoveConstructor exists simple trivial 
needs_implicit
 // CHECK-NEXT:|   | | | |-CopyAssignment trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:|   | | | |-MoveAssignment
-// CHECK-NEXT:|   | | | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
+// CHECK-NEXT:|   | | | `-Destructor simple irrelevant trivial 
needs_implicit
 // CHECK-NEXT:|   | | |-CXXMethodDecl {{.*}}  col:7{{( 
imported)?}} operator() 'auto () const -> auto' inline
 // CHECK-NEXT:|   | | | `-CompoundStmt {{.*}} 
 // CHECK-NEXT:|   | | `-FieldDecl {{.*}}  col:8{{( imported)?}} 
implicit 'V *'
@@ -75,7 +75,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:| | | |-MoveConstructor exists simple trivial 
needs_implicit
 // CHECK-NEXT:| | | |-CopyAssignment trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:| | | |-MoveAssignment
-// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
+// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial 
needs_implicit
 // CHECK-NEXT:| | |-CXXMethodDecl {{.*}}  col:7{{( 
imported)?}} operator() 'auto () const -> auto' inline
 // CHECK-NEXT:| | | `-CompoundStmt {{.*}} 
 // CHECK-NEXT:| | `-FieldDecl {{.*}}  col:8{{( imported)?}} 
implicit 'V'
@@ -94,7 +94,7 @@ template  void test(Ts... a) {
 // CHECK-NEXT:| | | |-MoveConstructor exists simple trivial needs_implicit
 // CHECK-NEXT:| | | |-CopyAssignment trivial has_const_param 
needs_implicit implicit_has_const_param
 // CHECK-NEXT:| | | |-MoveAssignment
-// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial{{( 
maybe_constexpr)?}} needs_implicit
+// CHECK-NEXT:| | | `-Destructor simple irrelevant trivial needs_implicit
 // CHECK-NEXT:| | |-CXXMethodDecl {{.*}}  col:3{{( 
imported)?}} operator() 'auto () const' inline
 // CHECK-NEXT:| | | `-CompoundStmt {{.*}} 
 // CHECK-NEXT:| | |-CXXConversionDecl {{.*}}  col:3{{( 
imported)?}} implicit constexpr operator auto (*)() 'auto (*() const 
noexcept)()' inline
@@ -108

[clang] 2853ae3 - [X86] Update SSE/AVX ABS intrinsics to emit llvm.abs.* (PR46851)

2020-09-07 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-09-07T13:54:12+01:00
New Revision: 2853ae3c1b8174e3660424ffac45922601f700ee

URL: 
https://github.com/llvm/llvm-project/commit/2853ae3c1b8174e3660424ffac45922601f700ee
DIFF: 
https://github.com/llvm/llvm-project/commit/2853ae3c1b8174e3660424ffac45922601f700ee.diff

LOG: [X86] Update SSE/AVX ABS intrinsics to emit llvm.abs.* (PR46851)

We're now getting close to having the necessary analysis/combines etc. for the 
new generic llvm.abs.* intrinsics.

This patch updates the SSE/AVX ABS vector intrinsics to emit the generic 
equivalents instead of the icmp+sub+select code pattern.

Differential Revision: https://reviews.llvm.org/D87101

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/avx2-builtins.c
clang/test/CodeGen/avx512bw-builtins.c
clang/test/CodeGen/avx512f-builtins.c
clang/test/CodeGen/avx512vl-builtins.c
clang/test/CodeGen/avx512vlbw-builtins.c
clang/test/CodeGen/ssse3-builtins.c
llvm/test/CodeGen/X86/avx2-intrinsics-fast-isel.ll
llvm/test/CodeGen/X86/ssse3-intrinsics-fast-isel.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 42fab29ab8aa..0cb8f8f636f4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -11314,16 +11314,6 @@ static Value *EmitX86ConvertIntToFp(CodeGenFunction 
&CGF,
   return EmitX86Select(CGF, Ops[2], Res, Ops[1]);
 }
 
-static Value *EmitX86Abs(CodeGenFunction &CGF, ArrayRef Ops) {
-
-  llvm::Type *Ty = Ops[0]->getType();
-  Value *Zero = llvm::Constant::getNullValue(Ty);
-  Value *Sub = CGF.Builder.CreateSub(Zero, Ops[0]);
-  Value *Cmp = CGF.Builder.CreateICmp(ICmpInst::ICMP_SGT, Ops[0], Zero);
-  Value *Res = CGF.Builder.CreateSelect(Cmp, Ops[0], Sub);
-  return Res;
-}
-
 static Value *EmitX86MinMax(CodeGenFunction &CGF, ICmpInst::Predicate Pred,
 ArrayRef Ops) {
   Value *Cmp = CGF.Builder.CreateICmp(Pred, Ops[0], Ops[1]);
@@ -13300,9 +13290,10 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   case X86::BI__builtin_ia32_pabsb512:
   case X86::BI__builtin_ia32_pabsw512:
   case X86::BI__builtin_ia32_pabsd512:
-  case X86::BI__builtin_ia32_pabsq512:
-return EmitX86Abs(*this, Ops);
-
+  case X86::BI__builtin_ia32_pabsq512: {
+Function *F = CGM.getIntrinsic(Intrinsic::abs, Ops[0]->getType());
+return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
+  }
   case X86::BI__builtin_ia32_pmaxsb128:
   case X86::BI__builtin_ia32_pmaxsw128:
   case X86::BI__builtin_ia32_pmaxsd128:

diff  --git a/clang/test/CodeGen/avx2-builtins.c 
b/clang/test/CodeGen/avx2-builtins.c
index 95659895eeaf..f3de6d1b8747 100644
--- a/clang/test/CodeGen/avx2-builtins.c
+++ b/clang/test/CodeGen/avx2-builtins.c
@@ -8,25 +8,19 @@
 
 __m256i test_mm256_abs_epi8(__m256i a) {
   // CHECK-LABEL: test_mm256_abs_epi8
-  // CHECK: [[SUB:%.*]] = sub <32 x i8> zeroinitializer, %{{.*}}
-  // CHECK: [[CMP:%.*]] = icmp sgt <32 x i8> %{{.*}}, zeroinitializer
-  // CHECK: select <32 x i1> [[CMP]], <32 x i8> %{{.*}}, <32 x i8> [[SUB]]
+  // CHECK: [[ABS:%.*]] = call <32 x i8> @llvm.abs.v32i8(<32 x i8> %{{.*}}, i1 
false)
   return _mm256_abs_epi8(a);
 }
 
 __m256i test_mm256_abs_epi16(__m256i a) {
   // CHECK-LABEL: test_mm256_abs_epi16
-  // CHECK: [[SUB:%.*]] = sub <16 x i16> zeroinitializer, %{{.*}}
-  // CHECK: [[CMP:%.*]] = icmp sgt <16 x i16> %{{.*}}, zeroinitializer
-  // CHECK: select <16 x i1> [[CMP]], <16 x i16> %{{.*}}, <16 x i16> [[SUB]]
+  // CHECK: [[ABS:%.*]] = call <16 x i16> @llvm.abs.v16i16(<16 x i16> %{{.*}}, 
i1 false)
   return _mm256_abs_epi16(a);
 }
 
 __m256i test_mm256_abs_epi32(__m256i a) {
   // CHECK-LABEL: test_mm256_abs_epi32
-  // CHECK: [[SUB:%.*]] = sub <8 x i32> zeroinitializer, %{{.*}}
-  // CHECK: [[CMP:%.*]] = icmp sgt <8 x i32> %{{.*}}, zeroinitializer
-  // CHECK: select <8 x i1> [[CMP]], <8 x i32> %{{.*}}, <8 x i32> [[SUB]]
+  // CHECK: [[ABS:%.*]] = call <8 x i32> @llvm.abs.v8i32(<8 x i32> %{{.*}}, i1 
false)
   return _mm256_abs_epi32(a);
 }
 

diff  --git a/clang/test/CodeGen/avx512bw-builtins.c 
b/clang/test/CodeGen/avx512bw-builtins.c
index c08b354d9519..cc173f1a9cfe 100644
--- a/clang/test/CodeGen/avx512bw-builtins.c
+++ b/clang/test/CodeGen/avx512bw-builtins.c
@@ -878,48 +878,36 @@ __m512i test_mm512_mask_blend_epi16(__mmask32 __U, 
__m512i __A, __m512i __W) {
 }
 __m512i test_mm512_abs_epi8(__m512i __A) {
   // CHECK-LABEL: @test_mm512_abs_epi8
-  // CHECK: [[SUB:%.*]] = sub <64 x i8> zeroinitializer, [[A:%.*]]
-  // CHECK: [[CMP:%.*]] = icmp sgt <64 x i8> [[A]], zeroinitializer
-  // CHECK: select <64 x i1> [[CMP]], <64 x i8> [[A]], <64 x i8> [[SUB]]
+  // CHECK: [[ABS:%.*]] = call <64 x i8> @llvm.abs.v64i8(<64 x i8> %{{.*}}, i1 
false)
   return _mm512_abs_epi8(__A); 
 }
 __m512i test_mm512_mask_abs_epi8(__m512i __W, __mmask64 __U, __m512i __A) {

[PATCH] D87101: [X86] Update SSE/AVX ABS intrinsics to emit llvm.abs.* (PR46851)

2020-09-07 Thread Simon Pilgrim via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2853ae3c1b81: [X86] Update SSE/AVX ABS intrinsics to emit 
llvm.abs.* (PR46851) (authored by RKSimon).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87101/new/

https://reviews.llvm.org/D87101

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/avx2-builtins.c
  clang/test/CodeGen/avx512bw-builtins.c
  clang/test/CodeGen/avx512f-builtins.c
  clang/test/CodeGen/avx512vl-builtins.c
  clang/test/CodeGen/avx512vlbw-builtins.c
  clang/test/CodeGen/ssse3-builtins.c
  llvm/test/CodeGen/X86/avx2-intrinsics-fast-isel.ll
  llvm/test/CodeGen/X86/ssse3-intrinsics-fast-isel.ll

Index: llvm/test/CodeGen/X86/ssse3-intrinsics-fast-isel.ll
===
--- llvm/test/CodeGen/X86/ssse3-intrinsics-fast-isel.ll
+++ llvm/test/CodeGen/X86/ssse3-intrinsics-fast-isel.ll
@@ -19,13 +19,11 @@
 ; AVX-NEXT:vpabsb %xmm0, %xmm0
 ; AVX-NEXT:ret{{[l|q]}}
   %arg = bitcast <2 x i64> %a0 to <16 x i8>
-  %sub = sub <16 x i8> zeroinitializer, %arg
-  %cmp = icmp sgt <16 x i8> %arg, zeroinitializer
-  %sel = select <16 x i1> %cmp, <16 x i8> %arg, <16 x i8> %sub
-  %res = bitcast <16 x i8> %sel to <2 x i64>
+  %abs = call <16 x i8> @llvm.abs.v16i8(<16 x i8> %arg, i1 false)
+  %res = bitcast <16 x i8> %abs to <2 x i64>
   ret <2 x i64> %res
 }
-declare <16 x i8> @llvm.x86.ssse3.pabs.b.128(<16 x i8>) nounwind readnone
+declare <16 x i8> @llvm.abs.v16i8(<16 x i8>, i1) nounwind readnone
 
 define <2 x i64> @test_mm_abs_epi16(<2 x i64> %a0) {
 ; SSE-LABEL: test_mm_abs_epi16:
@@ -38,13 +36,11 @@
 ; AVX-NEXT:vpabsw %xmm0, %xmm0
 ; AVX-NEXT:ret{{[l|q]}}
   %arg = bitcast <2 x i64> %a0 to <8 x i16>
-  %sub = sub <8 x i16> zeroinitializer, %arg
-  %cmp = icmp sgt <8 x i16> %arg, zeroinitializer
-  %sel = select <8 x i1> %cmp, <8 x i16> %arg, <8 x i16> %sub
-  %res = bitcast <8 x i16> %sel to <2 x i64>
+  %abs = call <8 x i16> @llvm.abs.v8i16(<8 x i16> %arg, i1 false)
+  %res = bitcast <8 x i16> %abs to <2 x i64>
   ret <2 x i64> %res
 }
-declare <8 x i16> @llvm.x86.ssse3.pabs.w.128(<8 x i16>) nounwind readnone
+declare <8 x i16> @llvm.abs.v8i16(<8 x i16>, i1) nounwind readnone
 
 define <2 x i64> @test_mm_abs_epi32(<2 x i64> %a0) {
 ; SSE-LABEL: test_mm_abs_epi32:
@@ -57,13 +53,11 @@
 ; AVX-NEXT:vpabsd %xmm0, %xmm0
 ; AVX-NEXT:ret{{[l|q]}}
   %arg = bitcast <2 x i64> %a0 to <4 x i32>
-  %sub = sub <4 x i32> zeroinitializer, %arg
-  %cmp = icmp sgt <4 x i32> %arg, zeroinitializer
-  %sel = select <4 x i1> %cmp, <4 x i32> %arg, <4 x i32> %sub
-  %res = bitcast <4 x i32> %sel to <2 x i64>
+  %abs = call <4 x i32> @llvm.abs.v4i32(<4 x i32> %arg, i1 false)
+  %res = bitcast <4 x i32> %abs to <2 x i64>
   ret <2 x i64> %res
 }
-declare <4 x i32> @llvm.x86.ssse3.pabs.d.128(<4 x i32>) nounwind readnone
+declare <4 x i32> @llvm.abs.v4i32(<4 x i32>, i1) nounwind readnone
 
 define <2 x i64> @test_mm_alignr_epi8(<2 x i64> %a0, <2 x i64> %a1) {
 ; SSE-LABEL: test_mm_alignr_epi8:
Index: llvm/test/CodeGen/X86/avx2-intrinsics-fast-isel.ll
===
--- llvm/test/CodeGen/X86/avx2-intrinsics-fast-isel.ll
+++ llvm/test/CodeGen/X86/avx2-intrinsics-fast-isel.ll
@@ -10,13 +10,11 @@
 ; CHECK-NEXT:vpabsb %ymm0, %ymm0
 ; CHECK-NEXT:ret{{[l|q]}}
   %arg = bitcast <4 x i64> %a0 to <32 x i8>
-  %sub = sub <32 x i8> zeroinitializer, %arg
-  %cmp = icmp sgt <32 x i8> %arg, zeroinitializer
-  %sel = select <32 x i1> %cmp, <32 x i8> %arg, <32 x i8> %sub
-  %res = bitcast <32 x i8> %sel to <4 x i64>
+  %abs = call <32 x i8> @llvm.abs.v32i8(<32 x i8> %arg, i1 false)
+  %res = bitcast <32 x i8> %abs to <4 x i64>
   ret <4 x i64> %res
 }
-declare <32 x i8> @llvm.x86.avx2.pabs.b(<32 x i8>) nounwind readnone
+declare <32 x i8> @llvm.abs.v32i8(<32 x i8>, i1) nounwind readnone
 
 define <4 x i64> @test_mm256_abs_epi16(<4 x i64> %a0) {
 ; CHECK-LABEL: test_mm256_abs_epi16:
@@ -24,13 +22,11 @@
 ; CHECK-NEXT:vpabsw %ymm0, %ymm0
 ; CHECK-NEXT:ret{{[l|q]}}
   %arg = bitcast <4 x i64> %a0 to <16 x i16>
-  %sub = sub <16 x i16> zeroinitializer, %arg
-  %cmp = icmp sgt <16 x i16> %arg, zeroinitializer
-  %sel = select <16 x i1> %cmp, <16 x i16> %arg, <16 x i16> %sub
-  %res = bitcast <16 x i16> %sel to <4 x i64>
+  %abs = call <16 x i16> @llvm.abs.v16i16(<16 x i16> %arg, i1 false)
+  %res = bitcast <16 x i16> %abs to <4 x i64>
   ret <4 x i64> %res
 }
-declare <16 x i16> @llvm.x86.avx2.pabs.w(<16 x i16>) nounwind readnone
+declare <16 x i16> @llvm.abs.v16i16(<16 x i16>, i1) nounwind readnone
 
 define <4 x i64> @test_mm256_abs_epi32(<4 x i64> %a0) {
 ; CHECK-LABEL: test_mm256_abs_epi32:
@@ -38,13 +34,11 @@
 ; CHECK-NEXT:vpabsd %ymm0, %ymm0
 ; CHECK-NEXT:ret{{[l|q]}}
   %arg = bitcast <4 x i64> %a0 to <8 x i32>
-  %sub = sub <8 x i32> zeroi

[PATCH] D86097: [OpenMP][AMDGCN] Generate global variables and attributes for AMDGCN

2020-09-07 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86097/new/

https://reviews.llvm.org/D86097

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

I can only imagine how long it took for you to write all this, because reading 
it wasn't that short either. Thank you so much! It really gave me a perspective 
on how you see this problem, as well as what is actually happening (and should 
happen) in the checker.

In D86874#2254638 , @steakhal wrote:

>   void foo(int x) {
> int buf[10];
>   
> char *r = (char*)(buf + x) + 3;
> *r = 66; // Might be safe, if x has a value to make it so.
>   }

I suppose you mean that it might be unsafe on the grounds of out-of-bounds 
addressing, but alignment-wise its okay?

In D86874#2256249 , @martong wrote:

>>   The resulting `RegionRawOffsetV2` for `p`, `q` will be:
>>   p: {BaseRegion: `buf`, ByteOffset: `20 S64b`}
>>   q: {BaseRegion: `buf`, ByteOffset: `(((reg_$0) + 1) * 12) + 24`}
>> ^^^  ^^
>>  |   |
>>   `@a` This is an //object-language// expression. --/|
>> /
>>   `@b` The rest should be //meta-language// expression. ---/
>>
>> SPOILER: This distinction is really important here.
>>
>> So, we made an expression, we should not evaluate in either of the worlds.
>> We should not evaluate it using the semantics of the //object-language// 
>> since only the `@a` is of that world.
>> We should model overflow in `@a` if that expression is of //unsigned// type 
>> (OR signed but `-fwrapv`...) etc. according to the //abstract machine//.
>> BUT modeling the possibility of an overflow of the rest of the expression 
>> (`@b`) would be a flaw.
>
> Why? I'd expect that the value of the whole expression `@a@b` could overflow.

That wasn't all too clear to me either. It seems like there is extra work to do 
if we do the calculation according to C++ rules, but not the other way around, 
so we could just regard everything as if it was under the object-language 
ruleset.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86874/new/

https://reviews.llvm.org/D86874

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D72932: [ARM] Follow AACPS standard for volatile bit-fields access width

2020-09-07 Thread Oliver Stannard (Linaro) via Phabricator via cfe-commits
ostannard added inline comments.



Comment at: clang/include/clang/Basic/CodeGenOptions.def:396
+/// according to the field declaring type width.
+CODEGENOPT(ForceNoAAPCSBitfieldWidth, 1, 0)
+

dnsampaio wrote:
> ostannard wrote:
> > Why is this a negative option, when the one above is positive?
> The enforcing of number of accesses would not be accepted if it was not an 
> opt-in option. This one I expect it should be accepted with a single opt-out 
> option.
My problem is with the name of the option (adding an extra negative just makes 
things more confusing), not with the default value. This could just be called 
`AAPCSBitfieldWidth`, (unless you think the `Force` is adding something), and 
default to true father than false.



Comment at: clang/include/clang/Driver/Options.td:2328
   HelpText<"Follows the AAPCS standard that all volatile bit-field write 
generates at least one load. (ARM only).">;
+def ForceNoAAPCSBitfieldWidth : Flag<["-"], "fno-AAPCSBitfieldWidth">, 
Group,
+  Flags<[DriverOption,CC1Option]>,

ostannard wrote:
> Command-line options are in kebab-case, so this should be something like 
> `fno-aapcs-bitfield-width`. This also applies to the `fAAPCSBitfieldLoad` 
> option above, assuming it's not too late to change that.
> 
> Please also add a positive version of this option (i.e. 
> `faapcs-bitfield-width`).
This still needs a positive version.



Comment at: clang/lib/CodeGen/CGRecordLayout.h:83
 
+  /// The offset within a contiguous run of bitfields that are represented as
+  /// a single "field" within the LLVM struct type. This offset is in bits.

These doc comments are copied from the ones above, they need changing.



Comment at: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:279
+lowerUnion();
+return computeVolatileBitfields();
+  }

Returning `void` is confusing (yes I know it was already there), this should be 
a separate `return;` statement.



Comment at: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:288
+  appendPaddingBytes(Size);
+  return computeVolatileBitfields();
+}

Same here.



Comment at: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:535
+///
+/// Enforcing the width restriction can be disable using
+/// -fno-aapcs-bitfield-width.

s/disable/disabled/


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D72932/new/

https://reviews.llvm.org/D72932

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86137: Add ignore-unknown-options flag to clang-format.

2020-09-07 Thread Joachim Meyer via Phabricator via cfe-commits
fodinabor added a subscriber: grimar.
fodinabor added a comment.

Thank you so far for the feedback!
maybe you can give further guidance on the comments on the comments :)

As of the git history it seems that @grimar did some work on YAML error 
handling..




Comment at: clang/tools/clang-format/ClangFormat.cpp:108
+static cl::opt
+IgnoreUnkownOptions("ignore-unknown-options",
+cl::desc("If set, unknown format options are 
ignored."),

MyDeveloperDay wrote:
> feels like a mouthful is there nothing shorter we could use?  -Wignore (or 
> something)
hmm... `-Wunknown`
but the `-W` does not really make it clear that the default "errors" should now 
be treated as warnings instead. From compiler conventions, I'd expect the `-W` 
to enable a warning ... 

and something like `-Wno-error=unknown` is not really shorter...



Comment at: llvm/include/llvm/Support/YAMLTraits.h:1520
   boolScalarMatchFound = false;
+  bool IgnoreUnkown = false;
 };

MyDeveloperDay wrote:
> is this clang-formatted?
the patch is... the original alignment of the members is not. (also see the 
`CurrentNode`'s formatting).
not sure what to do in this case, as the whole file seems rather unformatted?



Comment at: llvm/lib/Support/YAMLTraits.cpp:199
+  if (IgnoreUnkown)
+return;
   for (const auto &NN : MN->Mapping) {

MyDeveloperDay wrote:
> do we want to flat out ignore or just report but not fatally. (just a 
> thought) silent failures are hard to diagnose
true.. don't know what's the best option?

keep it as a printed out error and just don't return an error code on exit? 
This option would make it a clang-format only change, but feels really dirty.

Otherwise I'd have to dig my way through to `llvm::yaml::Stream::printError` 
(or maybe rather add a `printWarning`) to conditionally change the message type 
for the ignore case.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86137/new/

https://reviews.llvm.org/D86137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86533: (Urgent!) [release][docs][analyzer] Add 11.0.0. release notes

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:453
+  equal or known to be non-equal.
+
+- Added :ref:`on-demand parsing ` capability to Cross 
Translation

ASDenysPetrov wrote:
> I've added the patch "Reasoning about comparison expressions in 
> RangeConstraintManager". You can mention that as well.
I added the line you mentioned -- do you like how the notes look now?


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86533/new/

https://reviews.llvm.org/D86533

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86533: (Urgent!) [release][docs][analyzer] Add 11.0.0. release notes

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 290280.
Szelethus marked 4 inline comments as done.
Szelethus added a comment.

Added a line about D78933 .


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86533/new/

https://reviews.llvm.org/D86533

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -437,10 +437,77 @@
 
 - ...
 
+.. _release-notes-clang-static-analyzer:
+
 Static Analyzer
 ---
 
-- ...
+- Improved the analyzer's understanding of inherited C++ constructors.
+
+- Improved the analyzer's understanding of dynamic class method dispatching in
+  Objective-C.
+
+- Greatly improved the analyzer's constraint solver by better understanding
+  when constraints are imposed on multiple symbolic values that are known to be
+  equal or known to be non-equal. It will now also efficiently reject 
impossible
+  if-branches between known comparison expressions.
+
+- Added :ref:`on-demand parsing ` capability to Cross 
Translation
+  Unit (CTU) analysis.
+
+- Numerous fixes and improvements for the HTML output.
+
+- New checker: :ref:`alpha.core.C11Lock ` and
+  :ref:`alpha.fuchsia.Lock ` checks for their respective
+  locking APIs.
+
+- New checker: :ref:`alpha.security.cert.pos.34c `
+  finds calls to ``putenv`` where a pointer to an autmoatic variable is passed
+  as an argument.
+
+- New checker: :ref:`webkit.NoUncountedMemberChecker
+  ` to enforce the existence of virtual
+  destructors for all uncounted types used as base classes.
+
+- New checker: :ref:`webkit.RefCntblBaseVirtualDtor
+  ` checks that only ref-counted types
+  are used as class members, not raw pointers and references to uncounted
+  types.
+
+- New checker: :ref:`alpha.cplusplus.SmartPtr ` check
+  for dereference of null smart pointers.
+
+- Moved ``PlacementNewChecker`` out of alpha, making it enabled by default.
+
+- Added support for multi-dimensional variadic arrays in ``core.VLASize``.
+
+- Added a check for insufficient storage in array placement new calls, as well
+  as support for alignment variants to ``cplusplus.PlacementNew``.
+
+- While still in alpha, ``alpha.unix.PthreadLock``, the iterator and container
+  modeling infrastructure, ``alpha.unix.Stream``, and taint analysis were
+  improved greatly. An ongoing, currently off-by-default improvement was made 
on
+  the pre-condition modeling of several functions defined in the POSIX 
standard.
+
+- Improved the warning messages of several checkers.
+
+- Fixed a few remaining cases of checkers emitting reports under incorrect
+  checker names, and employed a few restrictions to more easily identify and
+  avoid such errors.
+
+- Moved several non-reporting checkers (those that model, among other things,
+  standard functions, but emit no diagnostics) to be listed under
+  ``-analyzer-checker-help-developer`` instead of ``-analyzer-checker-help``.
+  Manually enabling or disabling checkers found on this list is not supported
+  in production.
+
+- Numerous fixes for crashes, false positives and false negatives in
+  ``unix.Malloc``, ``osx.cocoa.NSError``, and several other checkers.
+
+- Implemented a dockerized testing system to more easily determine the
+  correctness and performance impact of a change to the static analyzer itself.
+  The currently beta-version tool is found in
+  ``(llvm-project repository)/clang/utils/analyzer/SATest.py``.
 
 .. _release-notes-ubsan:
 


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -437,10 +437,77 @@
 
 - ...
 
+.. _release-notes-clang-static-analyzer:
+
 Static Analyzer
 ---
 
-- ...
+- Improved the analyzer's understanding of inherited C++ constructors.
+
+- Improved the analyzer's understanding of dynamic class method dispatching in
+  Objective-C.
+
+- Greatly improved the analyzer's constraint solver by better understanding
+  when constraints are imposed on multiple symbolic values that are known to be
+  equal or known to be non-equal. It will now also efficiently reject impossible
+  if-branches between known comparison expressions.
+
+- Added :ref:`on-demand parsing ` capability to Cross Translation
+  Unit (CTU) analysis.
+
+- Numerous fixes and improvements for the HTML output.
+
+- New checker: :ref:`alpha.core.C11Lock ` and
+  :ref:`alpha.fuchsia.Lock ` checks for their respective
+  locking APIs.
+
+- New checker: :ref:`alpha.security.cert.pos.34c `
+  finds calls to ``putenv`` where a pointer to an autmoatic variable is passed
+  as an argument.
+
+- New checker: :ref:`webkit.NoUncountedMemberChecker
+  ` to enforce the existence of virtual
+  destructors for all uncounted types used as base classes.
+
+- New checker: :ref:`webkit.RefCntblBaseVirtualDtor
+  ` checks that only ref-counted t

[PATCH] D87187: [Driver] Perform Linux distribution detection just once

2020-09-07 Thread Dmitry Antipov via Phabricator via cfe-commits
dmantipov updated this revision to Diff 290281.
dmantipov added a comment.

Add trivial {/etc,/usr/lib}/os-release parser and fix tests.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87187/new/

https://reviews.llvm.org/D87187

Files:
  clang/include/clang/Driver/Distro.h
  clang/lib/Driver/Distro.cpp

Index: clang/lib/Driver/Distro.cpp
===
--- clang/lib/Driver/Distro.cpp
+++ clang/lib/Driver/Distro.cpp
@@ -19,30 +19,42 @@
 using namespace clang::driver;
 using namespace clang;
 
-static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS,
-   const llvm::Triple &TargetOrHost) {
-  // If we don't target Linux, no need to check the distro. This saves a few
-  // OS calls.
-  if (!TargetOrHost.isOSLinux())
-return Distro::UnknownDistro;
+static Distro::DistroType DetectOsRelease(llvm::vfs::FileSystem &VFS) {
+  Distro::DistroType Version = Distro::UnknownDistro;
+  llvm::ErrorOr> File =
+  VFS.getBufferForFile("/etc/os-release");
+  if (!File)
+File = VFS.getBufferForFile("/usr/lib/os-release");
 
-  // If the host is not running Linux, and we're backed by a real file system,
-  // no need to check the distro. This is the case where someone is
-  // cross-compiling from BSD or Windows to Linux, and it would be meaningless
-  // to try to figure out the "distro" of the non-Linux host.
-  IntrusiveRefCntPtr RealFS =
-  llvm::vfs::getRealFileSystem();
-  llvm::Triple HostTriple(llvm::sys::getProcessTriple());
-  if (!HostTriple.isOSLinux() && &VFS == RealFS.get())
-return Distro::UnknownDistro;
+  if (File) {
+SmallVector Lines;
+File.get()->getBuffer().split(Lines, "\n");
 
+// Obviously this can be improved a lot.
+for (StringRef Line : Lines)
+  if (Version == Distro::UnknownDistro && Line.startswith("ID="))
+Version = llvm::StringSwitch(Line.substr(3))
+  .Case("fedora", Distro::Fedora)
+  .Case("gentoo", Distro::Gentoo)
+  .Case("arch", Distro::ArchLinux)
+  // On SLES, /etc/os-release was introduced in SLES 11.
+  .Case("sles", Distro::OpenSUSE)
+  .Case("opensuse", Distro::OpenSUSE)
+  .Case("exherbo", Distro::Exherbo)
+  .Default(Distro::UnknownDistro);
+  }
+  return Version;
+}
+
+static Distro::DistroType DetectLsbRelease(llvm::vfs::FileSystem &VFS) {
+  Distro::DistroType Version = Distro::UnknownDistro;
   llvm::ErrorOr> File =
   VFS.getBufferForFile("/etc/lsb-release");
+
   if (File) {
-StringRef Data = File.get()->getBuffer();
 SmallVector Lines;
-Data.split(Lines, "\n");
-Distro::DistroType Version = Distro::UnknownDistro;
+File.get()->getBuffer().split(Lines, "\n");
+
 for (StringRef Line : Lines)
   if (Version == Distro::UnknownDistro && Line.startswith("DISTRIB_CODENAME="))
 Version = llvm::StringSwitch(Line.substr(17))
@@ -73,11 +85,28 @@
   .Case("focal", Distro::UbuntuFocal)
   .Case("groovy", Distro::UbuntuGroovy)
   .Default(Distro::UnknownDistro);
-if (Version != Distro::UnknownDistro)
-  return Version;
   }
+  return Version;
+}
+
+static Distro::DistroType DetectDistro(llvm::vfs::FileSystem &VFS) {
+  Distro::DistroType Version = Distro::UnknownDistro;
+
+  // Newer freedesktop.org's compilant systemd-based systems
+  // should provide /etc/os-release or /usr/lib/os-release.
+  Version = DetectOsRelease(VFS);
+  if (Version != Distro::UnknownDistro)
+return Version;
+
+  // Older systems might provide /etc/lsb-release.
+  Version = DetectLsbRelease(VFS);
+  if (Version != Distro::UnknownDistro)
+return Version;
+
+  // Otherwise try some distro-specific quirks for RedHat...
+  llvm::ErrorOr> File
+= VFS.getBufferForFile("/etc/redhat-release");
 
-  File = VFS.getBufferForFile("/etc/redhat-release");
   if (File) {
 StringRef Data = File.get()->getBuffer();
 if (Data.startswith("Fedora release"))
@@ -95,6 +124,7 @@
 return Distro::UnknownDistro;
   }
 
+  // ...for Debian
   File = VFS.getBufferForFile("/etc/debian_version");
   if (File) {
 StringRef Data = File.get()->getBuffer();
@@ -130,6 +160,7 @@
 .Default(Distro::UnknownDistro);
   }
 
+  // ...for SUSE
   File = VFS.getBufferForFile("/etc/SuSE-release");
   if (File) {
 StringRef Data = File.get()->getBuffer();
@@ -153,6 +184,7 @@
 return Distro::UnknownDistro;
   }
 
+  // ...and others.
   if (VFS.exists("/etc/exherbo-release"))
 return Distro::Exherbo;
 
@@ -168,5 +200,37 @@
   return Distro::UnknownDistro;
 }
 
+static Distro::DistroType GetDistro(llvm::vfs::FileSystem &VFS,
+const llvm::Triple &TargetOrHost) {
+  static Distro::DistroType Type = Distro::UninitializedDistro;

[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D86874#2256249 , @martong wrote:

>> Calculation of the RegionRawOffsetV2
>> 
>>
>> Let's see how does these subscript expressions used during the calculation 
>> of the `RegionRawOffsetV2`:
>> For multi-dimension arrays we //fold// the index expressions of the nested 
>> `ElementRegion`s.
>> We are doing that by simply calculating the byte-offset of the nested 
>> region, and adding the current level's //index*sizeof(Type)//.
>> So, the `ByteOffset` that we build up will contain mostly multiplications by 
>> a constant OR additions of symbolic expressions (like the `x+1` in the 
>> example).
>
> We have these lines in the case of handling the ElementRegion:
>
>   if (!index.getAs())
> return RegionRawOffsetV2();
>
> So, if the index is symbolic we give up, don't we? So, how could this work 
> with `x+1`? What am I missing here?

In my example, I'm speaking about the case when it's `nonloc::SymbolVal` 
wrapping the expression `x+1`. So not every `NonLoc` is `ConcreteInt`.

>>   The resulting `RegionRawOffsetV2` for `p`, `q` will be:
>>   p: {BaseRegion: `buf`, ByteOffset: `20 S64b`}
>>   q: {BaseRegion: `buf`, ByteOffset: `(((reg_$0) + 1) * 12) + 24`}
>> ^^^  ^^
>>  |   |
>>   `@a` This is an //object-language// expression. --/|
>> /
>>   `@b` The rest should be //meta-language// expression. ---/
>>
>> SPOILER: This distinction is really important here.
>>
>> So, we made an expression, we should not evaluate in either of the worlds.
>> We should not evaluate it using the semantics of the //object-language// 
>> since only the `@a` is of that world.
>> We should model overflow in `@a` if that expression is of //unsigned// type 
>> (OR signed but `-fwrapv`...) etc. according to the //abstract machine//.
>> BUT modeling the possibility of an overflow of the rest of the expression 
>> (`@b`) would be a flaw.
>
> Why? I'd expect that the value of the whole expression `@a@b` could overflow.

Hm, you might be right about that.
This //simplification// (over the plus operator) is only valid if no overflow 
can happen.
We could add the necessary constraints during this constant folding operation 
such as:
 Simplifying the expression `x+1 < 0` into `x<-1` //assuming that// `x <= 
numeric_limit_max(typeof(x)) - 1`
We could repeat this, while we have a //state// where all such assumptions are 
true.
I'm looking forward to implementing it.

>> Simplify step, again
>> 
>>
>>   Simplification of the `(((reg_$0) + 1) * 12) + 24` < `0` 
>> inequality...
>> ^^
>>`@b`
>>   Result:  `reg_$0 < -3 S64b`
>> ^   ^^^
>>   `RootSym` --/|
>>   /
>>   `C'` --/
>>
>> `#1`: This step supposed to fold **ONLY** the //meta-language// expression 
>> parts (`@b`) of the previously aquired `ByteOffset`.
>> `#2`: This step requires the expression under simplified to be of 
>> //meta-language// to be able to reorder the constants. (aka. to fold into 
>> the right hand side's constant).
>> `#3`: This also requires the right-hand side to be of the //meta-language//.
>
> Do I understand this correctly, that none of the binary operations can have a 
> symbolic RHS, because that would mean we have a VLA?

I think yes, you are right.
However, as I tried to build an example demonstrating this, it turned out that 
it does not handle VLAs quite well.

  void foo(int x, int y) {
int buf[x][y]; // VLA
clang_analyzer_dump(&buf[1][2]);
// &Element{Element{buf,1 S64b,int [y]},2 S64b,int}
  
clang_analyzer_DumpRegionRawOffsetV2AndSimplify(&buf[1][2]);
// RawOffsetV2: {BaseRegion: buf, ByteOffset: 8 S64b}
// simplification result: {RootSymbol: 8 S64b, FoldedConstant: 0 S64b)
  }

The RawOffsetV2 value is wrong. It supposed to have the ByteOffset: `(1 * 
sizeof(int[y])) + 8`.

>> We treat the complete expression under //simplification// as an expression 
>> of the //meta-language//.
>> I'm not changing this, but I probably should though.
>
> Again, I don't understand why you are sure that the value of //whole// 
> expression cannot overflow.
>
>> Ideally, after //simplification// we should have this inequality: `x+1 < -2`
>> That way we would not fold any subexpression of the //object-language//, so 
>> the `#1` requirement would be preserved.
>> The right-hand side is of an expression of the //meta-language//.
>> It makes sense, to evaluate the `operator<` as the semantics of the 
>> //meta-language//.
>> But the left-hand side is an expression of the //object-language//.
>> We need some sort of //logical// conv

[PATCH] D86137: Add ignore-unknown-options flag to clang-format.

2020-09-07 Thread George Rimar via Phabricator via cfe-commits
grimar added a comment.

I am not familar with `clang-format`, but have a few comments inlined about the 
rest.
I think the new `setIgnoreUnknown` YAMLlib API is probably OK generally.
I'd perhaps call it differently, e.g. `setAllowUnknownKeys` though.

Also, I think you need to add a unit testing for the new functionality.
It seems appropriate places are: `clang\unittests\Format\FormatTest.cpp` (to 
test clang-format)
and `llvm\unittests\ObjectYAML\YAMLTest.cpp` (to test new YAML 
`Input::setIgnoreUnknown` API)

I'll add people who might have something useful to say too.




Comment at: llvm/include/llvm/Support/YAMLTraits.h:1508
 
+  void setIgnoreUnknown(bool) override;
+

I'd add a parameter name here. Seems the style is mixed in this file,
but it is a public member, and having no names for arguments actually
reads bad I think. Not sure why it was done initially.

Probably the same applies for `setIgnoreUnknown` in the base class.



Comment at: llvm/lib/Support/YAMLTraits.cpp:199
+  if (IgnoreUnkown)
+return;
   for (const auto &NN : MN->Mapping) {

fodinabor wrote:
> MyDeveloperDay wrote:
> > do we want to flat out ignore or just report but not fatally. (just a 
> > thought) silent failures are hard to diagnose
> true.. don't know what's the best option?
> 
> keep it as a printed out error and just don't return an error code on exit? 
> This option would make it a clang-format only change, but feels really dirty.
> 
> Otherwise I'd have to dig my way through to `llvm::yaml::Stream::printError` 
> (or maybe rather add a `printWarning`) to conditionally change the message 
> type for the ignore case.
Yes, I think we might want to introduce a method, like `Input::reportWarning`
which will call ` Strm->printError(node, message);`, but will not set a `EC`.
Also, it should print "warning: ..." instead of "error: ..." prefix somehow.




Comment at: llvm/lib/Support/YAMLTraits.cpp:742
 
+void Output::setIgnoreUnknown(bool Value) {}
+

You don't actually need it for `Output`, right?
I think instead you can have a default implementation in the base class, which 
should call `llvm_unreachable`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86137/new/

https://reviews.llvm.org/D86137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86874: [analyzer] Fix ArrayBoundCheckerV2 false positive regarding size_t indexer

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D86874#2259105 , @Szelethus wrote:

> I can only imagine how long it took for you to write all this, because 
> reading it wasn't that short either. Thank you so much! It really gave me a 
> perspective on how you see this problem, as well as what is actually 
> happening (and should happen) in the checker.

Thank you very much. I tied to make it as short as possible while keeping all 
the necessary details to make my reasoning perfectly clean. Now I think I was 
on a bad track, but @martong helped me to pinpoint some issues.

> In D86874#2254638 , @steakhal wrote:
>
>>   void foo(int x) {
>> int buf[10];
>>   
>> char *r = (char*)(buf + x) + 3;
>> *r = 66; // Might be safe, if x has a value to make it so.
>>   }
>
> I suppose you mean that it might be unsafe on the grounds of out-of-bounds 
> addressing, but alignment-wise its okay?

You can safely access any valid memory region via `char`, `unsigned char` and 
`std::byte` pointers. And as integers are using all bits in their 
representation, I suspect that this code snippet is safe - given that the 
pointer points to a valid region.
(aka. no out-of-bound access happens). Alignment does not play any role here.

> In D86874#2256249 , @martong wrote:
>
>>>   The resulting `RegionRawOffsetV2` for `p`, `q` will be:
>>>   p: {BaseRegion: `buf`, ByteOffset: `20 S64b`}
>>>   q: {BaseRegion: `buf`, ByteOffset: `(((reg_$0) + 1) * 12) + 24`}
>>> ^^^  ^^
>>>  |   |
>>>   `@a` This is an //object-language// expression. --/|
>>> /
>>>   `@b` The rest should be //meta-language// expression. ---/
>>>
>>> SPOILER: This distinction is really important here.
>>>
>>> So, we made an expression, we should not evaluate in either of the worlds.
>>> We should not evaluate it using the semantics of the //object-language// 
>>> since only the `@a` is of that world.
>>> We should model overflow in `@a` if that expression is of //unsigned// type 
>>> (OR signed but `-fwrapv`...) etc. according to the //abstract machine//.
>>> BUT modeling the possibility of an overflow of the rest of the expression 
>>> (`@b`) would be a flaw.
>>
>> Why? I'd expect that the value of the whole expression `@a@b` could overflow.
>
> That wasn't all too clear to me either. It seems like there is extra work to 
> do if we do the calculation according to C++ rules, but not the other way 
> around, so we could just regard everything as if it was under the 
> object-language ruleset.

Let's forget it. My statements in this regard are going in a bad direction. 
Sorry for the dead-end, I thought I was on the right track.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86874/new/

https://reviews.llvm.org/D86874

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83088: Introduce CfgTraits abstraction

2020-09-07 Thread Nicolai Hähnle via Phabricator via cfe-commits
nhaehnle added inline comments.



Comment at: llvm/include/llvm/Support/CfgTraits.h:51
+
+  operator bool() const { return ptr != nullptr; }
+

dblaikie wrote:
> `operator bool` should be `explicit`
Done.



Comment at: llvm/include/llvm/Support/CfgTraits.h:53-54
+
+  bool operator==(CfgOpaqueType other) const { return ptr == other.ptr; }
+  bool operator!=(CfgOpaqueType other) const { return ptr != other.ptr; }
+};

dblaikie wrote:
> Preferably make any operator overload that can be a non-member, a non-member 
> - this ensures equal conversion handling on both the left and right hand side 
> of symmetric operators like these. (they can be friends if needed, but 
> doesn't look like it in this case - non-friend, non-members that call get() 
> should be fine here)
Done.



Comment at: llvm/include/llvm/Support/CfgTraits.h:90
+/// operations such as traversal of the CFG.
+class CfgTraitsBase {
+protected:

dblaikie wrote:
> Not sure if this benefits from being inherited from, versus being freely 
> accessible?
The idea here is to enforce via the type system that people use 
CfgTraits::{wrap,unwrap}Ref instead of having makeOpaque calls freely in random 
code.



Comment at: llvm/include/llvm/Support/CfgTraits.h:271-273
+template  struct CfgTraitsFor {
+  // using CfgTraits = ...;
+};

dblaikie wrote:
> This probably shouldn't be defined if it's only needed for specialization,  
> instead it can be declared:
> ```
> template struct CfgTraitsFor;
> ```
Interesting. So GraphTraits should arguably be changed similarly.



Comment at: llvm/include/llvm/Support/CfgTraits.h:287
+public:
+  virtual ~CfgInterface() {}
+

dblaikie wrote:
> prefer `= default` where possible
Done.



Comment at: llvm/include/llvm/Support/CfgTraits.h:337
+return Printable(
+[this, block](raw_ostream &out) { printBlockName(out, block); });
+  }

dblaikie wrote:
> generally capture everything by ref `[&]` if the lambda is only used 
> locally/within the same expression or block
The lambda is returned via `Printable`.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D83088/new/

https://reviews.llvm.org/D83088

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83660: [analyzer] Fix a crash for dereferencing an empty llvm::Optional variable in SMTConstraintManager.h.

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Ping @OikawaKirie .
How should we proceed?
I would happily participate in creating a minimal repro for this, but I need at 
least one crash.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D83660/new/

https://reviews.llvm.org/D83660

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85984: [analyzer] Add a new checker alpha.cplusplus.CPlusPlus11Lock

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I have checked only your test, but the readability of the reports should be 
improved.
You frequently refer to previous events, such as `This lock has already been 
unlocked`, `This lock has already been acquired`, etc.
It isn't clear to the reader where do you refer to. IMO you should put a 
//NoteTag// at the interesting locations to achieve more readable diagnostics.

Such as:

  void stms_bad2() {
stm1.lock();// expected-note {{Previously locked here}}
stm1.lock_shared(); // expected-warning {{This lock has already been 
acquired}}
  }

  void stm_bad3() {
stm1.lock();   // hmm, might be a good idea to put one note here too
stm2.lock();   // expected-note {{Previously locked mutex}}
stm1.unlock(); // expected-warning {{This was not the most recently 
acquired lock. Possible lock order reversal}}
stm2.unlock(); // no-warning
  }


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85984/new/

https://reviews.llvm.org/D85984

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86135: [analyzer][MacroExpansion] Fix a crash where multiple parameters resolved to __VA_ARGS__

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Perfectly clear, thank you. However, I would still rely on the others to accept 
this :|

BTW why does the `plist-macros-with-expansion.cpp.plist` change? It makes the 
diff somewhat noisy :s


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86135/new/

https://reviews.llvm.org/D86135

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86137: Add ignore-unknown-options flag to clang-format.

2020-09-07 Thread Jake Merdich via Phabricator via cfe-commits
JakeMerdichAMD added a comment.

I can see the use of this, but I am also wary that ignoring style options will 
lead to people producing different results on different versions of 
clang-format. This is both because having set-or-unset an option will naturally 
lead to different code and also that newer options are a de-facto check that 
clang-format is at least a certain version (we have minor differences between 
major versions as bugs are fixed). In any case, I see this being *very* easy to 
misuse and the documentation should have a warning reflecting that.

As far as docs go, the bulk are in clang/docs/ClangFormat.rst and require no 
additional 'publish' step but definitely should be updated. The command line 
options are implicitly generated for the cli tool's --help flag, but the docs 
for them are all in that rst file and manually maintained.




Comment at: clang/tools/clang-format/ClangFormat.cpp:108
+static cl::opt
+IgnoreUnkownOptions("ignore-unknown-options",
+cl::desc("If set, unknown format options are 
ignored."),

fodinabor wrote:
> MyDeveloperDay wrote:
> > feels like a mouthful is there nothing shorter we could use?  -Wignore (or 
> > something)
> hmm... `-Wunknown`
> but the `-W` does not really make it clear that the default "errors" should 
> now be treated as warnings instead. From compiler conventions, I'd expect the 
> `-W` to enable a warning ... 
> 
> and something like `-Wno-error=unknown` is not really shorter...
I personally like -Wno-error=unknown if the behavior is to emit warnings and 
-Wno-unknown if the behavior is to be silent, for consistency with clang/gcc.

I would also put a note in the description saying that ignoring options can 
lead to dramatically different output between versions that do and don't 
support a given option, so it should be used with care.



Comment at: llvm/lib/Support/YAMLTraits.cpp:199
+  if (IgnoreUnkown)
+return;
   for (const auto &NN : MN->Mapping) {

grimar wrote:
> fodinabor wrote:
> > MyDeveloperDay wrote:
> > > do we want to flat out ignore or just report but not fatally. (just a 
> > > thought) silent failures are hard to diagnose
> > true.. don't know what's the best option?
> > 
> > keep it as a printed out error and just don't return an error code on exit? 
> > This option would make it a clang-format only change, but feels really 
> > dirty.
> > 
> > Otherwise I'd have to dig my way through to 
> > `llvm::yaml::Stream::printError` (or maybe rather add a `printWarning`) to 
> > conditionally change the message type for the ignore case.
> Yes, I think we might want to introduce a method, like `Input::reportWarning`
> which will call ` Strm->printError(node, message);`, but will not set a `EC`.
> Also, it should print "warning: ..." instead of "error: ..." prefix somehow.
> 
Something like how clang/gcc only report unknown -Wno-foo options if there's 
another error is an idea, but clang-format almost never fails unless there's a 
bad config or input file so that's not too useful.

I'm fine with either warning or being silent. If the user has opted-into 
ignoring missing options, we can assume they're willing to accept the 
consequences of such.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86137/new/

https://reviews.llvm.org/D86137

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87239: [analyzer][StdLibraryFunctionsChecker] Remove strcasecmp

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: Szelethus, balazske, NoQ, vsavchenko.
Herald added subscribers: cfe-commits, ASDenysPetrov, steakhal, Charusso, 
gamesh411, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
baloghadamsoftware, xazax.hun, whisperity.
Herald added a project: clang.
martong requested review of this revision.

There are 2 reasons to remove strcasecmp and strncasecmp.

1. They are also modeled in CStringChecker and the related argumentum 
contraints are checked there.
2. The argument constraints are checked in CStringChecker::evalCall. This is 
fundamentally flawed, they should be checked in checkPreCall. Even if we set up 
CStringChecker as a weak dependency for StdLibraryFunctionsChecker then the 
latter reports the warning always. Besides, CStringChecker fails to discover 
the constraint violation before the call, so, its evalCall returns with `true` 
and then StdCLibraryFunctions also tries to evaluate, this causes an assertion 
in CheckerManager.

Either we fix CStringChecker to handle the call prerequisites in
checkPreCall, or we must not evaluate any pure functions in
StdCLibraryFunctions that are also handled in CStringChecker.
We do the latter in this patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87239

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c


Index: clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c
@@ -0,0 +1,21 @@
+// This test case crashes if strncasecmp is modeled in StdCLibraryFunctions.
+// Either we fix CStringChecker to handle the call prerequisites in
+// checkPreCall, or we must not evaluate any pure functions in
+// StdCLibraryFunctions that are also handled in CStringChecker.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=unix.cstring.NullArg \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+typedef __typeof(sizeof(int)) size_t;
+int strncasecmp(const char *s1, const char *s2, size_t n);
+
+int strncasecmp_null_argument(char *a, size_t n) {
+  char *b = 0;
+  return strncasecmp(a, b, n); // expected-warning{{Null pointer passed as 2nd 
argument to string comparison function}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -1674,22 +1674,6 @@
   RetType{IntTy}, NoEvalCall)
   .ArgConstraint(NotNull(ArgNo(0;
 
-// int strcasecmp(const char *s1, const char *s2);
-addToFunctionSummaryMap("strcasecmp",
-Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy},
-RetType{IntTy}, EvalCallAsPure)
-.ArgConstraint(NotNull(ArgNo(0)))
-.ArgConstraint(NotNull(ArgNo(1;
-
-// int strncasecmp(const char *s1, const char *s2, size_t n);
-addToFunctionSummaryMap(
-"strncasecmp", Summary(ArgTypes{ConstCharPtrTy, ConstCharPtrTy, 
SizeTy},
-   RetType{IntTy}, EvalCallAsPure)
-   .ArgConstraint(NotNull(ArgNo(0)))
-   .ArgConstraint(NotNull(ArgNo(1)))
-   .ArgConstraint(ArgumentCondition(
-   2, WithinRange, Range(0, SizeMax;
-
 // int fileno(FILE *stream);
 addToFunctionSummaryMap(
 "fileno", Summary(ArgTypes{FilePtrTy}, RetType{IntTy}, NoEvalCall)


Index: clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c
@@ -0,0 +1,21 @@
+// This test case crashes if strncasecmp is modeled in StdCLibraryFunctions.
+// Either we fix CStringChecker to handle the call prerequisites in
+// checkPreCall, or we must not evaluate any pure functions in
+// StdCLibraryFunctions that are also handled in CStringChecker.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-checker=unix.cstring.NullArg \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCL

[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-09-07 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin added a comment.

In D78938#2258557 , @jhenderson wrote:

> Not that I have anything particularly against this, but won't this likely rot 
> fairly rapidly? It's not like LLVM is even on C++17 let alone C++20 yet, so 
> trying to make it work like the latter when it's just going to break again 
> seems a bit like wasted effort to me.

People will want to write C++20 programs that use LLVM headers, so I think it's 
important to help let them do that. Sure, it may rot, but incremental fixes 
down the line will be smaller.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D78938/new/

https://reviews.llvm.org/D78938

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D78938: Fixing all comparisons for C++20 compilation.

2020-09-07 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin added inline comments.



Comment at: llvm/tools/llvm-objdump/llvm-objdump.cpp:805-817
+  return IsASCII ? "^" : (const char *)u8"\u2548";
 case LineChar::RangeMid:
-  return IsASCII ? "|" : u8"\u2503";
+  return IsASCII ? "|" : (const char *)u8"\u2503";
 case LineChar::RangeEnd:
-  return IsASCII ? "v" : u8"\u253b";
+  return IsASCII ? "v" : (const char *)u8"\u253b";
 case LineChar::LabelVert:
+  return IsASCII ? "|" : (const char *)u8"\u2502";

jhenderson wrote:
> This seems unrelated to comparison checking?
> This seems unrelated to comparison checking?

It is unrelated. But In C++20, `u8` literals become their own type so this no 
longer compiled and I wanted to ensure that I could actually run the tests. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D78938/new/

https://reviews.llvm.org/D78938

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87239: [analyzer][StdLibraryFunctionsChecker] Remove strcasecmp

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I completely agree with you.
I plan to further refactor the CStringChecker, but the related patches are 
pretty much stuck :D

I think this workaround is fine for now.
You might as well extend the corresponding parts of the CStringChecker to make 
the modelling more precise.
It shouldn't be much of a hassle.
What do you say about that?




Comment at: 
clang/test/Analysis/std-c-library-functions-arg-cstring-dependency.c:12
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify

I'm not sure if this is required.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87239/new/

https://reviews.llvm.org/D87239

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87138: [analyzer][NFC] Introduce refactoring of PthreadLockChecker

2020-09-07 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

Seems fine to me.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87138/new/

https://reviews.llvm.org/D87138

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87201: [clang-format] Add a option for the position of Java static import

2020-09-07 Thread Jake Merdich via Phabricator via cfe-commits
JakeMerdichAMD requested changes to this revision.
JakeMerdichAMD added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Format/Format.h:1705
+  /// \endcode
+  bool JavaStaticImportAfterImport;
+

3 things here:

1. Did you mix up the true and false cases?
2. (nit) You should also note that if this option is false, all static imports 
are before all non-static imports (as opposed to mixed together 
alphabetically). I was confused on first glance.
3. Please add this config option to FormatTests.cpp:ParsesConfigurationBools.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87201/new/

https://reviews.llvm.org/D87201

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87240: [analyzer][StdLibraryFunctionsChecker] Have proper weak dependencies

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: Szelethus, balazske, NoQ, vsavchenko.
Herald added subscribers: cfe-commits, ASDenysPetrov, steakhal, Charusso, 
gamesh411, dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
baloghadamsoftware, xazax.hun, whisperity.
Herald added a project: clang.
martong requested review of this revision.

We want the generice StdLibraryFunctionsChecker to report only if there
are no specific checkers that would handle the argument constraint for a
function.

Note, the assumptions are still evaluated, even if the arguement
constraint checker is set to not report. This means that the assumptions
made in the generic StdLibraryFunctionsChecker should be an
over-approximation of the assumptions made in the specific checkers. But
most importantly, the assumptions should not contradict.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D87240

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/std-c-library-functions-arg-weakdeps.c

Index: clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
@@ -0,0 +1,64 @@
+// Check that the more specific checkers report and not the generic
+// StdCLibraryFunctionArgs checker.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+
+// Make sure that all used functions have their summary loaded.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -triple x86_64-unknown-linux 2>&1 | FileCheck %s
+
+// CHECK: Loaded summary for: int isalnum(int)
+// CHECK: Loaded summary for: unsigned long fread(void *restrict, size_t, size_t, FILE *restrict) __attribute__((nonnull(1)))
+// CHECK: Loaded summary for: int fileno(FILE *stream)
+
+void initializeSummaryMap();
+// We analyze this function first, and the call expression inside initializes
+// the summary map. This way we force the loading of the summaries. The
+// summaries would not be loaded without this because during the first bug
+// report in WeakDependency::checkPreCall we stop further evaluation. And
+// StdLibraryFunctionsChecker lazily initializes its summary map from its
+// checkPreCall.
+void analyzeThisFirst() {
+  initializeSummaryMap();
+}
+
+typedef __typeof(sizeof(int)) size_t;
+struct FILE;
+typedef struct FILE FILE;
+
+int isalnum(int);
+size_t fread(void *restrict, size_t, size_t, FILE *restrict) __attribute__((nonnull(1)));
+int fileno(FILE *stream);
+
+void test_uninit_arg() {
+  int v;
+  int r = isalnum(v); // \
+  // expected-warning{{1st function call argument is an uninitialized value [core.CallAndMessage]}}
+  (void)r;
+}
+
+void test_notnull_arg(FILE *F) {
+  int *p = 0;
+  fread(p, sizeof(int), 5, F); // \
+  expected-warning{{Null pointer passed to 1st parameter expecting 'nonnull' [core.NonNullParamChecker]}}
+}
+
+void test_notnull_stream_arg() {
+  fileno(0); // \
+  // expected-warning{{Stream pointer might be NULL [alpha.unix.Stream]}}
+}
Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -1,4 +1,13 @@
+// Here we test the order of the Checkers when StdCLibraryFunctionArgs is
+// enabled.
+
 // RUN: %clang --analyze %s --target=x86_64-pc-linux-gnu \
+// RUN:   -Xclang -analyzer-checker=core \
+// RUN:   -Xclang -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -Xclang -analyzer-config \
+// RUN:  -Xclang apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.Stream \
 // RUN:   -Xclang -analyzer-list-enabled-checkers \
 // RUN:   -Xclang -analyzer-display-progress \
 // RUN:   2>&1 | FileCheck %s --implicit-check-not=ANALYZE \
@@ -7,14 +16,16 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: core.Ca

[PATCH] D87240: [analyzer][StdLibraryFunctionsChecker] Have proper weak dependencies

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.
This revision is now accepted and ready to land.

This is exactly how I imagines weak dependencies to work. LGTM on my end.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87240/new/

https://reviews.llvm.org/D87240

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86671: [clang-tidy] Add new case type to check variables with Hungarian notation

2020-09-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Did you upload this incorrectly again, context is missing and seems to be a 
relative diff from a previous version of this patch?


Repository:
  rCTE Clang Tools Extra

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86671/new/

https://reviews.llvm.org/D86671

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86135: [analyzer][MacroExpansion] Fix a crash where multiple parameters resolved to __VA_ARGS__

2020-09-07 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D86135#2259325 , @steakhal wrote:

> Perfectly clear, thank you. However, I would still rely on the others to 
> accept this :|
>
> BTW why does the `plist-macros-with-expansion.cpp.plist` change? It makes the 
> diff somewhat noisy :s

Well, I removed a line, so every other entry about file position is changed in 
the plist file. I think I could just remove the entire thing altogether, its 
not like the actual plist output is what we're looking for, at least not in its 
many-thousand-line entirety.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D86135/new/

https://reviews.llvm.org/D86135

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D85611: Improve dynamic AST matching diagnostics for conversion errors

2020-09-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D85611#2230481 , @aaron.ballman 
wrote:

> In D85611#2218144 , @aaron.ballman 
> wrote:
>
>> Ping
>
> Ping x2

I realize it's performance review time for some folks and their schedules may 
be busier than usual, gently pinging this so it doesn't fall through the cracks.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D85611/new/

https://reviews.llvm.org/D85611

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d012805 - [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

2020-09-07 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-09-07T17:47:01+02:00
New Revision: d01280587d97eb02d37da37666afd3e4d57c9336

URL: 
https://github.com/llvm/llvm-project/commit/d01280587d97eb02d37da37666afd3e4d57c9336
DIFF: 
https://github.com/llvm/llvm-project/commit/d01280587d97eb02d37da37666afd3e4d57c9336.diff

LOG: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

Differential Revision: https://reviews.llvm.org/D84415

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/std-c-library-functions-POSIX.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index ddde629f44a5..b71c19a80da9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -951,6 +951,8 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   const QualType ConstWchar_tPtrTy =
   getPointerTy(getConstTy(WCharTy)); // const wchar_t *
   const QualType ConstVoidPtrRestrictTy = getRestrictTy(ConstVoidPtrTy);
+  const QualType SizePtrTy = getPointerTy(SizeTy);
+  const QualType SizePtrRestrictTy = getRestrictTy(SizePtrTy);
 
   const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue();
   const RangeInt UnsignedIntMax =
@@ -2182,6 +2184,99 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 Summary(ArgTypes{IntTy, StructItimervalPtrTy},
 RetType{IntTy}, NoEvalCall)
 .ArgConstraint(NotNull(ArgNo(1;
+
+Optional Pthread_cond_tTy = lookupTy("pthread_cond_t");
+Optional Pthread_cond_tPtrTy = getPointerTy(Pthread_cond_tTy);
+Optional Pthread_tTy = lookupTy("pthread_t");
+Optional Pthread_tPtrTy = getPointerTy(Pthread_tTy);
+Optional Pthread_tPtrRestrictTy = getRestrictTy(Pthread_tPtrTy);
+Optional Pthread_mutex_tTy = lookupTy("pthread_mutex_t");
+Optional Pthread_mutex_tPtrTy = getPointerTy(Pthread_mutex_tTy);
+Optional Pthread_mutex_tPtrRestrictTy =
+getRestrictTy(Pthread_mutex_tPtrTy);
+Optional Pthread_attr_tTy = lookupTy("pthread_attr_t");
+Optional Pthread_attr_tPtrTy = getPointerTy(Pthread_attr_tTy);
+Optional ConstPthread_attr_tPtrTy =
+getPointerTy(getConstTy(Pthread_attr_tTy));
+Optional ConstPthread_attr_tPtrRestrictTy =
+getRestrictTy(ConstPthread_attr_tPtrTy);
+Optional Pthread_mutexattr_tTy = lookupTy("pthread_mutexattr_t");
+Optional ConstPthread_mutexattr_tPtrTy =
+getPointerTy(getConstTy(Pthread_mutexattr_tTy));
+Optional ConstPthread_mutexattr_tPtrRestrictTy =
+getRestrictTy(ConstPthread_mutexattr_tPtrTy);
+
+QualType PthreadStartRoutineTy = getPointerTy(
+ACtx.getFunctionType(/*ResultTy=*/VoidPtrTy, /*Args=*/VoidPtrTy,
+ FunctionProtoType::ExtProtoInfo()));
+
+// int pthread_cond_signal(pthread_cond_t *cond);
+// int pthread_cond_broadcast(pthread_cond_t *cond);
+addToFunctionSummaryMap(
+{"pthread_cond_signal", "pthread_cond_broadcast"},
+Signature(ArgTypes{Pthread_cond_tPtrTy}, RetType{IntTy}),
+Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
+
+// int pthread_create(pthread_t *restrict thread,
+//const pthread_attr_t *restrict attr,
+//void *(*start_routine)(void*), void *restrict arg);
+addToFunctionSummaryMap(
+"pthread_create",
+Signature(ArgTypes{Pthread_tPtrRestrictTy,
+   ConstPthread_attr_tPtrRestrictTy,
+   PthreadStartRoutineTy, VoidPtrRestrictTy},
+  RetType{IntTy}),
+Summary(NoEvalCall)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(NotNull(ArgNo(2;
+
+// int pthread_attr_destroy(pthread_attr_t *attr);
+// int pthread_attr_init(pthread_attr_t *attr);
+addToFunctionSummaryMap(
+{"pthread_attr_destroy", "pthread_attr_init"},
+Signature(ArgTypes{Pthread_attr_tPtrTy}, RetType{IntTy}),
+Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
+
+// int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
+//   size_t *restrict stacksize);
+// int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
+//   size_t *restrict guardsize);
+addToFunctionSummaryMap(
+{"pthread_attr_getstacksize", "pthread_attr_getguardsize"},
+Signature(ArgTypes{ConstPthread_attr_tPtrRestrictTy, 
SizePtrRestrictTy},
+  RetType{IntTy}),
+Summary(NoEvalCall)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(NotNull(ArgNo(

[PATCH] D84415: [analyzer][StdLibraryFunctionsChecker] Add POSIX pthread handling functions

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd01280587d97: [analyzer][StdLibraryFunctionsChecker] Add 
POSIX pthread handling functions (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D84415?vs=289970&id=290296#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84415/new/

https://reviews.llvm.org/D84415

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c

Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -108,6 +108,20 @@
 // CHECK: Loaded summary for: struct tm *gmtime(const time_t *tp)
 // CHECK: Loaded summary for: int clock_gettime(clockid_t clock_id, struct timespec *tp)
 // CHECK: Loaded summary for: int getitimer(int which, struct itimerval *curr_value)
+// CHECK: Loaded summary for: int pthread_cond_signal(pthread_cond_t *cond)
+// CHECK: Loaded summary for: int pthread_cond_broadcast(pthread_cond_t *cond)
+// CHECK: Loaded summary for: int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg)
+// CHECK: Loaded summary for: int pthread_attr_destroy(pthread_attr_t *attr)
+// CHECK: Loaded summary for: int pthread_attr_init(pthread_attr_t *attr)
+// CHECK: Loaded summary for: int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, size_t *restrict stacksize)
+// CHECK: Loaded summary for: int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, size_t *restrict guardsize)
+// CHECK: Loaded summary for: int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
+// CHECK: Loaded summary for: int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize)
+// CHECK: Loaded summary for: int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr)
+// CHECK: Loaded summary for: int pthread_mutex_destroy(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_lock(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_trylock(pthread_mutex_t *mutex)
+// CHECK: Loaded summary for: int pthread_mutex_unlock(pthread_mutex_t *mutex)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -259,6 +273,34 @@
 struct itimerval;
 int getitimer(int which, struct itimerval *curr_value);
 
+typedef union {
+  int x;
+} pthread_cond_t;
+int pthread_cond_signal(pthread_cond_t *cond);
+int pthread_cond_broadcast(pthread_cond_t *cond);
+typedef union {
+  int x;
+} pthread_attr_t;
+typedef unsigned long int pthread_t;
+int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void *), void *restrict arg);
+int pthread_attr_destroy(pthread_attr_t *attr);
+int pthread_attr_init(pthread_attr_t *attr);
+int pthread_attr_getstacksize(const pthread_attr_t *restrict attr, size_t *restrict stacksize);
+int pthread_attr_getguardsize(const pthread_attr_t *restrict attr, size_t *restrict guardsize);
+int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
+int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
+typedef union {
+  int x;
+} pthread_mutex_t;
+typedef union {
+  int x;
+} pthread_mutexattr_t;
+int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
+int pthread_mutex_destroy(pthread_mutex_t *mutex);
+int pthread_mutex_lock(pthread_mutex_t *mutex);
+int pthread_mutex_trylock(pthread_mutex_t *mutex);
+int pthread_mutex_unlock(pthread_mutex_t *mutex);
+
 // Must have at least one call expression to initialize the summary map.
 int bar(void);
 void foo() {
Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -951,6 +951,8 @@
   const QualType ConstWchar_tPtrTy =
   getPointerTy(getConstTy(WCharTy)); // const wchar_t *
   const QualType ConstVoidPtrRestrictTy = getRestrictTy(ConstVoidPtrTy);
+  const QualType SizePtrTy = getPointerTy(SizeTy);
+  const QualType SizePtrRestrictTy = getRestrictTy(SizePtrTy);
 
   const RangeInt IntMax = BVF.getMaxValue(IntTy).getLimitedValue();
   const RangeInt UnsignedIntMax =
@@ -2182,6 +2184,99 @@
 Summary(ArgTypes{IntTy, StructItimervalPtrTy},
 RetType{IntTy}, NoEvalCall)
 .ArgConstraint(NotNull(ArgNo(1;
+
+Optional Pthread_cond_tTy = lookupTy("pthread_cond_t");
+Optional Pthread_cond_tPtrTy = getPointerTy(Pthread_cond_tTy);
+Optional Pthread_tTy = lookupT

[PATCH] D87201: [clang-format] Add a option for the position of Java static import

2020-09-07 Thread Byoungchan Lee via Phabricator via cfe-commits
bc-lee added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:2027
+
+ .. code-block:: java
+ true:

MyDeveloperDay wrote:
> The ClangFormatStyleOptions.rst is generated using 
> doc/tools/dump_format_style.py which reads Format.h and generates this,
> 
> If this code block in not in the Format.h it will get removed the next time 
> the script is run, please don't change ClangFormatStyleOption.rst by hand use 
> the script, so add the code block to the Format.h file (see others options 
> for now to do this)
Done.



Comment at: clang/include/clang/Format/Format.h:1705
+  /// \endcode
+  bool JavaStaticImportAfterImport;
+

JakeMerdichAMD wrote:
> 3 things here:
> 
> 1. Did you mix up the true and false cases?
> 2. (nit) You should also note that if this option is false, all static 
> imports are before all non-static imports (as opposed to mixed together 
> alphabetically). I was confused on first glance.
> 3. Please add this config option to FormatTests.cpp:ParsesConfigurationBools.
I understand. The description is somewhat misleading. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87201/new/

https://reviews.llvm.org/D87201

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8248c2a - [analyzer][StdLibraryFunctionsChecker] Have proper weak dependencies

2020-09-07 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-09-07T17:56:26+02:00
New Revision: 8248c2af94975912b14e7e0cb414fcbb82c77123

URL: 
https://github.com/llvm/llvm-project/commit/8248c2af94975912b14e7e0cb414fcbb82c77123
DIFF: 
https://github.com/llvm/llvm-project/commit/8248c2af94975912b14e7e0cb414fcbb82c77123.diff

LOG: [analyzer][StdLibraryFunctionsChecker] Have proper weak dependencies

We want the generice StdLibraryFunctionsChecker to report only if there
are no specific checkers that would handle the argument constraint for a
function.

Note, the assumptions are still evaluated, even if the arguement
constraint checker is set to not report. This means that the assumptions
made in the generic StdLibraryFunctionsChecker should be an
over-approximation of the assumptions made in the specific checkers. But
most importantly, the assumptions should not contradict.

Differential Revision: https://reviews.llvm.org/D87240

Added: 
clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
clang/test/Analysis/std-c-library-functions-arg-weakdeps.c

Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/test/Analysis/analyzer-enabled-checkers.c

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index a444843c5006..a61af4523134 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -349,7 +349,6 @@ let ParentPackage = APIModeling in {
 
 def StdCLibraryFunctionsChecker : Checker<"StdCLibraryFunctions">,
   HelpText<"Improve modeling of the C standard library functions">,
-  Dependencies<[CallAndMessageModeling]>,
   CheckerOptions<[
 CmdLineOption,
"such as whether the parameter of isalpha is in the range [0, 255] "
"or is EOF.">,
   Dependencies<[StdCLibraryFunctionsChecker]>,
-  WeakDependencies<[NonNullParamChecker]>,
+  WeakDependencies<[CallAndMessageChecker, NonNullParamChecker, 
StreamChecker]>,
   Documentation;
 
 } // end "alpha.unix"

diff  --git a/clang/test/Analysis/analyzer-enabled-checkers.c 
b/clang/test/Analysis/analyzer-enabled-checkers.c
index 7c00e78c16ac..bef786a1a59b 100644
--- a/clang/test/Analysis/analyzer-enabled-checkers.c
+++ b/clang/test/Analysis/analyzer-enabled-checkers.c
@@ -6,11 +6,11 @@
 
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
-// CHECK-NEXT: core.CallAndMessageModeling
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
+// CHECK-NEXT: core.CallAndMessageModeling
 // CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation

diff  --git 
a/clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c 
b/clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
new file mode 100644
index ..9ad1be053851
--- /dev/null
+++ b/clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -0,0 +1,66 @@
+// Here we test the order of the Checkers when StdCLibraryFunctionArgs is
+// enabled.
+
+// RUN: %clang --analyze %s --target=x86_64-pc-linux-gnu \
+// RUN:   -Xclang -analyzer-checker=core \
+// RUN:   -Xclang -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -Xclang -analyzer-config \
+// RUN:  -Xclang apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.Stream \
+// RUN:   -Xclang -analyzer-list-enabled-checkers \
+// RUN:   -Xclang -analyzer-display-progress \
+// RUN:   2>&1 | FileCheck %s --implicit-check-not=ANALYZE \
+// RUN:   --implicit-check-not=\.
+
+// CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
+// CHECK-EMPTY:
+// CHECK-NEXT: core.CallAndMessageModeling
+// CHECK-NEXT: core.CallAndMessage
+// CHECK-NEXT: core.NonNullParamChecker
+// CHECK-NEXT: alpha.unix.Stream
+// CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: alpha.unix.StdCLibraryFunctionArgs
+// CHECK-NEXT: apiModeling.TrustNonnull
+// CHECK-NEXT: apiModeling.llvm.CastValue
+// CHECK-NEXT: apiModeling.llvm.ReturnValue
+// CHECK-NEXT: core.DivideZero
+// CHECK-NEXT: core.DynamicTypePropagation
+// CHECK-NEXT: core.NonnilStringConstants
+// CHECK-NEXT: core.NullDereference
+// CHECK-NEXT: core.StackAddrEscapeBase
+// CHECK-NEXT: core.StackAddressEscape
+// CHECK-NEXT: core.UndefinedBinaryOperatorResult
+// CHECK-NEXT: core.VLASize
+// CHECK-NEXT: core.builtin.BuiltinFunctions
+// CHECK-NEXT: core.builtin.NoReturnFunctions
+// CHECK-NEXT: core.uninitialized.ArraySubscript
+// CHECK-NEXT: core.uninitialized.Assign
+// CHECK-NEXT: core.uninitialized.Branch
+// CHECK-NEXT: core

[PATCH] D87240: [analyzer][StdLibraryFunctionsChecker] Have proper weak dependencies

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8248c2af9497: [analyzer][StdLibraryFunctionsChecker] Have 
proper weak dependencies (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D87240?vs=290294&id=290299#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87240/new/

https://reviews.llvm.org/D87240

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/std-c-library-functions-arg-weakdeps.c

Index: clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
===
--- /dev/null
+++ clang/test/Analysis/std-c-library-functions-arg-weakdeps.c
@@ -0,0 +1,64 @@
+// Check that the more specific checkers report and not the generic
+// StdCLibraryFunctionArgs checker.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+
+// Make sure that all used functions have their summary loaded.
+
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:DisplayLoadedSummaries=true \
+// RUN:   -triple x86_64-unknown-linux 2>&1 | FileCheck %s
+
+// CHECK: Loaded summary for: int isalnum(int)
+// CHECK: Loaded summary for: unsigned long fread(void *restrict, size_t, size_t, FILE *restrict) __attribute__((nonnull(1)))
+// CHECK: Loaded summary for: int fileno(FILE *stream)
+
+void initializeSummaryMap();
+// We analyze this function first, and the call expression inside initializes
+// the summary map. This way we force the loading of the summaries. The
+// summaries would not be loaded without this because during the first bug
+// report in WeakDependency::checkPreCall we stop further evaluation. And
+// StdLibraryFunctionsChecker lazily initializes its summary map from its
+// checkPreCall.
+void analyzeThisFirst() {
+  initializeSummaryMap();
+}
+
+typedef __typeof(sizeof(int)) size_t;
+struct FILE;
+typedef struct FILE FILE;
+
+int isalnum(int);
+size_t fread(void *restrict, size_t, size_t, FILE *restrict) __attribute__((nonnull(1)));
+int fileno(FILE *stream);
+
+void test_uninit_arg() {
+  int v;
+  int r = isalnum(v); // \
+  // expected-warning{{1st function call argument is an uninitialized value [core.CallAndMessage]}}
+  (void)r;
+}
+
+void test_notnull_arg(FILE *F) {
+  int *p = 0;
+  fread(p, sizeof(int), 5, F); // \
+  expected-warning{{Null pointer passed to 1st parameter expecting 'nonnull' [core.NonNullParamChecker]}}
+}
+
+void test_notnull_stream_arg() {
+  fileno(0); // \
+  // expected-warning{{Stream pointer might be NULL [alpha.unix.Stream]}}
+}
Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -1,4 +1,13 @@
+// Here we test the order of the Checkers when StdCLibraryFunctionArgs is
+// enabled.
+
 // RUN: %clang --analyze %s --target=x86_64-pc-linux-gnu \
+// RUN:   -Xclang -analyzer-checker=core \
+// RUN:   -Xclang -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -Xclang -analyzer-config \
+// RUN:  -Xclang apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.StdCLibraryFunctionArgs \
+// RUN:   -Xclang -analyzer-checker=alpha.unix.Stream \
 // RUN:   -Xclang -analyzer-list-enabled-checkers \
 // RUN:   -Xclang -analyzer-display-progress \
 // RUN:   2>&1 | FileCheck %s --implicit-check-not=ANALYZE \
@@ -7,14 +16,16 @@
 // CHECK:  OVERVIEW: Clang Static Analyzer Enabled Checkers List
 // CHECK-EMPTY:
 // CHECK-NEXT: core.CallAndMessageModeling
+// CHECK-NEXT: core.CallAndMessage
+// CHECK-NEXT: core.NonNullParamChecker
+// CHECK-NEXT: alpha.unix.Stream
 // CHECK-NEXT: apiModeling.StdCLibraryFunctions
+// CHECK-NEXT: alpha.unix.StdCLibraryFunctionArgs
 // CHECK-NEXT: apiModeling.TrustNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
-// CHECK-NEXT: core.CallAndMessage
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT:

[PATCH] D87081: [analyzer][StdLibraryFunctionsChecker] Elaborate the summary of fread and fwrite

2020-09-07 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D87081#2258637 , @Szelethus wrote:

> The patch looks great, in fact, it demonstrates how well thought out your 
> summary crafting machinery is.
>
> In D87081#2258579 , @martong wrote:
>
>> However, in a similar case with the CallAndMessage Checker, we decided to 
>> list the more specific Checker as a dependency.
>
> We got the answer to D77061#2057063 
> ! We should turn it into a weak 
> dependency though (D80905 ).
>
> In D87081#2256636 , @balazske wrote:
>
>> This checker will make an additional assumption on `fread` and `fwrite` with 
>> the ReturnValueCondition. The return value is constrained by `StreamChecker` 
>> too but it splits the error (if returned value is less that arg 3) and 
>> non-error cases into separate branches. I think this causes no problem 
>> because it will refine the assumption made here (if this assumption is made 
>> first) or the assumption here has no effect (if the split happened already).
>
> Be sure to triple check whether the `ExplodedGraph` looks okay with both 
> checkers enabled.

I'll try to create tests that check the state in both order.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D87081/new/

https://reviews.llvm.org/D87081

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D84467: Add support for Branch Coverage in LLVM Source-Based Code Coverage

2020-09-07 Thread Alan Phipps via Phabricator via cfe-commits
alanphipps marked an inline comment as done.
alanphipps added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.h:4359
+  /// condition (i.e. no "&&" or "||").
+  static bool isLeafCondition(const Expr *C);
+

vsk wrote:
> alanphipps wrote:
> > vsk wrote:
> > > alanphipps wrote:
> > > > vsk wrote:
> > > > > vsk wrote:
> > > > > > It might be helpful to either require that `C` be the RHS of a 
> > > > > > logical binop (e.g. by passing the binop expr in), or to document 
> > > > > > that requirement.
> > > > > Given a logical binop like `E = a && !(b || c)`, 
> > > > > `isLeafCondition(E->getRHS())` is true. That seems a bit 
> > > > > counter-intuitive, because `E->getRHS()` contains another leaf 
> > > > > condition. Would it make sense to rename the condition (perhaps to 
> > > > > something like 'InstrumentedCondition')? Have I misunderstood what a 
> > > > > leaf condition is?
> > > > Background: isLeafCondition() is an auxiliary routine that is used 
> > > > during 1.) counter allocation on binop RHS (CodeGenPGO.cpp), 2.) 
> > > > counter instrumentation (CodeGenFunction.cpp), and 3.) branch region 
> > > > generation (CoverageMappingGen.cpp).  In the #3 case, it isn't always 
> > > > looking at the RHS of a logical binop but can be used to assess whether 
> > > > any condition is instrumented/evaluated.
> > > > 
> > > > Given your example condition:
> > > > 
> > > > E = a && !(b || c)
> > > > 
> > > > You are correct that isLeafCondition(E->getRHS()) will return true, but 
> > > > I think it should actually return false here (and bypass logical-NOT), 
> > > > so I will adapt this. 
> > > > 
> > > > However, given a condition that includes an binary operator (like 
> > > > assign):
> > > > 
> > > > E = a && (x = !(b || c))
> > > > 
> > > > isLeafCondition(E->getRHS()) will also return true, and I think that is 
> > > > the correct behavior.  Given that, then I agree that maybe 
> > > > isLeafCondition() should be renamed to isInstrumentedCondition() since 
> > > > it's not technically just leaves that are tracked in the presence of 
> > > > operators.
> > > What is special about the assignment expression nested within "a && (x = 
> > > !(b || c))" that necessitates an extra counter compared to "a && !(b || 
> > > c)"?
> > I'm exempting the logical NOT operator basically to match the functionality 
> > of other coverage vendors (Bullseye, GCOV).  It's a simplistic operator in 
> > the sense that (as far as I can tell) it only affects the sense of the 
> > generated branch on a condition.
> > 
> > As for the assignment, we're effectively creating a new condition that is 
> > evaluatable (even if a branch may technically not be generated), and so 
> > creating a counter for it is more interesting (and matches other vendor 
> > behavior).
> > 
> > But I'm open to persuasion.  We could just be more conservative and create 
> > counters for logical NOT, but I think there's value in matching some of the 
> > expected behavior of other vendors.  This is also something we could 
> > continue to fine-tune in future patches.
> I agree that there isn't a need to insert a fresh counter to accommodate a 
> logical NOT operator in a condition. But I don't see how an assignment 
> expression effectively creates a new, evaluatable condition. It seems like 
> the count for the assignment expr can be derived by looking up the count for 
> its parent region.
> 
> At this stage I'm more interested in understanding the high-level design. If 
> the question of whether/not to add fresh counters for assignment exprs in a 
> condition is effectively about optimization, then I'm fine with tabling it.
I just realized I didn't make this name change to isInstrumentedCondition(). I 
will do that.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D84467/new/

https://reviews.llvm.org/D84467

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >