[PATCH] D126524: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Yuki Okushi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd3d3e2528e60: [CompilerInstance] Fix weird condition on 
`createCodeCompletionConsumer` (authored by JohnTitor).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126524

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,13 +710,10 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,13 +710,10 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d3d3e25 - [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Yuki Okushi via cfe-commits

Author: Yuki Okushi
Date: 2022-05-28T14:58:04+09:00
New Revision: d3d3e2528e60c93000c6d7f90053d1672cc7b47d

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

LOG: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

Fixes llvm#53545

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index bb896449b621..0ec7964bc599 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -710,13 +710,10 @@ static bool EnableCodeCompletion(Preprocessor ,
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);



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


[PATCH] D126137: [X86] Add support for `-mharden-sls=[none|all|return|indirect-jmp]`

2022-05-27 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:371
 
+- Support ``-mharden-sls=all`` for X86.
+

MaskRay wrote:
> nickdesaulniers wrote:
> > pengfei wrote:
> > > nickdesaulniers wrote:
> > > > This should be updated if additional options are supported.
> > > > 
> > > > You should also update `clang/docs/ClangCommandLineReference.rst` I 
> > > > think.
> > > There's already introduction there.
> > We should expand the introduction there to state explicitly what options 
> > are supported for which targets.
> Delete ` for X86`. The section is about X86.
I'd add ` for straight-line speculation hardening`



Comment at: clang/include/clang/Driver/Options.td:3525
+  HelpText<"Select straight-line speculation hardening scope (ARM/AArch64/X86 "
+   "only).  must be 'all', 'none', 'retbr'(ARM/AArch64), "
+   "'blr'(ARM/AArch64), 'comdat'(ARM/AArch64), 
'nocomdat'(ARM/AArch64),"

`must be one of: `.

Single quotes can be removed.



Comment at: clang/lib/Driver/ToolChains/Arch/X86.cpp:259
+} else if (Scope == "indirect-jmp") {
+  Features.push_back("+harden-sls-ind");
+} else if (Scope != "none") {

The name harden-sls-ind seems a bit different from indirect-jmp. Use a more 
descriptive feature name.



Comment at: clang/test/Driver/x86-target-features.c:313
+// RUN: %clang --target=i386-unknown-linux-gnu -march=i386 
-mharden-sls=return,indirect-jmp %s -### -o %t.o 2>&1 | FileCheck 
-check-prefix=BAD-SLS %s
+// NO-SLS-NOT: harden-sls
+// SLS-RET-DAG: "-target-feature" "+harden-sls-ret"

This can cause false positive if the path components of %s have `harden-sls`,

`...-NOT: "+harden-sls"` should be more robust.



Comment at: clang/test/Driver/x86-target-features.c:308-309
+
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mharden-sls=all %s 
-### -o %t.o 2>&1 | FileCheck -check-prefix=SLS %s
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mharden-sls=none %s 
-### -o %t.o 2>&1 | FileCheck -check-prefix=NO-SLS %s
+// SLS: "-target-feature" "+harden-sls-all"

MaskRay wrote:
> nickdesaulniers wrote:
> > Please add a test for `-mharden-sls=all -mharden-sls=none` to verify that 
> > the last value "wins."
> ` -target ` is deprecated legacy spelling. Better to use `--target=`
If the feature applies to any ELF OSes, use --target=i386 (generic ELF) instead 
of --target=i386-unknown-linux-gnu.



Comment at: llvm/test/CodeGen/X86/speculation-hardening-sls.ll:1
+; RUN: llc -mattr=harden-sls-ret -verify-machineinstrs 
-mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,RET
+; RUN: llc -mattr=harden-sls-ind -verify-machineinstrs 
-mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,IND

Most `-verify-machineinstrs ` usage is redundant.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[clang] 3b45000 - [Driver] Replace err_invalid_branch_protection with err_drv_unsupported_option_argument

2022-05-27 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-05-27T22:28:39-07:00
New Revision: 3b4500014a481f0de300f42e1e59a8137d136ed1

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

LOG: [Driver] Replace err_invalid_branch_protection with 
err_drv_unsupported_option_argument

The convention is to use err_drv_unsupported_option_argument instead of adding a
new diagnostic for every option.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/aarch64-security-options.c
clang/test/Driver/arm-security-options.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index ef08198273a16..9f4864a33a33b 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -424,8 +424,6 @@ def warn_ignoring_verify_debuginfo_preserve_export : 
Warning<
   "ignoring -fverify-debuginfo-preserve-export=%0 because "
   "-fverify-debuginfo-preserve wasn't enabled">,
   InGroup;
-def err_invalid_branch_protection: Error <
-  "invalid branch protection option '%0' in '%1'">;
 def warn_unsupported_branch_protection: Warning <
   "invalid branch protection option '%0' in '%1'">, InGroup;
 def err_sls_hardening_arm_not_supported : Error<

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 367001ddd2d39..936682e49299e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1693,18 +1693,17 @@ static void CollectARMPACBTIOptions(const ToolChain 
, const ArgList ,
 
   if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
 Scope = A->getValue();
-if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
-!Scope.equals("all"))
-  D.Diag(diag::err_invalid_branch_protection)
-  << Scope << A->getAsString(Args);
+if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
+  D.Diag(diag::err_drv_unsupported_option_argument)
+  << A->getOption().getName() << Scope;
 Key = "a_key";
 IndirectBranches = false;
   } else {
 StringRef DiagMsg;
 llvm::ARM::ParsedBranchProtection PBP;
 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
-  D.Diag(diag::err_invalid_branch_protection)
-  << DiagMsg << A->getAsString(Args);
+  D.Diag(diag::err_drv_unsupported_option_argument)
+  << A->getOption().getName() << DiagMsg;
 if (!isAArch64 && PBP.Key == "b_key")
   D.Diag(diag::warn_unsupported_branch_protection)
   << "b-key" << A->getAsString(Args);

diff  --git a/clang/test/Driver/aarch64-security-options.c 
b/clang/test/Driver/aarch64-security-options.c
index b4bb57e71aa79..2044dbd732ed9 100644
--- a/clang/test/Driver/aarch64-security-options.c
+++ b/clang/test/Driver/aarch64-security-options.c
@@ -44,11 +44,11 @@
 
 // CONFLICT: "-msign-return-address=none"
 
-// BAD-RA-PROTECTION: invalid branch protection option 'foo' in 
'-msign-return-address={{.*}}'
-// BAD-BP-PROTECTION: invalid branch protection option 'bar' in 
'-mbranch-protection={{.*}}'
+// BAD-RA-PROTECTION: unsupported argument 'foo' to option 
'-msign-return-address='
+// BAD-BP-PROTECTION: unsupported argument 'bar' to option 
'-mbranch-protection='
 
-// BAD-B-KEY-COMBINATION: invalid branch protection option 'b-key' in 
'-mbranch-protection={{.*}}'
-// BAD-LEAF-COMBINATION: invalid branch protection option 'leaf' in 
'-mbranch-protection={{.*}}'
+// BAD-B-KEY-COMBINATION: unsupported argument 'b-key' to option 
'-mbranch-protection='
+// BAD-LEAF-COMBINATION: unsupported argument 'leaf' to option 
'-mbranch-protection='
 
 // Check that the linker driver doesn't warn about -mbranch-protection=standard
 // as an unused option.

diff  --git a/clang/test/Driver/arm-security-options.c 
b/clang/test/Driver/arm-security-options.c
index fc1b5da78d2cf..b181f19370715 100644
--- a/clang/test/Driver/arm-security-options.c
+++ b/clang/test/Driver/arm-security-options.c
@@ -85,9 +85,9 @@
 // BTE-OFF-NOT: "-mbranch-target-enforce"
 // BTE-ON: "-mbranch-target-enforce"
 
-// BAD-BP-PROTECTION: invalid branch protection option 'bar' in 
'-mbranch-protection={{.*}}'
+// BAD-BP-PROTECTION: unsupported argument 'bar' to option 
'-mbranch-protection='
 
-// BAD-B-KEY-COMBINATION: invalid branch protection option 'b-key' in 
'-mbranch-protection={{.*}}'
-// BAD-LEAF-COMBINATION: invalid branch protection option 'leaf' in 
'-mbranch-protection={{.*}}'
+// BAD-B-KEY-COMBINATION: unsupported argument 'b-key' to option 
'-mbranch-protection='
+// BAD-LEAF-COMBINATION: unsupported argument 'leaf' to option 
'-mbranch-protection='
 
 // INCOMPATIBLE-ARCH: 

[PATCH] D126511: [ARM][AArch64] Change -mharden-sls= to use err_drv_unsupported_option_argument

2022-05-27 Thread Fangrui Song 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 rG068b8af7961c: [ARM][AArch64] Change -mharden-sls= to use 
err_drv_unsupported_option_argument (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126511

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Arch/AArch64.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/test/Driver/sls-hardening-options.c


Index: clang/test/Driver/sls-hardening-options.c
===
--- clang/test/Driver/sls-hardening-options.c
+++ clang/test/Driver/sls-hardening-options.c
@@ -99,7 +99,7 @@
 // NOCOMDAT-OFF-NOT: "harden-sls-nocomdat"
 // NOCOMDAT: "+harden-sls-nocomdat"
 
-// BAD-SLS-SPEC: invalid sls hardening option '{{[^']+}}' in '-mharden-sls=
+// BAD-SLS-SPEC: unsupported argument '{{[^']+}}' to option '-mharden-sls='
 
 // RUN: %clang -target armv6a--none-eabi -c %s -### -mharden-sls=all 2>&1 | \
 // RUN: FileCheck %s --check-prefix=SLS-NOT-SUPPORTED
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -868,8 +868,8 @@
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -324,8 +324,8 @@
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -428,8 +428,6 @@
   "invalid branch protection option '%0' in '%1'">;
 def warn_unsupported_branch_protection: Warning <
   "invalid branch protection option '%0' in '%1'">, InGroup;
-def err_invalid_sls_hardening : Error<
-  "invalid sls hardening option '%0' in '%1'">;
 def err_sls_hardening_arm_not_supported : Error<
   "-mharden-sls is only supported on armv7-a or later">;
 


Index: clang/test/Driver/sls-hardening-options.c
===
--- clang/test/Driver/sls-hardening-options.c
+++ clang/test/Driver/sls-hardening-options.c
@@ -99,7 +99,7 @@
 // NOCOMDAT-OFF-NOT: "harden-sls-nocomdat"
 // NOCOMDAT: "+harden-sls-nocomdat"
 
-// BAD-SLS-SPEC: invalid sls hardening option '{{[^']+}}' in '-mharden-sls=
+// BAD-SLS-SPEC: unsupported argument '{{[^']+}}' to option '-mharden-sls='
 
 // RUN: %clang -target armv6a--none-eabi -c %s -### -mharden-sls=all 2>&1 | \
 // RUN: FileCheck %s --check-prefix=SLS-NOT-SUPPORTED
Index: clang/lib/Driver/ToolChains/Arch/ARM.cpp
===
--- clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -868,8 +868,8 @@
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }
Index: clang/lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -324,8 +324,8 @@
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -428,8 +428,6 @@
   "invalid branch protection option '%0' in '%1'">;
 def warn_unsupported_branch_protection: Warning <
   "invalid branch protection option '%0' in '%1'">, InGroup;
-def 

[clang] 068b8af - [ARM][AArch64] Change -mharden-sls= to use err_drv_unsupported_option_argument

2022-05-27 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-05-27T22:03:48-07:00
New Revision: 068b8af7961caafadeffd1a99a103ef1d7a36e21

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

LOG: [ARM][AArch64] Change -mharden-sls= to use 
err_drv_unsupported_option_argument

Update the diagnostic in D81404: the convention is to use
err_drv_unsupported_option_argument instead of adding a new diagnostic for every
option.

Reviewed By: nickdesaulniers

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/ToolChains/Arch/AArch64.cpp
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/test/Driver/sls-hardening-options.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 3cc9565e6e8b2..ef08198273a16 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -428,8 +428,6 @@ def err_invalid_branch_protection: Error <
   "invalid branch protection option '%0' in '%1'">;
 def warn_unsupported_branch_protection: Warning <
   "invalid branch protection option '%0' in '%1'">, InGroup;
-def err_invalid_sls_hardening : Error<
-  "invalid sls hardening option '%0' in '%1'">;
 def err_sls_hardening_arm_not_supported : Error<
   "-mharden-sls is only supported on armv7-a or later">;
 

diff  --git a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp 
b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
index d82198ec678bf..b17743b728d92 100644
--- a/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -324,8 +324,8 @@ void aarch64::getAArch64TargetFeatures(const Driver ,
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 68e8dc2e5f052..dc6b35e39cfdd 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -868,8 +868,8 @@ void arm::getARMTargetFeatures(const Driver , const 
llvm::Triple ,
   DisableComdat = true;
   continue;
 }
-D.Diag(diag::err_invalid_sls_hardening)
-<< Scope << A->getAsString(Args);
+D.Diag(diag::err_drv_unsupported_option_argument)
+<< A->getOption().getName() << Scope;
 break;
   }
 }

diff  --git a/clang/test/Driver/sls-hardening-options.c 
b/clang/test/Driver/sls-hardening-options.c
index cb35d8b5f99d0..4deb74e66f1de 100644
--- a/clang/test/Driver/sls-hardening-options.c
+++ b/clang/test/Driver/sls-hardening-options.c
@@ -99,7 +99,7 @@
 // NOCOMDAT-OFF-NOT: "harden-sls-nocomdat"
 // NOCOMDAT: "+harden-sls-nocomdat"
 
-// BAD-SLS-SPEC: invalid sls hardening option '{{[^']+}}' in '-mharden-sls=
+// BAD-SLS-SPEC: unsupported argument '{{[^']+}}' to option '-mharden-sls='
 
 // RUN: %clang -target armv6a--none-eabi -c %s -### -mharden-sls=all 2>&1 | \
 // RUN: FileCheck %s --check-prefix=SLS-NOT-SUPPORTED



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


[PATCH] D126137: [X86] Add support for `-mharden-sls=[none|all|return|indirect-jmp]`

2022-05-27 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 432692.
pengfei added a comment.

1. Revert the change to clang/docs/ClangCommandLineReference.rst
2. Update missing options
3. Rebase on D126511 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/X86.cpp
  clang/test/Driver/x86-target-features.c
  llvm/lib/Target/X86/X86.td
  llvm/lib/Target/X86/X86AsmPrinter.cpp
  llvm/lib/Target/X86/X86AsmPrinter.h
  llvm/test/CodeGen/X86/speculation-hardening-sls.ll

Index: llvm/test/CodeGen/X86/speculation-hardening-sls.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/speculation-hardening-sls.ll
@@ -0,0 +1,97 @@
+; RUN: llc -mattr=harden-sls-ret -verify-machineinstrs -mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,RET
+; RUN: llc -mattr=harden-sls-ind -verify-machineinstrs -mtriple=x86_64-unknown-unknown < %s | FileCheck %s -check-prefixes=CHECK,IND
+
+define dso_local i32 @double_return(i32 %a, i32 %b) local_unnamed_addr {
+; CHECK-LABEL: double_return:
+; CHECK: jle
+; CHECK-NOT: int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  %cmp = icmp sgt i32 %a, 0
+  br i1 %cmp, label %if.then, label %if.else
+
+if.then:  ; preds = %entry
+  %div = sdiv i32 %a, %b
+  ret i32 %div
+
+if.else:  ; preds = %entry
+  %div1 = sdiv i32 %b, %a
+  ret i32 %div1
+}
+
+@__const.indirect_branch.ptr = private unnamed_addr constant [2 x i8*] [i8* blockaddress(@indirect_branch, %return), i8* blockaddress(@indirect_branch, %l2)], align 8
+
+; Function Attrs: norecurse nounwind readnone
+define dso_local i32 @indirect_branch(i32 %a, i32 %b, i32 %i) {
+; CHECK-LABEL: indirect_branch:
+; CHECK: jmpq *
+; RET-NOT:   int3
+; IND-NEXT:  int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  %idxprom = sext i32 %i to i64
+  %arrayidx = getelementptr inbounds [2 x i8*], [2 x i8*]* @__const.indirect_branch.ptr, i64 0, i64 %idxprom
+  %0 = load i8*, i8** %arrayidx, align 8
+  indirectbr i8* %0, [label %return, label %l2]
+
+l2:   ; preds = %entry
+  br label %return
+
+return:   ; preds = %entry, %l2
+  %retval.0 = phi i32 [ 1, %l2 ], [ 0, %entry ]
+  ret i32 %retval.0
+}
+
+define i32 @asmgoto() {
+; CHECK-LABEL: asmgoto:
+; CHECK:   # %bb.0: # %entry
+; CHECK: jmp .L
+; CHECK-NOT: int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+; CHECK: retq
+; RET-NEXT:  int3
+; IND-NOT:   int3
+entry:
+  callbr void asm sideeffect "jmp $0", "X"(i8* blockaddress(@asmgoto, %d))
+to label %asm.fallthrough [label %d]
+ ; The asm goto above produces a direct branch:
+
+asm.fallthrough:   ; preds = %entry
+  ret i32 0
+
+d: ; preds = %asm.fallthrough, %entry
+  ret i32 1
+}
+
+define void @bar(void ()* %0) {
+; CHECK-LABEL: bar:
+; CHECK: jmpq *
+; RET-NOT:   int3
+; IND-NEXT:  int3
+; CHECK-NOT: ret
+  tail call void %0()
+  ret void
+}
+
+declare dso_local void @foo()
+
+define dso_local void @bar2() {
+; CHECK-LABEL: bar2:
+; CHECK: jmp foo
+; CHECK-NOT: int3
+; CHECK-NOT: ret
+  tail call void @foo()
+  ret void
+}
Index: llvm/lib/Target/X86/X86AsmPrinter.h
===
--- llvm/lib/Target/X86/X86AsmPrinter.h
+++ llvm/lib/Target/X86/X86AsmPrinter.h
@@ -131,10 +131,7 @@
 
   void emitInstruction(const MachineInstr *MI) override;
 
-  void emitBasicBlockEnd(const MachineBasicBlock ) override {
-AsmPrinter::emitBasicBlockEnd(MBB);
-SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
-  }
+  void emitBasicBlockEnd(const MachineBasicBlock ) override;
 
   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
const char *ExtraCode, raw_ostream ) override;
Index: llvm/lib/Target/X86/X86AsmPrinter.cpp
===
--- llvm/lib/Target/X86/X86AsmPrinter.cpp
+++ llvm/lib/Target/X86/X86AsmPrinter.cpp
@@ -336,6 +336,37 @@
   }
 }
 
+static bool isSimpleReturn(const MachineInstr ) {
+  // We exclude all tail calls here which set both isReturn and isCall.
+  return MI.getDesc().isReturn() && !MI.getDesc().isCall();
+}
+
+static bool isIndirectBranchOrTailCall(const MachineInstr ) {
+  unsigned Opc = MI.getOpcode();
+  return MI.getDesc().isIndirectBranch() /*Make below code 

[PATCH] D121838: Generalize "check-all" umbrella targets, use for check-clang-tools

2022-05-27 Thread James Nagurne via Phabricator via cfe-commits
JamesNagurne added a comment.

In D121838#3543421 , @JamesNagurne 
wrote:

> After some investigation, I found that we did not set LLVM_INCLUDE_TESTS from 
> the top-level project. This seems like an oversight because we build the 
> test-depends (and check-all) regularly.
> After seeing LLVM_INCLUDE_TESTS to ON, the builds worked.
>
> This commit cleaned things up and exposed that mistake.

Sorry, this was a false positive. Building the 'test-depends' target still 
shows the LLVM build system telling the runtimes to build 
'runtimes-test-depends', which is not defined in those ExternalProjects.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

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


[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith accepted this revision.
rsmith added a comment.
This revision is now accepted and ready to land.

OK, fair enough.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126566

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


[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

For the record, `FunctionTemplate` case was added in 
https://reviews.llvm.org/rG9359e8f22a5403ad9524a92c4ccab4db46c9c100


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126566

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


[PATCH] D125622: [clang-tidy] Reject invalid enum initializers in C files

2022-05-27 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 432676.
LegalizeAdulthood added a comment.

- Add C++ test case for acceptable `operator,` initializer


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

https://reviews.llvm.org/D125622

Files:
  clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
  clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
  clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
@@ -36,177 +36,241 @@
   return Tokens;
 }
 
-static bool matchText(const char *Text) {
+static bool matchText(const char *Text, bool AllowComma) {
   std::vector Tokens{tokenify(Text)};
-  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens);
+  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens, AllowComma);
 
   return Matcher.match();
 }
 
+static modernize::LiteralSize sizeText(const char *Text) {
+  std::vector Tokens{tokenify(Text)};
+  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens, true);
+  if (Matcher.match())
+return Matcher.largestLiteralSize();
+  return modernize::LiteralSize::Unknown;
+}
+
+static const char *toString(modernize::LiteralSize Value) {
+  switch (Value) {
+  case modernize::LiteralSize::Int:
+return "Int";
+  case modernize::LiteralSize::UnsignedInt:
+return "UnsignedInt";
+  case modernize::LiteralSize::Long:
+return "Long";
+  case modernize::LiteralSize::UnsignedLong:
+return "UnsignedLong";
+  case modernize::LiteralSize::LongLong:
+return "LongLong";
+  case modernize::LiteralSize::UnsignedLongLong:
+return "UnsignedLongLong";
+  default:
+return "Unknown";
+  }
+}
+
 namespace {
 
-struct Param {
+struct MatchParam {
+  bool AllowComma;
   bool Matched;
   const char *Text;
 
-  friend std::ostream <<(std::ostream , const Param ) {
-return Str << "Matched: " << std::boolalpha << Value.Matched << ", Text: '"
-   << Value.Text << "'";
+  friend std::ostream <<(std::ostream , const MatchParam ) {
+return Str << "Allow operator,: " << std::boolalpha << Value.AllowComma
+   << ", Matched: " << std::boolalpha << Value.Matched
+   << ", Text: '" << Value.Text << '\'';
   }
 };
 
-class MatcherTest : public ::testing::TestWithParam {};
+struct SizeParam {
+  modernize::LiteralSize Size;
+  const char *Text;
+
+  friend std::ostream <<(std::ostream , const SizeParam ) {
+return Str << "Size: " << toString(Value.Size) << ", Text: '" << Value.Text << '\'';
+  }
+};
+
+class MatcherTest : public ::testing::TestWithParam {};
+
+class SizeTest : public ::testing::TestWithParam {};
 
 } // namespace
 
-static const Param Params[] = {
+static const MatchParam MatchParams[] = {
 // Accept integral literals.
-{true, "1"},
-{true, "0177"},
-{true, "0xdeadbeef"},
-{true, "0b1011"},
-{true, "'c'"},
+{true, true, "1"},
+{true, true, "0177"},
+{true, true, "0xdeadbeef"},
+{true, true, "0b1011"},
+{true, true, "'c'"},
 // Reject non-integral literals.
-{false, "1.23"},
-{false, "0x1p3"},
-{false, R"("string")"},
-{false, "1i"},
+{true, false, "1.23"},
+{true, false, "0x1p3"},
+{true, false, R"("string")"},
+{true, false, "1i"},
 
 // Accept literals with these unary operators.
-{true, "-1"},
-{true, "+1"},
-{true, "~1"},
-{true, "!1"},
+{true, true, "-1"},
+{true, true, "+1"},
+{true, true, "~1"},
+{true, true, "!1"},
 // Reject invalid unary operators.
-{false, "1-"},
-{false, "1+"},
-{false, "1~"},
-{false, "1!"},
+{true, false, "1-"},
+{true, false, "1+"},
+{true, false, "1~"},
+{true, false, "1!"},
 
 // Accept valid binary operators.
-{true, "1+1"},
-{true, "1-1"},
-{true, "1*1"},
-{true, "1/1"},
-{true, "1%2"},
-{true, "1<<1"},
-{true, "1>>1"},
-{true, "1<=>1"},
-{true, "1<1"},
-{true, "1>1"},
-{true, "1<=1"},
-{true, "1>=1"},
-{true, "1==1"},
-{true, "1!=1"},
-{true, "1&1"},
-{true, "1^1"},
-{true, "1|1"},
-{true, "1&&1"},
-{true, "1||1"},
-{true, "1+ +1"}, // A space is needed to avoid being tokenized as ++ or --.
-{true, "1- -1"},
-{true, "1,1"},
+{true, true, "1+1"},
+{true, true, "1-1"},
+{true, true, "1*1"},
+{true, true, "1/1"},
+{true, true, "1%2"},
+{true, true, "1<<1"},
+{true, true, "1>>1"},
+{true, true, "1<=>1"},
+{true, true, "1<1"},
+{true, true, 

[PATCH] D125622: [clang-tidy] Reject invalid enum initializers in C files

2022-05-27 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood marked 5 inline comments as done.
LegalizeAdulthood added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:324
 {
-  IntegralLiteralExpressionMatcher Matcher(MacroTokens);
-  return Matcher.match();
+  IntegralLiteralExpressionMatcher Matcher(MacroTokens, LangOpts.C99 == 0);
+  bool Matched = Matcher.match();

aaron.ballman wrote:
> Huh? Comma wasn't allowed in C89 either... In fact, there's no language mode 
> which allows top-level commas in either C or C++ -- the issue with the comma 
> operator is a parsing one. You can't tell the difference between the comma 
> being part of the initializer expression or the comma being the separator 
> between enumerators.
The most recent diff handles the issue with `operator,` but the previous 
version was only handling the overly-big literal



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:326
+  bool Matched = Matcher.match();
+  if (LangOpts.C99 &&
+  (Matcher.largestLiteralSize() != LiteralSize::Int &&

aaron.ballman wrote:
> And C89?
`C99` was the earliest dialect of C I could find in `LangOptions.def`.  If you 
can show me an earlier version for C, I'm happy to switch it.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:3-7
+// C requires enum values to fit into an int.
+#define TOO_BIG1 1L
+#define TOO_BIG2 1UL
+#define TOO_BIG3 1LL
+#define TOO_BIG4 1ULL

aaron.ballman wrote:
> How do we want to handle the fact that Clang has an extension to allow this? 
> Perhaps we want a config option for pedantic vs non-pedantic fixes?
I was trying to find a way to make it fail on gcc/clang on compiler explorer 
and I couldn't get it to fail in either compiler

Where is the extension documented?  It appears to be on by default in both 
compilers.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c:10
+// C forbids comma operator in initializing expressions.
+#define BAD_OP 1, 2
+

aaron.ballman wrote:
> LegalizeAdulthood wrote:
> > aaron.ballman wrote:
> > > Can you add a test:
> > > ```
> > > #define GOOD_OP (1, 2)
> > > ```
> > > to make sure it still gets converted to an enum?
> > Yeah, another one I was thinking of is when someone does [[ 
> > https://godbolt.org/z/c677je8s1 | something as disgusting as this. ]]
> > 
> > ```
> > #define ARGS 1, 2
> > #define OTHER_ARGS (1, 2)
> > 
> > int f(int x, int y) { return x + y; }
> > 
> > int main()
> > {
> > return f(ARGS) + f OTHER_ARGS;
> > }
> > ```
> > 
> > However, the only real way to handle avoiding conversion of the 2nd case is 
> > to examine the context of macro expansion.  This is another edge case that 
> > will have to be handled subsequently.
> > 
> > This gets tricky because AFAIK there is no way to select expressions in the 
> > AST that result from macro expansion.  You have to match the macro 
> > expansion locations against AST nodes to identify the node(s) that match 
> > the expansion location yourself.
> That's a good test case (for some definition of good)! :-)
> 
> At this point, there's a few options:
> 
> 1) Go back to the way things were -- disallow comma expressions, even in 
> parens. Document it as a limitation.
> 2) Accept comma expressions in parens, ignore the problem case like you 
> described above. Document it as a limitation?
> 3) Try to solve every awful code construct we can ever imagine. Document the 
> check is perfect in every way, but probably not land it for several years.
> 
> I think I'd be happy with #2 but I could also live with #1
In the most recent diff, I'm supporting `operator,` inside parens for C++ and 
never allowing it in C.

I plan to do a subsequent enhancement that examines the expansion locations of 
macros and rejects any macro whose expansion doesn't encompass a single 
expression.  In other words, if the tokens in the macro somehow get 
incorporated into some syntactic element that isn't completely encased in a 
single expression, then reject the macro.


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

https://reviews.llvm.org/D125622

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


[PATCH] D125622: [clang-tidy] Reject invalid enum initializers in C files

2022-05-27 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood updated this revision to Diff 432675.
LegalizeAdulthood marked an inline comment as done.
LegalizeAdulthood added a comment.

- Update from review comments
- Disallow operator, unless inside parentheses


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

https://reviews.llvm.org/D125622

Files:
  clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.cpp
  clang-tools-extra/clang-tidy/modernize/IntegralLiteralExpressionMatcher.h
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.c
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
  clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ModernizeModuleTest.cpp
@@ -36,177 +36,241 @@
   return Tokens;
 }
 
-static bool matchText(const char *Text) {
+static bool matchText(const char *Text, bool AllowComma) {
   std::vector Tokens{tokenify(Text)};
-  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens);
+  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens, AllowComma);
 
   return Matcher.match();
 }
 
+static modernize::LiteralSize sizeText(const char *Text) {
+  std::vector Tokens{tokenify(Text)};
+  modernize::IntegralLiteralExpressionMatcher Matcher(Tokens, true);
+  if (Matcher.match())
+return Matcher.largestLiteralSize();
+  return modernize::LiteralSize::Unknown;
+}
+
+static const char *toString(modernize::LiteralSize Value) {
+  switch (Value) {
+  case modernize::LiteralSize::Int:
+return "Int";
+  case modernize::LiteralSize::UnsignedInt:
+return "UnsignedInt";
+  case modernize::LiteralSize::Long:
+return "Long";
+  case modernize::LiteralSize::UnsignedLong:
+return "UnsignedLong";
+  case modernize::LiteralSize::LongLong:
+return "LongLong";
+  case modernize::LiteralSize::UnsignedLongLong:
+return "UnsignedLongLong";
+  default:
+return "Unknown";
+  }
+}
+
 namespace {
 
-struct Param {
+struct MatchParam {
+  bool AllowComma;
   bool Matched;
   const char *Text;
 
-  friend std::ostream <<(std::ostream , const Param ) {
-return Str << "Matched: " << std::boolalpha << Value.Matched << ", Text: '"
-   << Value.Text << "'";
+  friend std::ostream <<(std::ostream , const MatchParam ) {
+return Str << "Allow operator,: " << std::boolalpha << Value.AllowComma
+   << ", Matched: " << std::boolalpha << Value.Matched
+   << ", Text: '" << Value.Text << '\'';
   }
 };
 
-class MatcherTest : public ::testing::TestWithParam {};
+struct SizeParam {
+  modernize::LiteralSize Size;
+  const char *Text;
+
+  friend std::ostream <<(std::ostream , const SizeParam ) {
+return Str << "Size: " << toString(Value.Size) << ", Text: '" << Value.Text << '\'';
+  }
+};
+
+class MatcherTest : public ::testing::TestWithParam {};
+
+class SizeTest : public ::testing::TestWithParam {};
 
 } // namespace
 
-static const Param Params[] = {
+static const MatchParam MatchParams[] = {
 // Accept integral literals.
-{true, "1"},
-{true, "0177"},
-{true, "0xdeadbeef"},
-{true, "0b1011"},
-{true, "'c'"},
+{true, true, "1"},
+{true, true, "0177"},
+{true, true, "0xdeadbeef"},
+{true, true, "0b1011"},
+{true, true, "'c'"},
 // Reject non-integral literals.
-{false, "1.23"},
-{false, "0x1p3"},
-{false, R"("string")"},
-{false, "1i"},
+{true, false, "1.23"},
+{true, false, "0x1p3"},
+{true, false, R"("string")"},
+{true, false, "1i"},
 
 // Accept literals with these unary operators.
-{true, "-1"},
-{true, "+1"},
-{true, "~1"},
-{true, "!1"},
+{true, true, "-1"},
+{true, true, "+1"},
+{true, true, "~1"},
+{true, true, "!1"},
 // Reject invalid unary operators.
-{false, "1-"},
-{false, "1+"},
-{false, "1~"},
-{false, "1!"},
+{true, false, "1-"},
+{true, false, "1+"},
+{true, false, "1~"},
+{true, false, "1!"},
 
 // Accept valid binary operators.
-{true, "1+1"},
-{true, "1-1"},
-{true, "1*1"},
-{true, "1/1"},
-{true, "1%2"},
-{true, "1<<1"},
-{true, "1>>1"},
-{true, "1<=>1"},
-{true, "1<1"},
-{true, "1>1"},
-{true, "1<=1"},
-{true, "1>=1"},
-{true, "1==1"},
-{true, "1!=1"},
-{true, "1&1"},
-{true, "1^1"},
-{true, "1|1"},
-{true, "1&&1"},
-{true, "1||1"},
-{true, "1+ +1"}, // A space is needed to avoid being tokenized as ++ or --.
-{true, "1- -1"},
-{true, "1,1"},
+{true, true, "1+1"},
+{true, true, "1-1"},
+{true, true, "1*1"},
+{true, true, "1/1"},
+{true, true, "1%2"},
+{true, true, "1<<1"},
+{true, true, "1>>1"},
+

[PATCH] D126100: Add sanitizer-specific GlobalValue attributes.

2022-05-27 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka requested changes to this revision.
vitalybuka added a comment.
This revision now requires changes to proceed.

all stuff under llvm/... here needs testing, Bitcode and AsmParser have many 
tests usable as examples

Also probably better to separate from clang changes:
Patch 1: extends LLVM IR
Patch 2: Integrate new LLVM IR feature into clang

LangRef.rst part will probably requires wider review. I suspect we there will 
be strong opinions.
So maybe you can extract just a document into a 3rd patch.

Also it does not really document what new attributes do.

For review context you can organize them into Stack.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126100

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


[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

To trigger "function template|different function template" diagnostic we need 
the entire "case FunctionTemplate" in "switch (FirstDiffType)" 

 not to detect any mismatches. And I don't know any such cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126566

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


[PATCH] D126324: [clang] Allow const variables with weak attribute to be overridden

2022-05-27 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders updated this revision to Diff 432669.
wanders added a comment.

Diff updated with release note + updated text in documentation as per 
jyknight's suggestion.

Tests for existing behavior added in separate patch: 
https://reviews.llvm.org/D126578


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/global-init.c
  clang/test/CodeGen/weak_constant.c

Index: clang/test/CodeGen/weak_constant.c
===
--- clang/test/CodeGen/weak_constant.c
+++ clang/test/CodeGen/weak_constant.c
@@ -1,13 +1,31 @@
 // RUN: %clang_cc1 -w -emit-llvm %s -O1 -o - | FileCheck %s
-// Check for bug compatibility with gcc.
+// This used to "check for bug compatibility with gcc".
+// Now it checks that that the "weak" declaration makes the value
+// fully interposable whereas a "selectany" one is handled as constant
+// and propagated.
 
+// CHECK: @x = weak {{.*}}constant i32 123
 const int x __attribute((weak)) = 123;
 
+// CHECK: @y = weak_odr {{.*}}constant i32 234
+const int y __attribute((selectany)) = 234;
+
 int* f(void) {
   return 
 }
 
 int g(void) {
-  // CHECK: ret i32 123
+  // CHECK: load i32, ptr @x
+  // CHECK-NOT: ret i32 123
   return *f();
 }
+
+int *k(void) {
+  return 
+}
+
+int l(void) {
+  // CHECK-NOT: load i32, ptr @y
+  // CHECK: ret i32 234
+  return *k();
+}
Index: clang/test/CodeGen/global-init.c
===
--- clang/test/CodeGen/global-init.c
+++ clang/test/CodeGen/global-init.c
@@ -9,14 +9,20 @@
 
 // This should get normal weak linkage.
 int c __attribute__((weak))= 0;
-// CHECK: @c = weak{{.*}} global i32 0
+// CHECK: @c = weak global i32 0
 
-
-// Since this is marked const, it should get weak_odr linkage, since all
-// definitions have to be the same.
-// CHECK: @d = weak_odr constant i32 0
+// Even though is marked const, it should get still get "weak"
+// linkage, not "weak_odr" as the weak attribute makes it possible
+// that there is a strong definition that changes the value linktime,
+// so the value must not be considered constant.
+// CHECK: @d = weak constant i32 0
 const int d __attribute__((weak))= 0;
 
+// However, "selectany" is similar to "weak", but isn't interposable
+// by a strong definition, and should appear as weak_odr.
+// CHECK: @e = weak_odr constant i32 17
+const int e __attribute__((selectany)) = 17;
+
 // PR6168 "too many undefs"
 struct ManyFields {
   int a;
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4899,12 +4899,8 @@
   if (Linkage == GVA_Internal)
 return llvm::Function::InternalLinkage;
 
-  if (D->hasAttr()) {
-if (IsConstantVariable)
-  return llvm::GlobalVariable::WeakODRLinkage;
-else
-  return llvm::GlobalVariable::WeakAnyLinkage;
-  }
+  if (D->hasAttr())
+return llvm::GlobalVariable::WeakAnyLinkage;
 
   if (const auto *FD = D->getAsFunction())
 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6477,3 +6477,69 @@
 The full documentation is available here: https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sv-groupindex
   }];
 }
+
+def WeakDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+
+In supported output formats the ``weak`` attribute can be used to
+specify that a variable or function should be emitted as a symbol with
+``weak`` (if a definition) or ``extern_weak`` (if a declaration of an
+external symbol) `linkage
+`_.
+
+If there is a non-weak definition of the symbol the linker will select
+that over the weak. They must have same type and alignment (variables
+must also have the same size), but may have a different value.
+
+If there are multiple weak definitions of same symbol, but no non-weak
+definition, they should have same type, size, alignment and value, the
+linker will select one of them (see also selectany_ attribute).
+
+If the ``weak`` attribute is applied to a ``const`` qualified variable
+definition that variable is no longer consider a compiletime constant
+as its value can change during linking (or dynamic linking). This
+means that it can e.g no longer be part of an initializer expression.
+
+.. code-block:: c
+
+  const int ANSWER __attribute__ ((weak)) = 42;
+
+  /* This function may be replaced link-time */
+  __attribute__ ((weak)) void debug_log(const char *msg)
+  {
+  

[PATCH] D126578: [clang] Add tests for (const) weak variables

2022-05-27 Thread Anders Waldenborg via Phabricator via cfe-commits
wanders created this revision.
wanders added a reviewer: aaron.ballman.
Herald added a project: All.
wanders requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This adds tests checking the behavior of const variables declared with
weak attribute.

Both checking that they can not be used in places where a constant
expression is required and that a dynamic initializer is emitted when
used as an initializer expression.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126578

Files:
  clang/test/CodeGenCXX/weak-init.cpp
  clang/test/SemaCXX/weak-init.cpp


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__ ((weak)) = 10; // expected-note {{declared 
here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is 
not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak 
variable 'W1' is not considered constant because it may be different at 
runtime}}
+
+
+extern const int W2 __attribute__ ((weak)) = 20;
+
+int S2[W2];  // expected-error {{variable length array declaration not allowed 
at file scope}}
+
+
+extern const int W3 __attribute__ ((weak)) = 30; // expected-note {{declared 
here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be 
initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' 
is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__ ((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;


Index: clang/test/SemaCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/weak-init.cpp
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only
+
+extern const int W1 __attribute__ ((weak)) = 10; // expected-note {{declared here}}
+
+static_assert(W1 == 10, ""); // expected-error   {{static_assert expression is not an integral constant expression}}
+ // expected-note@-1 {{initializer of weak variable 'W1' is not considered constant because it may be different at runtime}}
+
+
+extern const int W2 __attribute__ ((weak)) = 20;
+
+int S2[W2];  // expected-error {{variable length array declaration not allowed at file scope}}
+
+
+extern const int W3 __attribute__ ((weak)) = 30; // expected-note {{declared here}}
+
+constexpr int S3 = W3; // expected-error   {{constexpr variable 'S3' must be initialized by a constant expression}}
+   // expected-note@-1 {{initializer of weak variable 'W3' is not considered constant because it may be different at runtime}}
Index: clang/test/CodeGenCXX/weak-init.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/weak-init.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+extern const int W __attribute__ ((weak)) = 99;
+const int S = 77;
+
+// CHECK: @C1 = {{.*}} 77
+extern const int C1 = S;
+
+// CHECK: %0 = load {{.*}} @W
+// CHECK-NEXT: store {{.*}} %0, {{.*}} @C2
+extern const int C2 = W;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126547: [OpenACC][OpenMP] Document atomic-in-teams extension

2022-05-27 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Thanks for the quick review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126547

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


[PATCH] D126547: [OpenACC][OpenMP] Document atomic-in-teams extension

2022-05-27 Thread Joel E. Denny via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4a368136693b: [OpenACC][OpenMP] Document atomic-in-teams 
extension (authored by jdenny).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126547

Files:
  clang/docs/OpenMPSupport.rst
  openmp/docs/openacc/OpenMPExtensions.rst


Index: openmp/docs/openacc/OpenMPExtensions.rst
===
--- openmp/docs/openacc/OpenMPExtensions.rst
+++ openmp/docs/openacc/OpenMPExtensions.rst
@@ -137,3 +137,36 @@
 the runtime level.  That is, OpenACC's dynamic reference count is
 OpenMP's dynamic reference count, and OpenACC's structured reference
 count is our OpenMP hold reference count extension.
+
+.. _atomicWithinTeams:
+
+``atomic`` Strictly Nested Within ``teams``
+---
+
+Example
+^^^
+
+OpenMP 5.2, sec. 10.2 "teams Construct", p. 232, L9-12 restricts what
+regions can be strictly nested within a ``teams`` region.  As an
+extension, Clang relaxes that restriction in the case of the
+``atomic`` construct so that, for example, the following case is
+permitted:
+
+.. code-block:: c++
+
+  #pragma omp target teams map(tofrom:x)
+  #pragma omp atomic update
+  x++;
+
+Relationship with OpenACC
+^
+
+This extension is important when translating OpenACC to OpenMP because
+OpenACC does not have the same restriction for its corresponding
+constructs.  For example, the following is conforming OpenACC:
+
+.. code-block:: c++
+
+  #pragma acc parallel copy(x)
+  #pragma acc atomic update
+  x++;
Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -369,9 +369,12 @@
 considered for standardization.  Please contact *openmp-dev* at
 *lists.llvm.org* to provide feedback.
 
-+--+---+--++
-|Category  | Feature   
| Status   | Reviews
|
-+==+===+==++
-| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, D106510   
|
-|  | 
`_  | 
 ||
-+--+---+--++
++--+---+--++
+|Category  | Feature   
| Status   | Reviews
|
++==+===+==++
+| atomic extension | `'atomic' strictly nested within 'teams'  
| :good:`prototyped`   | D126323
|
+|  | 
`_
  |  |  
  |
++--+---+--++
+| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, 
D106510   |
+|  | 
`_
  |  |  
  |
++--+---+--++



[clang] 4a36813 - [OpenACC][OpenMP] Document atomic-in-teams extension

2022-05-27 Thread Joel E. Denny via cfe-commits

Author: Joel E. Denny
Date: 2022-05-27T18:53:19-04:00
New Revision: 4a368136693ba9c4e827702e9d390280c3d5e7ac

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

LOG: [OpenACC][OpenMP] Document atomic-in-teams extension

That is, put D126323 in the status doc and explain its relationship to
OpenACC support.

Reviewed By: jdoerfert

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

Added: 


Modified: 
clang/docs/OpenMPSupport.rst
openmp/docs/openacc/OpenMPExtensions.rst

Removed: 




diff  --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index 1292af07a8e41..88e3050d3622c 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -369,9 +369,12 @@ documentation are provided.  As these extensions mature, 
they will be
 considered for standardization.  Please contact *openmp-dev* at
 *lists.llvm.org* to provide feedback.
 
-+--+---+--++
-|Category  | Feature   
| Status   | Reviews
|
-+==+===+==++
-| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, D106510   
|
-|  | 
`_  | 
 ||
-+--+---+--++
++--+---+--++
+|Category  | Feature   
| Status   | Reviews
|
++==+===+==++
+| atomic extension | `'atomic' strictly nested within 'teams'  
| :good:`prototyped`   | D126323
|
+|  | 
`_
  |  |  
  |
++--+---+--++
+| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, 
D106510   |
+|  | 
`_
  |  |  
  |
++--+---+--++

diff  --git a/openmp/docs/openacc/OpenMPExtensions.rst 
b/openmp/docs/openacc/OpenMPExtensions.rst
index bc662c32e81ca..82cf77548b9a0 100644
--- a/openmp/docs/openacc/OpenMPExtensions.rst
+++ b/openmp/docs/openacc/OpenMPExtensions.rst
@@ -137,3 +137,36 @@ selecting OpenMP reference counts, the implementation is 
the same at
 the runtime level.  That is, OpenACC's dynamic reference count is
 OpenMP's dynamic reference count, and OpenACC's structured reference
 count is our OpenMP hold reference count extension.
+
+.. _atomicWithinTeams:
+
+``atomic`` Strictly Nested Within ``teams``
+---
+
+Example
+^^^
+
+OpenMP 5.2, sec. 10.2 "teams Construct", p. 232, L9-12 restricts what
+regions can be strictly nested within a ``teams`` region.  As an
+extension, Clang relaxes that restriction in the case of the
+``atomic`` construct so 

[PATCH] D121838: Generalize "check-all" umbrella targets, use for check-clang-tools

2022-05-27 Thread James Nagurne via Phabricator via cfe-commits
JamesNagurne added a comment.

After some investigation, I found that we did not set LLVM_INCLUDE_TESTS from 
the top-level project. This seems like an oversight because we build the 
test-depends (and check-all) regularly.
After seeing LLVM_INCLUDE_TESTS to ON, the builds worked.

This commit cleaned things up and exposed that mistake.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

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


[PATCH] D121838: Generalize "check-all" umbrella targets, use for check-clang-tools

2022-05-27 Thread James Nagurne via Phabricator via cfe-commits
JamesNagurne added a comment.

Hi Sam, I've got a downstream build system that is failing here and I'm trying 
to figure out why.

After your commit, I get an error during bootstrapped runtime builds:

  05-27 14:41 __main__ INFO [202/796] cd 
/path/to/builddir/runtimes/runtimes-target-bins && cmake --build 
/path/to/builddir/runtimes/runtimes-target-bins/ --target runtimes-test-depends 
--config Release
  05-27 14:41 __main__ INFO ninja: error: unknown target 
'runtimes-test-depends'

We have a mono-project CMakeLists.txt that builds our entire cross-compilation 
toolchain, libraries and all.
The build system uses a bootstrapping strategy, but must separate the builds of 
llvm/clang tools and the runtime builds, so we have LLVM_ENABLE_RUNTIMES set 
but LLVM_BUILD_RUNTIMES=OFF

Why do we do this instead of using the "default build strategy", you may ask? 
Well, the default strategy didn't exist when we set everything up. Wouldn't be 
against trying that if it seems to be the only way to fix the issue I'm seeing.

Specifically, in-order, the actions we perform:

- Build clang/llvm tools (target llvm-build)
- Build in-house tools
- Build in-house C Library (uses just-built tools from above)
- Build libc++, libc++abi, compiler-rt using llvm/runtimes (target 'runtimes'. 
Needs C includes and just-built compiler from previous step)
- Build llvm-test-depends in preparation for check-all, etc. (arbitrarily 
ordered after runtime builds)

We do this by adding llvm as an ExternalProject and then adding step targets 
(llvm-runtimes, llvm-test-depends) that just map to the LLVM equivalent target.

I'll look more deeply into your commit and what's changed in our downstream 
build system, but I wanted to fire this comment off in case you've seen it or 
have a quick way to figure out what might be wrong.
We do have some downstream changes, including an abandoned commit 
(https://reviews.llvm.org/D72947) that could be causing issues. That's also a 
main target of scrutiny.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

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


Re: Call for an assistance pushing patch review forward

2022-05-27 Thread stryku_t via cfe-commits
Hi Paul,

Thank you for the tips.
Pinging is indeed mentioned in the docs, but I didn't want to piss everyone
off, so after two pings I thought that I'm doing something wrong. From now
on I'll ping once a week in such situations.

Got review comments now, so we're back on track. Gonna implement changes
over the weekend.

Thanks,
Mateusz Janek

czw., 26 maj 2022 o 22:51 Robinson, Paul 
napisał(a):

> Hi Mateusz,
>
>
>
> I wouldn’t worry too much about the failed build.  I took a peek and it
> looks like the failures are mostly in places very unrelated to your patch.
> If your own testing shows no problems, it’s very likely you’re fine.
>
>
>
> Regarding lack of response, this is unfortunately more common than it
> should be.  Our recommended practice—and I’m surprised we don’t say
> anything on the website—is to add a “ping” comment to your review, maybe
> once a week.  This can “bump” it up in someone’s to-be-reviewed list; if
> nothing else, there’s another email to the list that will hopefully catch
> someone’s attention.
>
>
>
> Good luck,
>
> --paulr
>
>
>
> *From:* cfe-commits  *On Behalf Of 
> *stryku_t
> via cfe-commits
> *Sent:* Thursday, May 26, 2022 4:20 PM
> *To:* cfe-commits@lists.llvm.org
> *Subject:* Call for an assistance pushing patch review forward
>
>
>
> Hi,
>
> Some time ago I submitted a Clang patch for review:
> https://reviews.llvm.org/D123532
> 
>
> It's been some time and I can't make progress with it.
> I'm aware that there is failed build. But, as I mentioned in one of the
> comments, I can't reproduce it locally.
> Tried to reach out to the people mentioned in the review, but I struggle
> getting answers.
> At this point I'm not sure if I'm doing something wrong or people are just
> busy. Should tag different people? Different project? Am I expected to
> figure out failed builds on my own before someone will review the changes?
>
> Could someone from the community please assist me how for move forward
> with this patch? Also, I'd be grateful if there's someone who can hint me
> how to reproduce failed builds locally or using some CI server.
>
> Thanks in advance!
>
> Best regards,
> Mateusz Janek
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

We perhaps can't or don't want to add test coverage for the "unexpected decl" 
case here. Can we add coverage for the "function template" case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126566

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


[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

We emit `err_module_odr_violation_mismatch_decl_unknown` at
https://github.com/llvm/llvm-project/blob/0fbe3f3f486e01448121f7931a4ca29fac1504ab/clang/lib/Serialization/ASTReader.cpp#L11143-L11150

`ODRMismatchDecl` is defined at
https://github.com/llvm/llvm-project/blob/0fbe3f3f486e01448121f7931a4ca29fac1504ab/clang/lib/Serialization/ASTReader.cpp#L9624-L9638


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126566

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


[PATCH] D126341: Order implicitly instantiated global variable's initializer by the reverse instantiation order

2022-05-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:563
+  } else if (IsInstantiation ||
  getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR ||
  D->hasAttr()) {

rnk wrote:
> rsmith wrote:
> > rnk wrote:
> > > @rsmith , if inline global variable initialization has ordering 
> > > requirements, we have a bug, because I believe this GVA_DiscardableODR 
> > > codepath handles them, and we come through here to give them separate 
> > > initializers in llvm.global_ctors. See the example with two separate 
> > > global_ctors entries on godbolt:
> > > https://gcc.godbolt.org/z/5d577snqb
> > > 
> > > As long as LLVM doesn't provide ordering guarantees about same priority 
> > > initializers in global_ctors, inline globals have the same problems as 
> > > template instantiations. IMO whatever solution we use to order inline 
> > > globals should be used for template instantiations.
> > > 
> > > Intuitively, that means LLVM should promise to run global_ctors in 
> > > left-to-right order, and if all TUs instantiate initializers in the same 
> > > order, everything should behave intuitively.
> > > 
> > > The question then becomes, why doesn't this work already?
> > > Intuitively, that means LLVM should promise to run global_ctors in 
> > > left-to-right order
> > 
> > I don't think that's sufficient, due to the way we use COMDATs to discard 
> > duplicate global initializers. Consider:
> > 
> > TU 1 defines inline variable A.
> > TU 2 defines inline variable A and then inline variable B.
> > The standard guarantees that A is initialized before B in this scenario. 
> > But if (somehow) the linker picks the definition of A from TU 2, but orders 
> > the initializers from TU 1 first, then the resulting global_ctors order 
> > will be B then A, which is not allowed.
> > 
> > Either we need a guarantee that linkers will use the same ordering between 
> > objects when picking COMDATs as when concatenating `.init_array`, or we 
> > need to stop using the COMDAT trick for them (and either make LLVM respect 
> > the `@llvm.global_ctors` order or coalesce all inline variable initializers 
> > into the same function we run non-inline initializers from or something). 
> > Getting that guarantee seems like the best path to me, since the other 
> > option will presumably mean we check the guard variable once on startup for 
> > each TU that defines the variable, and it's something I expect linkers 
> > already happen to guarantee in practice.
> > 
> > > IMO whatever solution we use to order inline globals should be used for 
> > > template instantiations.
> > 
> > That sounds like it would regress what globalopt is able to optimize, for 
> > no gain in conformance nor perhaps any real gain in initialization order 
> > guarantees. The inline variable case is different, both because we can 
> > guarantee an initialization order and because the standard requires us to 
> > do so. Should we add complexity to the compiler whose only purpose is to 
> > mask bugs, if that complexity doesn't actually define away the possibility 
> > of bad behavior?
> > 
> > If we can actually describe a rule that we provide for initialization order 
> > of instantiated variables, and we can easily implement that rule and be 
> > confident we won't want to substantially weaken it later, and we can 
> > thereby assure our users that we will satisfy that rule, then I think that 
> > could be interesting, but anything less than that doesn't seem worthwhile 
> > to me.
> > 
> > > The question then becomes, why doesn't this work already?
> > 
> > It looks like it mostly does.
> > 
> > One factor here is instantiation order. When we instantiate a variable, we 
> > add the variables that it references to our "to be instantiated" list, 
> > which is processed later:
> > ```
> > template int Fib = Fib + Fib;
> > template<> int Fib<0> = 0;
> > template<> int Fib<1> = 1;
> > ```
> > * instantiating `Fib<5>` will append `Fib<3>` and `Fib<4>` to the list
> > * then we visit `Fib<3>` and append `Fib<1>` and `Fib<2>` to the list
> > * then we visit `Fib<4>` and add no new entries
> > 
> > We pass declarations to the consumer when we're done with the instantiation 
> > step. *Sometimes* this includes instantiating variables referenced by that 
> > variable, and *sometimes* it doesn't. The difference is whether we're 
> > performing "recursive" instantiation or not.
> > 
> > When we're performing immediate instantiation of a variable (either because 
> > it was explicitly instantiated, or because we might need its value 
> > immediately because it might be usable in constant expressions), our 
> > instantiation step is non-recursive. We just add declarations to `Sema`'s 
> > "to be instantiated at end of TU" list. This is at least a little important 
> > semantically: we allow a matching specialization to be declared after the 
> > first use wherever possible. In that case, 

[PATCH] D126566: [ODRHash][NFC] Add missing 'select' case for `ODRMismatchDecl`.

2022-05-27 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added a reviewer: rtrieu.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.

No test changes because `err_module_odr_violation_mismatch_decl_unknown`
is a catch-all when custom diagnostic is missing. And missing custom
diagnostic we should fix by implementing it, not by improving the
general case. But if we pass enum value not covered by 'select', clang
can crash, so protect against that.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126566

Files:
  clang/include/clang/Basic/DiagnosticSerializationKinds.td


Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -375,12 +375,14 @@
   "%q0 %select{with definition in module '%2'|defined here}1 has different "
   "definitions in different modules; first difference is this "
   "%select{static assert|field|method|type alias|typedef|data member|"
-  "friend declaration|unexpected decl}3">;
+  "friend declaration|function template|"
+  "unexpected decl}3">;
 def note_module_odr_violation_mismatch_decl_unknown : Note<
   "but in '%0' found "
   "%select{different static assert|different field|different method|"
   "different type alias|different typedef|different data member|"
-  "different friend declaration|another unexpected decl}1">;
+  "different friend declaration|different function template|"
+  "another unexpected decl}1">;
 
 def warn_duplicate_module_file_extension : Warning<
   "duplicate module file extension block name '%0'">,


Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -375,12 +375,14 @@
   "%q0 %select{with definition in module '%2'|defined here}1 has different "
   "definitions in different modules; first difference is this "
   "%select{static assert|field|method|type alias|typedef|data member|"
-  "friend declaration|unexpected decl}3">;
+  "friend declaration|function template|"
+  "unexpected decl}3">;
 def note_module_odr_violation_mismatch_decl_unknown : Note<
   "but in '%0' found "
   "%select{different static assert|different field|different method|"
   "different type alias|different typedef|different data member|"
-  "different friend declaration|another unexpected decl}1">;
+  "different friend declaration|different function template|"
+  "another unexpected decl}1">;
 
 def warn_duplicate_module_file_extension : Warning<
   "duplicate module file extension block name '%0'">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-05-27 Thread Petr Hosek via Phabricator via cfe-commits
phosek added inline comments.



Comment at: clang/cmake/caches/Fuchsia-stage2.cmake:124
 set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
-set(RUNTIMES_${target}_LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
 set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")

ldionne wrote:
> ldionne wrote:
> > phosek wrote:
> > > ldionne wrote:
> > > > phosek wrote:
> > > > > ldionne wrote:
> > > > > > Note that I am removing these options here because I don't think 
> > > > > > they are required -- since we specify 
> > > > > > `LIBCXXABI_ENABLE_SHARED=OFF`, there is no shared libc++abi to link 
> > > > > > against, so we should already be linking against `libc++abi.a` 
> > > > > > regardless of this change.
> > > > > This option was set to merge `libc++abi.a` into `libc++.a` so to 
> > > > > achieve the same effect, presumably we would need to set 
> > > > > `-DLIBCXX_CXX_ABI=libcxxabi-objects`?
> > > > I agree this is suspicious, but why is there no 
> > > > `LIBCXX_STATICALLY_LINK_ABI_IN_SHARED_LIBRARY` specified here then? I 
> > > > can add `-DLIBCXX_CXX_ABI=libcxxabi-objects`, I just want to make sure 
> > > > we both understand what's going on.
> > > This is intentional. We are merging `libc++abi.a` into `libc++.a` but we 
> > > ship `libc++abi.so` and `libc++.so` as separate (and use the generated 
> > > linker script to pull in `libc++abi.so` when you pass `-lc++` to linker). 
> > > I'd be fine merging `libc++abi.so` into `libc++.so` as well, but we'll 
> > > need to figure out a transition plan since there are several places in 
> > > our build right now that expect `libc++abi.so` to exist. We cannot land 
> > > this change as is because that would break the `-static-libstdc++` use 
> > > case, since Clang driver only passes `-lc++` to the linker and not 
> > > `-lc++abi` and there's nothing that would pull `libc++abi.a` in.
> > I see, so to summarize, basically you want to use `libcxxabi-objects` for 
> > the static `libc++.a`, but `libcxxabi` for the dynamic `libc++.so`. This 
> > change as currently laid out does not permit that to happen, since 
> > `libcxxabi-objects` implies that the objects are merged both in the static 
> > and in the shared library. I guess we could introduce a new 
> > `libcxxabi-objects-static` option, however that would be kind of strange. 
> > We can either do that, or wait for you to stop relying on `libc++abi.so` 
> > existing and switch to `libcxxabi-objects` wholesale for Fuchsia. WDYT?
> Gentle ping. It would be nice to land this in one form or another. If you 
> don't think Fuchsia can stop relying on `libc++abi.so` being there, I could 
> add yet another `libcxxabi-objects-static` -- I still feel like that's better 
> than the status quo.
We discussed this on our team and we don't have any issues switching towards 
combined `libc++.so`, we just need to figure out a transition plan. Let me test 
this change locally to see if landing this as is will break anything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125683

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


[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-05-27 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 432634.
ldionne added a comment.

Rebase onto main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125683

Files:
  clang/cmake/caches/Android.cmake
  clang/cmake/caches/Fuchsia-stage2.cmake
  clang/cmake/caches/Fuchsia.cmake
  compiler-rt/cmake/Modules/AddCompilerRT.cmake
  libcxx/CMakeLists.txt
  libcxx/cmake/Modules/HandleLibCXXABI.cmake
  libcxx/cmake/caches/MinGW.cmake
  libcxx/docs/BuildingLibcxx.rst
  libcxx/docs/ReleaseNotes.rst
  libcxx/src/CMakeLists.txt
  libcxx/test/CMakeLists.txt
  libcxx/test/configs/legacy.cfg.in
  libcxx/utils/ci/run-buildbot
  llvm/docs/HowToBuildWindowsItaniumPrograms.rst

Index: llvm/docs/HowToBuildWindowsItaniumPrograms.rst
===
--- llvm/docs/HowToBuildWindowsItaniumPrograms.rst
+++ llvm/docs/HowToBuildWindowsItaniumPrograms.rst
@@ -124,7 +124,6 @@
 * ``-DLIBCXXABI_ENABLE_SHARED=OFF``
 * ``-DLIBCXXABI_ENABLE_STATIC=ON``
 * ``-DLIBCXX_ENABLE_SHARED=ON'``
-* ``-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON``
 
 To break the symbol dependency between libc++abi and libc++ we
 build libc++abi as a static library and then statically link it
@@ -157,8 +156,7 @@
 
 Windows Itanium does not offer a POSIX-like layer over WIN32.
 
-* ``-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON``
-* ``-DLIBCXX_CXX_ABI=libcxxabi``
+* ``-DLIBCXX_CXX_ABI=libcxxabi-objects``
 * ``-DLIBCXX_CXX_ABI_INCLUDE_PATHS=/include``
 * ``-DLIBCXX_CXX_ABI_LIBRARY_PATH=/lib``
 
Index: libcxx/utils/ci/run-buildbot
===
--- libcxx/utils/ci/run-buildbot
+++ libcxx/utils/ci/run-buildbot
@@ -93,7 +93,6 @@
 function generate-cmake() {
 generate-cmake-base \
   -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" \
-  -DLIBCXX_CXX_ABI=libcxxabi \
   "${@}"
 }
 
@@ -478,8 +477,7 @@
   -GNinja -DCMAKE_MAKE_PROGRAM="${NINJA}" \
   -DCMAKE_BUILD_TYPE=RelWithDebInfo \
   -DCMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \
-  -DLLVM_LIT_ARGS="-sv --show-unsupported --xunit-xml-output test-results.xml --timeout=1200" \
-  -DLIBCXX_CXX_ABI=libcxxabi
+  -DLLVM_LIT_ARGS="-sv --show-unsupported --xunit-xml-output test-results.xml --timeout=1200"
 check-runtimes
 ;;
 aarch64)
Index: libcxx/test/configs/legacy.cfg.in
===
--- libcxx/test/configs/legacy.cfg.in
+++ libcxx/test/configs/legacy.cfg.in
@@ -14,7 +14,7 @@
 config.cxx_library_root = "@LIBCXX_LIBRARY_DIR@"
 config.abi_library_root = "@LIBCXX_CXX_ABI_LIBRARY_PATH@"
 config.enable_shared= @LIBCXX_LINK_TESTS_WITH_SHARED_LIBCXX@
-config.cxx_abi  = "@LIBCXX_CXXABI_FOR_TESTS@"
+config.cxx_abi  = "@LIBCXX_CXX_ABI@"
 config.configuration_variant= "@LIBCXX_LIT_VARIANT@"
 config.host_triple  = "@LLVM_HOST_TRIPLE@"
 config.sysroot  = "@CMAKE_SYSROOT@"
Index: libcxx/test/CMakeLists.txt
===
--- libcxx/test/CMakeLists.txt
+++ libcxx/test/CMakeLists.txt
@@ -14,14 +14,6 @@
 set(LIBCXX_TEST_COMPILER_FLAGS "" CACHE STRING
 "Additonal linker flags to pass when compiling the tests")
 
-# The tests shouldn't link to any ABI library when it has been linked into
-# libc++ statically or via a linker script.
-if (LIBCXX_ENABLE_STATIC_ABI_LIBRARY OR LIBCXX_ENABLE_ABI_LINKER_SCRIPT)
-  set(LIBCXX_CXXABI_FOR_TESTS "none")
-else()
-  set(LIBCXX_CXXABI_FOR_TESTS "${LIBCXX_CXX_ABI}")
-endif()
-
 # The tests shouldn't link to libunwind if we have a linker script which
 # already does so.
 if (LIBCXX_ENABLE_ABI_LINKER_SCRIPT)
Index: libcxx/src/CMakeLists.txt
===
--- libcxx/src/CMakeLists.txt
+++ libcxx/src/CMakeLists.txt
@@ -204,7 +204,7 @@
 if (LIBCXX_ENABLE_SHARED)
   add_library(cxx_shared SHARED ${exclude_from_all} ${LIBCXX_SOURCES} ${LIBCXX_HEADERS})
   target_include_directories(cxx_shared PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
-  target_link_libraries(cxx_shared PUBLIC cxx-headers
+  target_link_libraries(cxx_shared PUBLIC cxx-headers libcxx-abi-shared
PRIVATE ${LIBCXX_LIBRARIES})
   set_target_properties(cxx_shared
 PROPERTIES
@@ -232,19 +232,9 @@
 endif()
   endif()
 
-  # Link against libc++abi
-  if (LIBCXX_STATICALLY_LINK_ABI_IN_SHARED_LIBRARY)
-target_link_libraries(cxx_shared PRIVATE libcxx-abi-shared-objects)
-  else()
-target_link_libraries(cxx_shared PUBLIC libcxx-abi-shared)
-  endif()
-
   # Maybe re-export symbols from libc++abi
-  # In particular, we don't re-export the symbols if libc++abi is merged statically
-  # into libc++ because in that case there's no dylib to re-export from.
   if (APPLE AND LIBCXX_CXX_ABI STREQUAL "libcxxabi"
-AND NOT 

[PATCH] D125683: [runtimes] Replace LIBCXX_ENABLE_STATIC_ABI_LIBRARY & friends by a new LIBCXX_CXX_ABI choice

2022-05-27 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added inline comments.



Comment at: clang/cmake/caches/Fuchsia-stage2.cmake:124
 set(RUNTIMES_${target}_LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
-set(RUNTIMES_${target}_LIBCXX_ENABLE_STATIC_ABI_LIBRARY ON CACHE BOOL "")
 set(RUNTIMES_${target}_LIBCXX_ABI_VERSION 2 CACHE STRING "")

ldionne wrote:
> phosek wrote:
> > ldionne wrote:
> > > phosek wrote:
> > > > ldionne wrote:
> > > > > Note that I am removing these options here because I don't think they 
> > > > > are required -- since we specify `LIBCXXABI_ENABLE_SHARED=OFF`, there 
> > > > > is no shared libc++abi to link against, so we should already be 
> > > > > linking against `libc++abi.a` regardless of this change.
> > > > This option was set to merge `libc++abi.a` into `libc++.a` so to 
> > > > achieve the same effect, presumably we would need to set 
> > > > `-DLIBCXX_CXX_ABI=libcxxabi-objects`?
> > > I agree this is suspicious, but why is there no 
> > > `LIBCXX_STATICALLY_LINK_ABI_IN_SHARED_LIBRARY` specified here then? I can 
> > > add `-DLIBCXX_CXX_ABI=libcxxabi-objects`, I just want to make sure we 
> > > both understand what's going on.
> > This is intentional. We are merging `libc++abi.a` into `libc++.a` but we 
> > ship `libc++abi.so` and `libc++.so` as separate (and use the generated 
> > linker script to pull in `libc++abi.so` when you pass `-lc++` to linker). 
> > I'd be fine merging `libc++abi.so` into `libc++.so` as well, but we'll need 
> > to figure out a transition plan since there are several places in our build 
> > right now that expect `libc++abi.so` to exist. We cannot land this change 
> > as is because that would break the `-static-libstdc++` use case, since 
> > Clang driver only passes `-lc++` to the linker and not `-lc++abi` and 
> > there's nothing that would pull `libc++abi.a` in.
> I see, so to summarize, basically you want to use `libcxxabi-objects` for the 
> static `libc++.a`, but `libcxxabi` for the dynamic `libc++.so`. This change 
> as currently laid out does not permit that to happen, since 
> `libcxxabi-objects` implies that the objects are merged both in the static 
> and in the shared library. I guess we could introduce a new 
> `libcxxabi-objects-static` option, however that would be kind of strange. We 
> can either do that, or wait for you to stop relying on `libc++abi.so` 
> existing and switch to `libcxxabi-objects` wholesale for Fuchsia. WDYT?
Gentle ping. It would be nice to land this in one form or another. If you don't 
think Fuchsia can stop relying on `libc++abi.so` being there, I could add yet 
another `libcxxabi-objects-static` -- I still feel like that's better than the 
status quo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125683

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


[PATCH] D125695: [clang][DebugInfo] Allow function-local type-like entities to be scoped within a lexical block (5/5)

2022-05-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:231-234
+  assert(LexicalBlockMap.find() == LexicalBlockMap.end() &&
+ "D is already mapped to a lexical block scope");
+  if (!LexicalBlockStack.empty())
+LexicalBlockMap.insert({, LexicalBlockStack.back()});

Rather than doing an extra lookup in the assert, could probably check the 
return value of `insert` instead and assert based on that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125695

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


[PATCH] D126412: Fix a buglet in remove_dots().

2022-05-27 Thread Paul Pluzhnikov via Phabricator via cfe-commits
ppluzhnikov created this revision.
Herald added a subscriber: hiraditya.
Herald added a project: All.
ppluzhnikov updated this revision to Diff 432324.
ppluzhnikov added a comment.
ppluzhnikov updated this revision to Diff 432461.
ppluzhnikov updated this revision to Diff 432551.
ppluzhnikov updated this revision to Diff 432577.
ppluzhnikov updated this revision to Diff 432592.
ppluzhnikov updated this revision to Diff 432612.
ppluzhnikov updated this revision to Diff 432623.
ppluzhnikov published this revision for review.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Fix failed tests.


ppluzhnikov added a comment.

Rebase to ToT.


ppluzhnikov added a comment.

Fix InMemoryFileSystemTest bug.


ppluzhnikov added a comment.

Fix ProxyFileSystemTest.Basic on Win/x64


ppluzhnikov added a comment.

One more ProxyFileSystemTest fixe.


ppluzhnikov added a comment.

Fix compile failure.


ppluzhnikov added a comment.

Fix formatting.


The function promises to canonicalize the path, but neglected to do so
for the root component.

For example, calling remove_dots("/tmp/foo.c", Style::windows_backslash)
resulted in "/tmp\foo.c". Now it produces "\tmp\foo.c".

Also fix FIXME in the corresponding test.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126412

Files:
  clang/unittests/Basic/FileManagerTest.cpp
  clang/unittests/Frontend/PCHPreambleTest.cpp
  llvm/lib/Support/Path.cpp
  llvm/unittests/Support/Path.cpp
  llvm/unittests/Support/VirtualFileSystemTest.cpp

Index: llvm/unittests/Support/VirtualFileSystemTest.cpp
===
--- llvm/unittests/Support/VirtualFileSystemTest.cpp
+++ llvm/unittests/Support/VirtualFileSystemTest.cpp
@@ -199,7 +199,7 @@
 };
 
 /// Replace back-slashes by front-slashes.
-std::string getPosixPath(std::string S) {
+std::string getPosixPath(const Twine ) {
   SmallString<128> Result;
   llvm::sys::path::native(S, Result, llvm::sys::path::Style::posix);
   return std::string(Result.str());
@@ -923,11 +923,11 @@
 
   auto PWD = PFS.getCurrentWorkingDirectory();
   ASSERT_FALSE(PWD.getError());
-  ASSERT_EQ("/", *PWD);
+  ASSERT_EQ("/", getPosixPath(*PWD));
 
   SmallString<16> Path;
   ASSERT_FALSE(PFS.getRealPath("a", Path));
-  ASSERT_EQ("/a", Path);
+  ASSERT_EQ("/a", getPosixPath(Path));
 
   bool Local = true;
   ASSERT_FALSE(PFS.isLocal("/a", Local));
@@ -1343,7 +1343,8 @@
   EXPECT_NE(FS.status("/a")->getUniqueID(), FS.status("/e")->getUniqueID());
 
   // Recreating the "same" FS yields the same UniqueIDs.
-  vfs::InMemoryFileSystem FS2;
+  // Note: FS2 should match FS with respect to path normalization.
+  vfs::InMemoryFileSystem FS2(/*UseNormalizedPath=*/false);
   ASSERT_TRUE(FS2.addFile("/a/b", 0, MemoryBuffer::getMemBuffer("text")));
   EXPECT_EQ(FS.status("/a/b")->getUniqueID(),
 FS2.status("/a/b")->getUniqueID());
Index: llvm/unittests/Support/Path.cpp
===
--- llvm/unittests/Support/Path.cpp
+++ llvm/unittests/Support/Path.cpp
@@ -1544,16 +1544,14 @@
   EXPECT_EQ("C:\\a\\c", remove_dots("C:\\foo\\bar//..\\..\\a\\c", true,
 path::Style::windows));
 
-  // FIXME: These leading forward slashes are emergent behavior. VFS depends on
-  // this behavior now.
-  EXPECT_EQ("C:/bar",
+  EXPECT_EQ("C:\\bar",
 remove_dots("C:/foo/../bar", true, path::Style::windows));
-  EXPECT_EQ("C:/foo\\bar",
+  EXPECT_EQ("C:\\foo\\bar",
 remove_dots("C:/foo/bar", true, path::Style::windows));
-  EXPECT_EQ("C:/foo\\bar",
+  EXPECT_EQ("C:\\foo\\bar",
 remove_dots("C:/foo\\bar", true, path::Style::windows));
-  EXPECT_EQ("/", remove_dots("/", true, path::Style::windows));
-  EXPECT_EQ("C:/", remove_dots("C:/", true, path::Style::windows));
+  EXPECT_EQ("\\", remove_dots("/", true, path::Style::windows));
+  EXPECT_EQ("C:\\", remove_dots("C:/", true, path::Style::windows));
 
   // Some clients of remove_dots expect it to remove trailing slashes. Again,
   // this is emergent behavior that VFS relies on, and not inherently part of
@@ -1564,7 +1562,8 @@
 remove_dots("/foo/bar/", true, path::Style::posix));
 
   // A double separator is rewritten.
-  EXPECT_EQ("C:/foo\\bar", remove_dots("C:/foo//bar", true, path::Style::windows));
+  EXPECT_EQ("C:\\foo\\bar",
+remove_dots("C:/foo//bar", true, path::Style::windows));
 
   SmallString<64> Path1(".\\.\\c");
   EXPECT_TRUE(path::remove_dots(Path1, true, path::Style::windows));
Index: llvm/lib/Support/Path.cpp
===
--- llvm/lib/Support/Path.cpp
+++ llvm/lib/Support/Path.cpp
@@ -760,11 +760,15 @@
 }
   }
 
+  SmallString<256> buffer = root;
+  // "root" could be "/", which may need to be translated into "\".
+  make_preferred(buffer, style);
+  needs_change |= root != buffer;
+
   // Avoid rewriting 

[PATCH] D126068: [llvm][clang][bolt][NFC] Use llvm::less_first() when applicable

2022-05-27 Thread Chris Lattner via Phabricator via cfe-commits
lattner added a comment.

This patch LGTM other than the apparent build breakage


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126068

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


[PATCH] D126084: [Sema] Reject implicit conversions between different scoped enum types in list initialization

2022-05-27 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:4506
 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
-(E->getType()->isIntegralOrEnumerationType() ||
+(E->getType()->isIntegralOrUnscopedEnumerationType() ||
  E->getType()->isFloatingType())) {

ahatanak wrote:
> aaron.ballman wrote:
> > ahatanak wrote:
> > > aaron.ballman wrote:
> > > > This doesn't match the comments immediately above here and I don't 
> > > > think is the correct fix.
> > > > 
> > > > We're handling this case: http://eel.is/c++draft/dcl.init.list#3.8
> > > > 
> > > > A scoped enumeration has a fixed underlying type 
> > > > (https://eel.is/c++draft/dcl.enum#5.sentence-5). The initializer list 
> > > > has a single element and that element can be implicitly converted to 
> > > > the underlying type (`int` in all of the test cases changed in this 
> > > > patch). And this is a direct initialization case, so I think we should 
> > > > be performing the conversion here rather than skipping to the next 
> > > > bullet.
> > > Can scoped enums be implicitly converted to integer types? Unscoped enums 
> > > can be converted to an integer type, but I don't see any mention of 
> > > scoped enums here: https://eel.is/c++draft/conv.integral
> > > 
> > > It seems that the original paper was trying to change the rules about 
> > > conversions from the underlying type to a scoped enum. It doesn't look 
> > > like it's allowing conversion from a scope enum to another scope enum.
> > > 
> > > https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf
> > > Can scoped enums be implicitly converted to integer types? Unscoped enums 
> > > can be converted to an integer type, but I don't see any mention of 
> > > scoped enums here: https://eel.is/c++draft/conv.integral
> > 
> > Correct, they cannot be implicitly converted to an integer.
> > 
> > > It seems that the original paper was trying to change the rules about 
> > > conversions from the underlying type to a scoped enum. It doesn't look 
> > > like it's allowing conversion from a scope enum to another scope enum.
> > 
> > Agreed, however, I think where we want this to fail is below in the attempt 
> > at conversion. "v can be implicitly converted to U" is the part that should 
> > be failing here, and we're now skipping over the bit of code that's 
> > checking whether the implicit conversion is valid.
> Is the code below checking whether the implicit conversion is valid? It looks 
> like it's assuming the implicit conversion is valid and adding an implicit 
> conversion sequence based on that assumption. If the source is an integer, 
> unscoped enum, or floating type, the implicit conversion that is performed 
> later should succeed except when there is narrowing.
> 
> Or are you suggesting we should add a check to 
> `Sema::PerformImplicitConversion` that rejects conversions from scoped enums 
> to other types? It seems to me that it's better to detect the error earlier.
Alternatively, we can emit a diagnostic in the code below that specifically 
calls out conversion from scoped enums to integer types.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126084

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


[PATCH] D126084: [Sema] Reject implicit conversions between different scoped enum types in list initialization

2022-05-27 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/Sema/SemaInit.cpp:4506
 !S.Context.hasSameUnqualifiedType(E->getType(), DestType) &&
-(E->getType()->isIntegralOrEnumerationType() ||
+(E->getType()->isIntegralOrUnscopedEnumerationType() ||
  E->getType()->isFloatingType())) {

aaron.ballman wrote:
> ahatanak wrote:
> > aaron.ballman wrote:
> > > This doesn't match the comments immediately above here and I don't think 
> > > is the correct fix.
> > > 
> > > We're handling this case: http://eel.is/c++draft/dcl.init.list#3.8
> > > 
> > > A scoped enumeration has a fixed underlying type 
> > > (https://eel.is/c++draft/dcl.enum#5.sentence-5). The initializer list has 
> > > a single element and that element can be implicitly converted to the 
> > > underlying type (`int` in all of the test cases changed in this patch). 
> > > And this is a direct initialization case, so I think we should be 
> > > performing the conversion here rather than skipping to the next bullet.
> > Can scoped enums be implicitly converted to integer types? Unscoped enums 
> > can be converted to an integer type, but I don't see any mention of scoped 
> > enums here: https://eel.is/c++draft/conv.integral
> > 
> > It seems that the original paper was trying to change the rules about 
> > conversions from the underlying type to a scoped enum. It doesn't look like 
> > it's allowing conversion from a scope enum to another scope enum.
> > 
> > https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf
> > Can scoped enums be implicitly converted to integer types? Unscoped enums 
> > can be converted to an integer type, but I don't see any mention of scoped 
> > enums here: https://eel.is/c++draft/conv.integral
> 
> Correct, they cannot be implicitly converted to an integer.
> 
> > It seems that the original paper was trying to change the rules about 
> > conversions from the underlying type to a scoped enum. It doesn't look like 
> > it's allowing conversion from a scope enum to another scope enum.
> 
> Agreed, however, I think where we want this to fail is below in the attempt 
> at conversion. "v can be implicitly converted to U" is the part that should 
> be failing here, and we're now skipping over the bit of code that's checking 
> whether the implicit conversion is valid.
Is the code below checking whether the implicit conversion is valid? It looks 
like it's assuming the implicit conversion is valid and adding an implicit 
conversion sequence based on that assumption. If the source is an integer, 
unscoped enum, or floating type, the implicit conversion that is performed 
later should succeed except when there is narrowing.

Or are you suggesting we should add a check to 
`Sema::PerformImplicitConversion` that rejects conversions from scoped enums to 
other types? It seems to me that it's better to detect the error earlier.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126084

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


[PATCH] D125094: [ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records

2022-05-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: llvm/lib/Target/ARM/ARMFrameLowering.cpp:732
+  // AAPCS requires use of R11, and PACBTI gets in the way of regular pushes,
+  // so FP ends up on area two.
   if (HasFP) {

I guess this is related to this patch because it involves the interaction of 
PACBTI with -mframe_chain ?  (Without this patch, PACBTI doesn't exist on any 
targets where the frame pointer is in r11.)  I'm fine leaving it to a followup, 
though.



Comment at: llvm/lib/Target/ARM/Thumb1FrameLowering.cpp:1118
+
+  // Determine intermidiate registers which can be used for pushing high regs:
+  // - Spilled low regs

*intermediate.



Comment at: llvm/lib/Target/ARM/ThumbRegisterInfo.cpp:545
   MI.getOperand(FIOperandNum+1).ChangeToRegister(FrameReg, false, false,
  false);
   } else if (MI.mayStore()) {

Do we need to do something different here if FrameReg is r11?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125094

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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code

2022-05-27 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: NoQ, steakhal.
Herald added subscribers: manas, ASDenysPetrov, gamesh411, dkrupp, donat.nagy, 
Szelethus, mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a project: All.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Since D113753 , we simplify the symbols right 
at the beginning of
evalBinOpNN. Since D114938 , we do the 
simplification until a fix-point
is reached.
These changes renders the two workarounds introduced in D47155 
 and in
D51252  superfluous.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126560

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1190,7 +1190,6 @@
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
-  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 
@@ -1376,14 +1375,6 @@
 SVal VisitSVal(SVal V) { return V; }
   };
 
-  // A crude way of preventing this function from calling itself from 
evalBinOp.
-  static bool isReentering = false;
-  if (isReentering)
-return V;
-
-  isReentering = true;
   SVal SimplifiedV = Simplifier(State).Visit(V);
-  isReentering = false;
-
   return SimplifiedV;
 }


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1190,7 +1190,6 @@
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
-  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 
@@ -1376,14 +1375,6 @@
 SVal VisitSVal(SVal V) { return V; }
   };
 
-  // A crude way of preventing this function from calling itself from evalBinOp.
-  static bool isReentering = false;
-  if (isReentering)
-return V;
-
-  isReentering = true;
   SVal SimplifiedV = Simplifier(State).Visit(V);
-  isReentering = false;
-
   return SimplifiedV;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-27 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Haven't had a chance to try it yet, but based on a quick glance, my suspicion 
is that the problem is the use of `ReferenceType::getPointeeType()`, which may 
do more unwrapping than we want (its implementation contains a loop 
).

I would try using getPointeeTypeAsWritten() 

 instead and see if that helps.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

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


[PATCH] D124753: [HLSL] Set main as default entry.

2022-05-27 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 432606.
python3kgae marked 2 inline comments as done.
python3kgae added a comment.

Use default value of MarshallingInfoString.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124753

Files:
  clang/include/clang/Driver/Options.td
  clang/test/CodeGenHLSL/entry_default.hlsl


Index: clang/test/CodeGenHLSL/entry_default.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/entry_default.hlsl
@@ -0,0 +1,28 @@
+// RUN: %clang --driver-mode=dxc -Tcs_6_1 -fcgl -Fo - %s | FileCheck %s
+// RUN: %clang --driver-mode=dxc -Efoo -Tcs_6_1 -fcgl -Fo - %s | FileCheck %s 
--check-prefix=NOTMAIN
+
+// Make sure main is default entry.
+// Make sure not mangle entry.
+// CHECK:define void @main() [[MAIN_ATTR:#[0-9]]]
+// CHECK:define void @_Z3foov() [[FOO_ATTR:#[0-9]]]
+// Make sure only main has dx.shader attribute.
+// CHECK:[[MAIN_ATTR]]
+// CHECK:"dx.shader"="compute"
+// CHECK-SAME:}
+// CHECK:[[FOO_ATTR]]
+// CHECK-NOT:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void main() {
+
+}
+
+// NOTMAIN:define void @main() [[MAIN_ATTR:#[0-9]]]
+// NOTMAIN:define void @foo() [[FOO_ATTR:#[0-9]]]
+// Make sure only foo has dx.shader attribute.
+// NOTMAIN:[[MAIN_ATTR]]
+// NOTMAIN-NOT:"dx.shader"="compute"
+// NOTMAIN-SAME:}
+// NOTMAIN:[[FOO_ATTR]]
+// NOTMAIN-SAME:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void foo() {
+
+}
\ No newline at end of file
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6810,5 +6810,5 @@
 def hlsl_entrypoint : Option<["--", "/", "-"], "E", KIND_JOINED_OR_SEPARATE>,
   Group,
   Flags<[DXCOption, CC1Option, NoXarchOption]>,
-  MarshallingInfoString>,
+  MarshallingInfoString, 
"\"main\"">,
   HelpText<"Entry point name">;


Index: clang/test/CodeGenHLSL/entry_default.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/entry_default.hlsl
@@ -0,0 +1,28 @@
+// RUN: %clang --driver-mode=dxc -Tcs_6_1 -fcgl -Fo - %s | FileCheck %s
+// RUN: %clang --driver-mode=dxc -Efoo -Tcs_6_1 -fcgl -Fo - %s | FileCheck %s --check-prefix=NOTMAIN
+
+// Make sure main is default entry.
+// Make sure not mangle entry.
+// CHECK:define void @main() [[MAIN_ATTR:#[0-9]]]
+// CHECK:define void @_Z3foov() [[FOO_ATTR:#[0-9]]]
+// Make sure only main has dx.shader attribute.
+// CHECK:[[MAIN_ATTR]]
+// CHECK:"dx.shader"="compute"
+// CHECK-SAME:}
+// CHECK:[[FOO_ATTR]]
+// CHECK-NOT:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void main() {
+
+}
+
+// NOTMAIN:define void @main() [[MAIN_ATTR:#[0-9]]]
+// NOTMAIN:define void @foo() [[FOO_ATTR:#[0-9]]]
+// Make sure only foo has dx.shader attribute.
+// NOTMAIN:[[MAIN_ATTR]]
+// NOTMAIN-NOT:"dx.shader"="compute"
+// NOTMAIN-SAME:}
+// NOTMAIN:[[FOO_ATTR]]
+// NOTMAIN-SAME:"dx.shader"="compute"
+[numthreads(1, 1, 1)] void foo() {
+
+}
\ No newline at end of file
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6810,5 +6810,5 @@
 def hlsl_entrypoint : Option<["--", "/", "-"], "E", KIND_JOINED_OR_SEPARATE>,
   Group,
   Flags<[DXCOption, CC1Option, NoXarchOption]>,
-  MarshallingInfoString>,
+  MarshallingInfoString, "\"main\"">,
   HelpText<"Entry point name">;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126559: [MSVC] Fix pragma alloc_text failing for C files

2022-05-27 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126559

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


[PATCH] D116088: [compiler-rt] Implement ARM atomic operations for architectures without SMP support

2022-05-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

ldr+op+swp still isn't atomic.  For each point in the code, please try the 
exercise of "what if my code is interrupted here"?

The only way to use swp to implement general atomic operations is to use a 
separate spinlock.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116088

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


[PATCH] D126481: [analyzer] Handle SymbolCast in SValBuilder

2022-05-27 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

@martong As you said, my solution D103096  
suppose to pass these and more other tests cases. So how it will help in 
combination with my solution D103096 ? 
Although, your patch is really simple but it's more like a plug then a real 
`SymbolCast ` support, isn't it? I don't quite understand the motivation.




Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1354
+return I->second;
+  const SymExpr *OpSym = S->getOperand();
+  SVal OpVal = getConstOrVisit(OpSym);

Should this imply to use the root symbol and not the second nested one?
E.g. from `(int)(short)(x)` do you want `(short)(x)` or `(x)`?
`getOperand` gives you `(short)(x)` in this case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126481

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


[PATCH] D126364: Fix interaction of pragma FENV_ACCESS with other pragmas

2022-05-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I mean that ActOnPragmaFEnvAccess shouldn't call 
hasRoundingModeOverride()/setRoundingModeOverride(), and setRoundingMode 
shouldn't call getAllowFEnvAccess().


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D126341: Order implicitly instantiated global variable's initializer by the reverse instantiation order

2022-05-27 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:563
+  } else if (IsInstantiation ||
  getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR ||
  D->hasAttr()) {

rsmith wrote:
> rnk wrote:
> > @rsmith , if inline global variable initialization has ordering 
> > requirements, we have a bug, because I believe this GVA_DiscardableODR 
> > codepath handles them, and we come through here to give them separate 
> > initializers in llvm.global_ctors. See the example with two separate 
> > global_ctors entries on godbolt:
> > https://gcc.godbolt.org/z/5d577snqb
> > 
> > As long as LLVM doesn't provide ordering guarantees about same priority 
> > initializers in global_ctors, inline globals have the same problems as 
> > template instantiations. IMO whatever solution we use to order inline 
> > globals should be used for template instantiations.
> > 
> > Intuitively, that means LLVM should promise to run global_ctors in 
> > left-to-right order, and if all TUs instantiate initializers in the same 
> > order, everything should behave intuitively.
> > 
> > The question then becomes, why doesn't this work already?
> > Intuitively, that means LLVM should promise to run global_ctors in 
> > left-to-right order
> 
> I don't think that's sufficient, due to the way we use COMDATs to discard 
> duplicate global initializers. Consider:
> 
> TU 1 defines inline variable A.
> TU 2 defines inline variable A and then inline variable B.
> The standard guarantees that A is initialized before B in this scenario. But 
> if (somehow) the linker picks the definition of A from TU 2, but orders the 
> initializers from TU 1 first, then the resulting global_ctors order will be B 
> then A, which is not allowed.
> 
> Either we need a guarantee that linkers will use the same ordering between 
> objects when picking COMDATs as when concatenating `.init_array`, or we need 
> to stop using the COMDAT trick for them (and either make LLVM respect the 
> `@llvm.global_ctors` order or coalesce all inline variable initializers into 
> the same function we run non-inline initializers from or something). Getting 
> that guarantee seems like the best path to me, since the other option will 
> presumably mean we check the guard variable once on startup for each TU that 
> defines the variable, and it's something I expect linkers already happen to 
> guarantee in practice.
> 
> > IMO whatever solution we use to order inline globals should be used for 
> > template instantiations.
> 
> That sounds like it would regress what globalopt is able to optimize, for no 
> gain in conformance nor perhaps any real gain in initialization order 
> guarantees. The inline variable case is different, both because we can 
> guarantee an initialization order and because the standard requires us to do 
> so. Should we add complexity to the compiler whose only purpose is to mask 
> bugs, if that complexity doesn't actually define away the possibility of bad 
> behavior?
> 
> If we can actually describe a rule that we provide for initialization order 
> of instantiated variables, and we can easily implement that rule and be 
> confident we won't want to substantially weaken it later, and we can thereby 
> assure our users that we will satisfy that rule, then I think that could be 
> interesting, but anything less than that doesn't seem worthwhile to me.
> 
> > The question then becomes, why doesn't this work already?
> 
> It looks like it mostly does.
> 
> One factor here is instantiation order. When we instantiate a variable, we 
> add the variables that it references to our "to be instantiated" list, which 
> is processed later:
> ```
> template int Fib = Fib + Fib;
> template<> int Fib<0> = 0;
> template<> int Fib<1> = 1;
> ```
> * instantiating `Fib<5>` will append `Fib<3>` and `Fib<4>` to the list
> * then we visit `Fib<3>` and append `Fib<1>` and `Fib<2>` to the list
> * then we visit `Fib<4>` and add no new entries
> 
> We pass declarations to the consumer when we're done with the instantiation 
> step. *Sometimes* this includes instantiating variables referenced by that 
> variable, and *sometimes* it doesn't. The difference is whether we're 
> performing "recursive" instantiation or not.
> 
> When we're performing immediate instantiation of a variable (either because 
> it was explicitly instantiated, or because we might need its value 
> immediately because it might be usable in constant expressions), our 
> instantiation step is non-recursive. We just add declarations to `Sema`'s "to 
> be instantiated at end of TU" list. This is at least a little important 
> semantically: we allow a matching specialization to be declared after the 
> first use wherever possible. In that case, we'll pass a declaration to the 
> consumer before we've instantiated the things it references.
> 
> When we're performing the end-of-TU instantiation of all referenced template 
> 

[PATCH] D126559: [MSVC] Fix pragma alloc_text failing for C files

2022-05-27 Thread Stephen Long via Phabricator via cfe-commits
steplong created this revision.
Herald added a project: All.
steplong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`isExternCContext()` is returning false for functions in C files

Change-Id: I51cccb476aa19dc0a0a78e951d7f482befdb78ca


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126559

Files:
  clang/lib/Sema/SemaAttr.cpp
  clang/test/Sema/pragma-ms-alloc-text.c


Index: clang/test/Sema/pragma-ms-alloc-text.c
===
--- /dev/null
+++ clang/test/Sema/pragma-ms-alloc-text.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+void foo();
+#pragma alloc_text("hello", foo) // expected-no-diagnostics
+void foo() {}
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -762,8 +762,8 @@
   return;
 }
 
-DeclContext *DC = ND->getDeclContext();
-if (!DC->isExternCContext()) {
+FunctionDecl *FD = ND->getAsFunction();
+if (!FD->isExternC()) {
   Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
   return;
 }


Index: clang/test/Sema/pragma-ms-alloc-text.c
===
--- /dev/null
+++ clang/test/Sema/pragma-ms-alloc-text.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+void foo();
+#pragma alloc_text("hello", foo) // expected-no-diagnostics
+void foo() {}
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -762,8 +762,8 @@
   return;
 }
 
-DeclContext *DC = ND->getDeclContext();
-if (!DC->isExternCContext()) {
+FunctionDecl *FD = ND->getAsFunction();
+if (!FD->isExternC()) {
   Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
   return;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126137: [X86] Add support for `-mharden-sls=[none|all|return|indirect-jmp]`

2022-05-27 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers requested changes to this revision.
nickdesaulniers added a subscriber: aaron.ballman.
nickdesaulniers added a comment.
This revision now requires changes to proceed.

Let's get this rebased on top of D126511 .




Comment at: clang/docs/ClangCommandLineReference.rst:368
 
-Select straight-line speculation hardening scope
+Select straight-line speculation hardening scope (AArch64/X86 only).  
must be 'all', 'none', 'retbr'(AArch64), 'blr'(AArch64), 'return'(X86), 
'indirect-branch'(X86)
 

nickdesaulniers wrote:
> MaskRay wrote:
> > This file is generated occasionally. Please don't modify it.
> ah, it's generated from the clang/include/clang/Driver/Options.td HelpText 
> for this option. Yeah, that should be updated.
This hunk should still be removed. @aaron.ballman confirmed to me that:

> we auto-generate that
> documentation when doing a sphinx build, like we do for attributes and
> diagnostics: 
> https://github.com/llvm/llvm-project/blob/d480f968ad8b56d3ee4a6b6df5532d485b0ad01e/clang/docs/CMakeLists.txt#L129

You're addition to the HelpText in clang/include/clang/Driver/Options.td is 
sufficient.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126137

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


[libunwind] 719bf2d - [runtimes] Officially deprecate the legacy testing configuration system

2022-05-27 Thread Louis Dionne via cfe-commits

Author: Louis Dionne
Date: 2022-05-27T13:15:48-04:00
New Revision: 719bf2d9d9fdb8792b15d93364c9c6b2ddd68a36

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

LOG: [runtimes] Officially deprecate the legacy testing configuration system

Add a warning and tweak the release note to explain that the deprecation
targets libc++, libc++abi and libuwnind as well.

Also, as a fly-by, ensure that our CI runs the legacy testing configuration
for libc++, libc++abi and libunwind. This doesn't matter too much since
it's deprecated, but we might as well test it properly.

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

Added: 


Modified: 
libcxx/docs/ReleaseNotes.rst
libcxx/test/configs/legacy.cfg.in
libcxx/utils/ci/run-buildbot
libcxxabi/test/lit.site.cfg.in
libunwind/test/lit.site.cfg.in

Removed: 




diff  --git a/libcxx/docs/ReleaseNotes.rst b/libcxx/docs/ReleaseNotes.rst
index 514de5de3213d..b2bd0718001e5 100644
--- a/libcxx/docs/ReleaseNotes.rst
+++ b/libcxx/docs/ReleaseNotes.rst
@@ -148,7 +148,8 @@ Build System Changes
   its own headers.
 
 - The legacy testing configuration is now deprecated and will be removed in 
the next release. For
-  most users, this should not have any impact. However, if you are testing 
libc++ in a configuration
-  or on a platform that used to be supported by the legacy testing 
configuration and isn't supported
-  by one of the configurations in ``libcxx/test/configs``, please reach out to 
the libc++ developers
-  to get your configuration supported officially.
+  most users, this should not have any impact. However, if you are testing 
libc++, libc++abi or
+  libunwind in a configuration or on a platform that used to be supported by 
the legacy testing
+  configuration and isn't supported by one of the configurations in 
``libcxx/test/configs``,
+  ``libcxxabi/test/configs`` or ``libunwind/test/configs``, please move to one 
of those
+  configurations or define your own.

diff  --git a/libcxx/test/configs/legacy.cfg.in 
b/libcxx/test/configs/legacy.cfg.in
index 8bb5bc76aa5ee..a7ac6f8042402 100644
--- a/libcxx/test/configs/legacy.cfg.in
+++ b/libcxx/test/configs/legacy.cfg.in
@@ -62,3 +62,6 @@ import libcxx.test.config
 configuration = libcxx.test.config.Configuration(lit_config, config)
 configuration.configure()
 configuration.print_config_info()
+
+lit_config.warning("This is a legacy testing configuration which will be 
removed in LLVM 16. "
+   "Please use one of the configurations in 
libcxx/test/configs or define your own.")

diff  --git a/libcxx/utils/ci/run-buildbot b/libcxx/utils/ci/run-buildbot
index 23708e680893f..2b9f129fd2588 100755
--- a/libcxx/utils/ci/run-buildbot
+++ b/libcxx/utils/ci/run-buildbot
@@ -462,7 +462,9 @@ bootstrapping-build)
 ;;
 legacy-test-config)
 clean
-generate-cmake -DLIBCXX_TEST_CONFIG="legacy.cfg.in"
+generate-cmake -DLIBCXX_TEST_CONFIG="legacy.cfg.in" \
+   
-DLIBCXXABI_TEST_CONFIG="${MONOREPO_ROOT}/libcxxabi/test/lit.site.cfg.in" \
+   
-DLIBUNWIND_TEST_CONFIG="${MONOREPO_ROOT}/libunwind/test/lit.site.cfg.in"
 check-runtimes
 ;;
 legacy-project-build)

diff  --git a/libcxxabi/test/lit.site.cfg.in b/libcxxabi/test/lit.site.cfg.in
index ae387f55e0356..7a786a3a7691e 100644
--- a/libcxxabi/test/lit.site.cfg.in
+++ b/libcxxabi/test/lit.site.cfg.in
@@ -60,3 +60,6 @@ import libcxxabi.test.config
 configuration = libcxxabi.test.config.Configuration(lit_config, config)
 configuration.configure()
 configuration.print_config_info()
+
+lit_config.warning("This is a legacy testing configuration which will be 
removed in LLVM 16. "
+   "Please use one of the configurations in 
libcxxabi/test/configs or define your own.")

diff  --git a/libunwind/test/lit.site.cfg.in b/libunwind/test/lit.site.cfg.in
index 9fb324007a55a..31530935ce876 100644
--- a/libunwind/test/lit.site.cfg.in
+++ b/libunwind/test/lit.site.cfg.in
@@ -56,3 +56,6 @@ import libunwind.test.config
 configuration = libunwind.test.config.Configuration(lit_config, config)
 configuration.configure()
 configuration.print_config_info()
+
+lit_config.warning("This is a legacy testing configuration which will be 
removed in LLVM 16. "
+   "Please use one of the configurations in 
libunwind/test/configs or define your own.")



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


[clang] 4dc3893 - Revert "[Clang] Extend -gen-reproducer flag"

2022-05-27 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2022-05-27T17:03:32Z
New Revision: 4dc3893eeb47bef9298c34cdc993165af88721a5

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

LOG: Revert "[Clang] Extend -gen-reproducer flag"

This reverts commit 684c080108766b4f112f172fed4a49059484614d.

Added: 


Modified: 
clang/include/clang/Driver/Driver.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/tools/driver/driver.cpp

Removed: 
clang/test/Driver/emit-reproducer.c



diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 86eea9375f673..f0f294a669d98 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -276,6 +276,11 @@ class Driver {
   unsigned ProbePrecompiled : 1;
 
 public:
+  /// Force clang to emit reproducer for driver invocation. This is enabled
+  /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
+  /// or when using the -gen-reproducer driver flag.
+  unsigned GenReproducer : 1;
+
   // getFinalPhase - Determine which compilation mode we are in and record
   // which option we used to determine the final phase.
   // TODO: Much of what getFinalPhase returns are not actually true compiler
@@ -500,32 +505,6 @@ class Driver {
   StringRef AdditionalInformation = "",
   CompilationDiagnosticReport *GeneratedReport = nullptr);
 
-  enum class CommandStatus {
-Crash = 1,
-Error,
-Ok,
-  };
-
-  enum class ReproLevel {
-Off = 0,
-OnCrash = static_cast(CommandStatus::Crash),
-OnError = static_cast(CommandStatus::Error),
-Always = static_cast(CommandStatus::Ok),
-  };
-
-  bool maybeGenerateCompilationDiagnostics(
-  CommandStatus CS, ReproLevel Level, Compilation ,
-  const Command , StringRef AdditionalInformation = "",
-  CompilationDiagnosticReport *GeneratedReport = nullptr) {
-if (static_cast(CS) > static_cast(Level))
-  return false;
-// Hack to ensure that diagnostic notes get emitted.
-Diags.setLastDiagnosticIgnored(false);
-generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation,
-   GeneratedReport);
-return true;
-  }
-
   /// @}
   /// @name Helper Methods
   /// @{

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2a5e8bf27e353..e19baac5860aa 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -558,10 +558,7 @@ def arcmt_migrate_report_output : Separate<["-"], 
"arcmt-migrate-report-output">
 def arcmt_migrate_emit_arc_errors : Flag<["-"], "arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">, 
Flags<[CC1Option]>,
   MarshallingInfoFlag>;
-def gen_reproducer_eq: Joined<["-"], "gen-reproducer=">, 
Flags<[NoArgumentUnused, CoreOption]>,
-  HelpText<"Emit reproducer on (option: off, crash (default), error, always)">;
 def gen_reproducer: Flag<["-"], "gen-reproducer">, InternalDebugOpt,
-  Alias, AliasArgs<["always"]>,
   HelpText<"Auto-generates preprocessed source files and a reproduction 
script">;
 def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, 
InternalDebugOpt,
   HelpText<"Emit a compilation database fragment to the specified directory">;
@@ -1400,7 +1397,6 @@ def fexperimental_new_constant_interpreter : Flag<["-"], 
"fexperimental-new-cons
 def fconstexpr_backtrace_limit_EQ : Joined<["-"], 
"fconstexpr-backtrace-limit=">,
 Group;
 def fno_crash_diagnostics : Flag<["-"], "fno-crash-diagnostics">, 
Group, Flags<[NoArgumentUnused, CoreOption]>,
-  Alias, AliasArgs<["off"]>,
   HelpText<"Disable auto-generation of preprocessed source files and a script 
for reproduction during a clang crash">;
 def fcrash_diagnostics_dir : Joined<["-"], "fcrash-diagnostics-dir=">,
   Group, Flags<[NoArgumentUnused, CoreOption]>,

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index aaef2e1ded327..94925568aec23 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -198,7 +198,8 @@ Driver::Driver(StringRef ClangExecutable, StringRef 
TargetTriple,
   CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
   CCGenDiagnostics(false), CCPrintProcessStats(false),
   TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
-  ProbePrecompiled(true), SuppressMissingInputWarning(false) {
+  ProbePrecompiled(true), GenReproducer(false),
+  SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no VFS is specified.
   if (!this->VFS)
 this->VFS = llvm::vfs::getRealFileSystem();
@@ -1216,6 +1217,9 @@ Compilation *Driver::BuildCompilation(ArrayRef 

[PATCH] D120201: [Clang] Extend -gen-reproducer flag

2022-05-27 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests on (at least) Mac and window, see eg 
http://45.33.8.238/macm1/36198/step_7.txt (passes on my Linux bit though).

Please take a look and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120201

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


[PATCH] D126308: cmake: use llvm dir variables for clang/utils/hmaptool

2022-05-27 Thread Matheus Izvekov 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 rGbf1ab1f0eb95: cmake: use llvm dir variables for 
clang/utils/hmaptool (authored by mizvekov).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126308

Files:
  clang/utils/hmaptool/CMakeLists.txt


Index: clang/utils/hmaptool/CMakeLists.txt
===
--- clang/utils/hmaptool/CMakeLists.txt
+++ clang/utils/hmaptool/CMakeLists.txt
@@ -1,19 +1,9 @@
-set(CLANG_HMAPTOOL hmaptool)
+add_custom_command(OUTPUT "${LLVM_TOOLS_BINARY_DIR}/hmaptool"
+   COMMAND "${CMAKE_COMMAND}" -E copy 
"${CMAKE_CURRENT_SOURCE_DIR}/hmaptool" "${LLVM_TOOLS_BINARY_DIR}"
+   DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/hmaptool")
 
-add_custom_command(OUTPUT 
${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL}
-   COMMAND ${CMAKE_COMMAND} -E make_directory
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin
-   COMMAND ${CMAKE_COMMAND} -E copy
- ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL}
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/
-   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL})
-
-list(APPEND Depends 
${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL})
-install(PROGRAMS ${CLANG_HMAPTOOL}
-DESTINATION "${CMAKE_INSTALL_BINDIR}"
-COMPONENT hmaptool)
-
-add_custom_target(hmaptool ALL DEPENDS ${Depends})
+install(PROGRAMS hmaptool DESTINATION "${LLVM_UTILS_INSTALL_DIR}}" COMPONENT 
hmaptool)
+add_custom_target(hmaptool ALL DEPENDS "${LLVM_TOOLS_BINARY_DIR}/hmaptool")
 set_target_properties(hmaptool PROPERTIES FOLDER "Utils")
 
 if(NOT LLVM_ENABLE_IDE)


Index: clang/utils/hmaptool/CMakeLists.txt
===
--- clang/utils/hmaptool/CMakeLists.txt
+++ clang/utils/hmaptool/CMakeLists.txt
@@ -1,19 +1,9 @@
-set(CLANG_HMAPTOOL hmaptool)
+add_custom_command(OUTPUT "${LLVM_TOOLS_BINARY_DIR}/hmaptool"
+   COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/hmaptool" "${LLVM_TOOLS_BINARY_DIR}"
+   DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/hmaptool")
 
-add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL}
-   COMMAND ${CMAKE_COMMAND} -E make_directory
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin
-   COMMAND ${CMAKE_COMMAND} -E copy
- ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL}
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/
-   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL})
-
-list(APPEND Depends ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL})
-install(PROGRAMS ${CLANG_HMAPTOOL}
-DESTINATION "${CMAKE_INSTALL_BINDIR}"
-COMPONENT hmaptool)
-
-add_custom_target(hmaptool ALL DEPENDS ${Depends})
+install(PROGRAMS hmaptool DESTINATION "${LLVM_UTILS_INSTALL_DIR}}" COMPONENT hmaptool)
+add_custom_target(hmaptool ALL DEPENDS "${LLVM_TOOLS_BINARY_DIR}/hmaptool")
 set_target_properties(hmaptool PROPERTIES FOLDER "Utils")
 
 if(NOT LLVM_ENABLE_IDE)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bf1ab1f - cmake: use llvm dir variables for clang/utils/hmaptool

2022-05-27 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2022-05-27T18:44:58+02:00
New Revision: bf1ab1f0eb9578914343f48096229ecccd0ecf52

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

LOG: cmake: use llvm dir variables for clang/utils/hmaptool

Install hmaptool using the LLVM specific variables, so
everything goes in the right place in case llvm is included
from a top level CMakeLists.txt.

Signed-off-by: Matheus Izvekov 

Reviewed By: stephenneuendorffer

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

Added: 


Modified: 
clang/utils/hmaptool/CMakeLists.txt

Removed: 




diff  --git a/clang/utils/hmaptool/CMakeLists.txt 
b/clang/utils/hmaptool/CMakeLists.txt
index f0d9866782b8..320a24da346d 100644
--- a/clang/utils/hmaptool/CMakeLists.txt
+++ b/clang/utils/hmaptool/CMakeLists.txt
@@ -1,19 +1,9 @@
-set(CLANG_HMAPTOOL hmaptool)
+add_custom_command(OUTPUT "${LLVM_TOOLS_BINARY_DIR}/hmaptool"
+   COMMAND "${CMAKE_COMMAND}" -E copy 
"${CMAKE_CURRENT_SOURCE_DIR}/hmaptool" "${LLVM_TOOLS_BINARY_DIR}"
+   DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/hmaptool")
 
-add_custom_command(OUTPUT 
${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL}
-   COMMAND ${CMAKE_COMMAND} -E make_directory
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin
-   COMMAND ${CMAKE_COMMAND} -E copy
- ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL}
- ${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/
-   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${CLANG_HMAPTOOL})
-
-list(APPEND Depends 
${CMAKE_BINARY_DIR}/${CMAKE_CFG_INTDIR}/bin/${CLANG_HMAPTOOL})
-install(PROGRAMS ${CLANG_HMAPTOOL}
-DESTINATION "${CMAKE_INSTALL_BINDIR}"
-COMPONENT hmaptool)
-
-add_custom_target(hmaptool ALL DEPENDS ${Depends})
+install(PROGRAMS hmaptool DESTINATION "${LLVM_UTILS_INSTALL_DIR}}" COMPONENT 
hmaptool)
+add_custom_target(hmaptool ALL DEPENDS "${LLVM_TOOLS_BINARY_DIR}/hmaptool")
 set_target_properties(hmaptool PROPERTIES FOLDER "Utils")
 
 if(NOT LLVM_ENABLE_IDE)



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


[PATCH] D126481: [analyzer] Handle SymbolCast in SValBuilder

2022-05-27 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 432588.
martong marked 7 inline comments as done.
martong added a comment.

- Hoist S->getOperand, rework the test file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126481

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/svalbuilder-casts.cpp


Index: clang/test/Analysis/svalbuilder-casts.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-casts.cpp
@@ -0,0 +1,58 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+
+void clang_analyzer_eval(bool);
+
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
+
+void test(int x) {
+  // Constrain a SymSymExpr to a constant value.
+  assert(x * x == 1);
+  // It is expected to be able to get the constraint for the operand of the
+  // cast.
+  clang_analyzer_eval((char)(x * x) == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval((long)(x * x) == 1); // expected-warning{{TRUE}}
+}
+
+void test1(int x, int y) {
+  // Even if two lower bytes of `x` equal to zero, it doesn't mean that
+  // the entire `x` is zero. We are not able to know the exact value of x.
+  // It can be one of  65536 possible values like
+  // [0, 65536, -65536, 131072, -131072, ...]. To avoid huge range sets we
+  // still assume `x` in the range [INT_MIN, INT_MAX].
+  assert((short)x == 0); // Lower two bytes are set to 0.
+
+  static_assert((short)65536 == 0, "");
+  static_assert((short)-65536 == 0, "");
+  static_assert((short)131072 == 0, "");
+  static_assert((short)-131072 == 0, "");
+  clang_analyzer_eval(x == 0);   // expected-warning{{UNKNOWN}}
+
+  // These are not truncated to short as zero.
+  static_assert((short)1 != 0, "");
+  clang_analyzer_eval(x == 1);   // expected-warning{{FALSE}}
+  static_assert((short)-1 != 0, "");
+  clang_analyzer_eval(x == -1);  // expected-warning{{FALSE}}
+  static_assert((short)65537 != 0, "");
+  clang_analyzer_eval(x == 65537);   // expected-warning{{FALSE}}
+  static_assert((short)-65537 != 0, "");
+  clang_analyzer_eval(x == -65537);  // expected-warning{{FALSE}}
+  static_assert((short)131073 != 0, "");
+  clang_analyzer_eval(x == 131073);  // expected-warning{{FALSE}}
+  static_assert((short)-131073 != 0, "");
+  clang_analyzer_eval(x == -131073); // expected-warning{{FALSE}}
+
+  // Check for implicit cast.
+  short s = y;
+  assert(s == 0);
+  clang_analyzer_eval(y == 0); // expected-warning{{UNKNOWN}}
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1278,8 +1278,6 @@
   return SVB.makeSymbolVal(S);
 }
 
-// TODO: Support SymbolCast.
-
 SVal VisitSymIntExpr(const SymIntExpr *S) {
   auto I = Cached.find(S);
   if (I != Cached.end())
@@ -1349,7 +1347,17 @@
   S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
 }
 
-// FIXME add VisitSymbolCast
+SVal VisitSymbolCast(const SymbolCast *S) {
+  auto I = Cached.find(S);
+  if (I != Cached.end())
+return I->second;
+  const SymExpr *OpSym = S->getOperand();
+  SVal OpVal = getConstOrVisit(OpSym);
+  if (isUnchanged(OpSym, OpVal))
+return skip(S);
+
+  return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
+}
 
 SVal VisitUnarySymExpr(const UnarySymExpr *S) {
   auto I = Cached.find(S);


Index: clang/test/Analysis/svalbuilder-casts.cpp
===
--- /dev/null
+++ clang/test/Analysis/svalbuilder-casts.cpp
@@ -0,0 +1,58 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -verify
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+
+void clang_analyzer_eval(bool);
+
+extern void abort() __attribute__((__noreturn__));
+#define assert(expr) ((expr) ? (void)(0) : abort())
+
+void test(int x) {
+  // Constrain a SymSymExpr to a constant value.
+  assert(x * x == 1);
+  // It is 

[PATCH] D126481: [analyzer] Handle SymbolCast in SValBuilder

2022-05-27 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:1359
+  return cache(S,
+   SVB.evalCast(Op, S->getType(), S->getOperand()->getType()));
+}

steakhal wrote:
> Hoist this common subexpression.
Ok.



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:9-10
+
+// Test that the SValBuilder is able to look up and use a constraint for an
+// operand of a SymbolCast, when the operand is constrained to a const value.
+

steakhal wrote:
> Please ass a test case where these events happen in the execution path:
> 1) Have an unconstrained variable, such as a fn parameter `x`.
> 2) Produce a Symbolic cast of `x`, let's call it `s`.
> 3) Constrain `x` to some value range, let's say it must be positive.
> 4) Verify that the value of the Symbolic cast `s` is also constrained to be 
> positive.
Here is the test you'd like.
```
void testA(int x) {
  short s = x;
  assert(x > 0);
  clang_analyzer_eval(s > 0); // expected-warning{{UNKNOWN}} should be TRUE
}
```
However, this will not pass, because `x` is constrained with a **range**, and 
in the `Simplifier` we do constant folding, i.e. the range must collapse to a 
single value.
This test will pass with the child patch (created by Denys).



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:44-45
+  // which is not truncated to short as zero. Thus the branch is infisible.
+  short s = x;
+  if (!s) {
+if (x == 65537 || x == 131073)

steakhal wrote:
> It took me a while to get that the `short` variable has nothing to do with 
> the test.
> I would recommend extending the previous example with the //short variable// 
> to demonstrate that the same thing (narrowing cast) can occur by either an 
> explicit cast or some implicit casts like a variable 
> initialization/assignment.
Ok, I added a hunk for the implicit cast.



Comment at: clang/test/Analysis/svalbuilder-casts.cpp:46-49
+if (x == 65537 || x == 131073)
+  clang_analyzer_warnIfReached(); // no-warning
+else
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}

steakhal wrote:
> ```lang=C++
> clang_analyzer_eval(x == 1);   // expected-warning {{UNKNOWN}}
> clang_analyzer_eval(x == -1);  // expected-warning {{UNKNOWN}}
> clang_analyzer_eval(x == 0);   // expected-warning {{FALSE}}
> clang_analyzer_eval(x == 65537);   // expected-warning {{FALSE}}
> clang_analyzer_eval(x == -65537);  // expected-warning {{FALSE}}
> clang_analyzer_eval(x == 131073);  // expected-warning {{FALSE}}
> clang_analyzer_eval(x == -131073); // expected-warning {{FALSE}}
> ```
Thanks, I've added these cases.

> clang_analyzer_eval(x == 1);   // expected-warning {{UNKNOWN}}
> clang_analyzer_eval(x == -1);  // expected-warning {{UNKNOWN}}

Actually, `1` and `-1` does not cast to `0` as `short`, so these should be 
`FALSE`. Updated like so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126481

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


[PATCH] D119051: Extend the C++03 definition of POD to include defaulted functions

2022-05-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5596
+  DefaultedSMFArePOD = false;
+  }
+

probinson wrote:
> dblaikie wrote:
> > probinson wrote:
> > > dblaikie wrote:
> > > > probinson wrote:
> > > > > Does this mean `-fclang-abi-compat` will override the PS4/Darwin 
> > > > > special case?  I think we don't want to do that.
> > > > I don't think so - this expression will make `DefaultedSMFArePOD` false 
> > > > when it's already false due to the target not being PS4 or Darwin, 
> > > > yeah? So it'll redundantly/harmlessly set it to false.
> > > No, I mean if it *is* PS4, it will turn true into false, and that's bad.  
> > > If I'm reading this correctly.
> > Right - let's see if I can explain how I'm understanding it at least - 
> > maybe I've got some code blindness from staring at it too long.
> > 
> > If it /is/ PS4, then this code:
> > ```
> > bool DefaultedSMFArePOD = !RawTriple.isPS4() && !RawTriple.isOSDarwin();
> > ```
> > Will amount to this:
> > ```
> > bool DefaultedSMFArePOD = !true && !RawTriple.isOSDarwin();
> > ```
> > ```
> > bool DefaultedSMFArePOD = false && !RawTriple.isOSDarwin();
> > ```
> > ```
> > bool DefaultedSMFArePOD = false;
> > ```
> > So then then the code at 5595 can only reinforce that, not change it - 
> > since it only sets the value to false. So my understanding is that the 
> > `-fclang-abi-compat` flag can not have any effect on the 
> > `DefaultedSMFArePOD` behavior of PS4. And it sounds like that's what you 
> > want? So I think we're good here?
> Those little bangs can be hard to see sometimes...  Also, I think this bit
> > already false due to the target not being PS4 or Darwin, 
> confused me, should have read
> > already false due to the target being PS4 or Darwin,
> and so what the code actually does is in fact what we want.
> 
> Thanks for your patience in explaining it, and I will go make an eye doctor 
> appointment!
>  I think this bit
> > already false due to the target not being PS4 or Darwin,
> confused me, should have read
> > already false due to the target being PS4 or Darwin,

Ah, right you are, sorry about that!

> Thanks for your patience in explaining it, and I will go make an eye doctor 
> appointment!

Sure thing - certainly sometimes consider whether or not switching to the C++ 
alternative tokens would be an improvement...
```
DefaultedSMFArePOD = not RawTriple.isPS4() and not RawTriple.isOSDarwin()
```
 ;)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119051

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


[PATCH] D126289: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-27 Thread Egor Zhdan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe917801eddbe: [Clang][Driver] Fix include paths for 
`--sysroot /` on Linux (authored by egorzhdan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126289

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/bin/.keep
  
clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/crtbegin.o
  clang/test/Driver/linux-header-search.cpp

Index: clang/test/Driver/linux-header-search.cpp
===
--- clang/test/Driver/linux-header-search.cpp
+++ clang/test/Driver/linux-header-search.cpp
@@ -16,6 +16,22 @@
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/x86_64-unknown-linux-gnu/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
+
+// Test include paths when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/x86_64-unknown-linux-gnu/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/local/include"
+
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
 // RUN: -stdlib=libc++ \
@@ -56,7 +72,20 @@
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/x86_64-unknown-linux-gnu/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-//
+
+// Test Linux with libstdc++ when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libstdc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libstdcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/../../../../x86_64-unknown-linux-gnu/include"
+
 // Test Linux with both libc++ and libstdc++ installed.
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -97,9 +97,9 @@
   case llvm::Triple::mips64: {
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
   return "mips64-linux-gnu";
 break;
   }
@@ -108,14 +108,14 @@
   return "mips64el-linux-android";
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
   return "mips64el-linux-gnu";
 break;
   }
   case llvm::Triple::ppc:
-if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
   return "powerpc-linux-gnuspe";
 return "powerpc-linux-gnu";
   case 

[clang] e917801 - [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-27 Thread Egor Zhdan via cfe-commits

Author: Egor Zhdan
Date: 2022-05-27T16:51:36+01:00
New Revision: e917801eddbe1b32f1adc81391fd434557391b5e

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

LOG: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

Currently if `--sysroot /` is passed to the Clang driver, the include paths 
generated by the Clang driver will start with a double slash: 
`//usr/include/...`.
 If VFS is used to inject files into the include paths (for example, the Swift 
compiler does this), VFS will get confused and the injected files won't be 
visible.

This change makes sure that the include paths start with a single slash.

Fixes #28283.

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

Added: 
clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/bin/.keep

clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/crtbegin.o

Modified: 
clang/include/clang/Driver/ToolChain.h
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/Linux.cpp
clang/test/Driver/linux-header-search.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 0bc345a970df..f20ab164531b 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -215,6 +215,9 @@ class ToolChain {
   static void addSystemIncludes(const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 ArrayRef Paths);
+
+  static std::string concat(StringRef Path, const Twine , const Twine  = 
"",
+const Twine  = "", const Twine  = "");
   ///@}
 
 public:

diff  --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index eb3117e689d8..5130eb9b72c1 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -942,6 +942,14 @@ void ToolChain::addExternCSystemIncludeIfExists(const 
ArgList ,
   }
 }
 
+/*static*/ std::string ToolChain::concat(StringRef Path, const Twine ,
+ const Twine , const Twine ,
+ const Twine ) {
+  SmallString<128> Result(Path);
+  llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
+  return std::string(Result);
+}
+
 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
   std::error_code EC;
   int MaxVersion = 0;

diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 38280a2e3652..b3d414f2dc78 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2038,7 +2038,7 @@ void Generic_GCC::GCCInstallationDetector::init(
 if (!VFS.exists(Prefix))
   continue;
 for (StringRef Suffix : CandidateLibDirs) {
-  const std::string LibDir = Prefix + Suffix.str();
+  const std::string LibDir = concat(Prefix, Suffix);
   if (!VFS.exists(LibDir))
 continue;
   // Maybe filter out /gcc and /gcc-cross.
@@ -2104,7 +2104,7 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with
 // /usr/gcc/ as a prefix.
 
-std::string PrefixDir = SysRoot.str() + "/usr/gcc";
+std::string PrefixDir = concat(SysRoot, "/usr/gcc");
 std::error_code EC;
 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, 
EC),
LE;
@@ -2144,7 +2144,7 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   }
 
   // Fall back to /usr which is used by most non-Solaris systems.
-  Prefixes.push_back(SysRoot.str() + "/usr");
+  Prefixes.push_back(concat(SysRoot, "/usr"));
 }
 
 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples(
@@ -2667,7 +2667,7 @@ bool 
Generic_GCC::GCCInstallationDetector::ScanGentooConfigs(
 const llvm::Triple , const ArgList ,
 const SmallVectorImpl ,
 const SmallVectorImpl ) {
-  if (!D.getVFS().exists(D.SysRoot + GentooConfigDir))
+  if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir)))
 return false;
 
   for (StringRef CandidateTriple : CandidateTriples) {
@@ -2686,8 +2686,8 @@ bool 
Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig(
 const llvm::Triple , const ArgList ,
 StringRef CandidateTriple, bool NeedsBiarchSuffix) {
   llvm::ErrorOr> File =
-  D.getVFS().getBufferForFile(D.SysRoot + GentooConfigDir + "/config-" +
-  CandidateTriple.str());
+  D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir,
+ "/config-" + CandidateTriple.str()));
   if (File) {

[PATCH] D120201: [Clang] Extend -gen-reproducer flag

2022-05-27 Thread Alex Brachet via Phabricator via cfe-commits
abrachet marked an inline comment as done.
abrachet added inline comments.



Comment at: clang/test/Driver/emit-reproducer.c:1
+// RUN: rm -rf %t; mkdir %t
+

hans wrote:
> I'm not sure if lit handles that semicolon, or if it hands this over to the 
> shell, in which case it won't work on windows.
> Instead, `rm -rf %t && mkdir %t` seems common among clang tests.
> 
> Otherwise, this is a nice test file :-)
Thanks :) updated it in the commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120201

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


[PATCH] D120201: [Clang] Extend -gen-reproducer flag

2022-05-27 Thread Alex Brachet 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 rG684c08010876: [Clang] Extend -gen-reproducer flag (authored 
by abrachet).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D120201?vs=432047=432575#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120201

Files:
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/emit-reproducer.c
  clang/tools/driver/driver.cpp

Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -482,32 +482,37 @@
   }
 
   std::unique_ptr C(TheDriver.BuildCompilation(Args));
+
+  Driver::ReproLevel ReproLevel = Driver::ReproLevel::OnCrash;
+  if (Arg *A = C->getArgs().getLastArg(options::OPT_gen_reproducer_eq)) {
+auto Level = llvm::StringSwitch>(A->getValue())
+ .Case("off", Driver::ReproLevel::Off)
+ .Case("crash", Driver::ReproLevel::OnCrash)
+ .Case("error", Driver::ReproLevel::OnError)
+ .Case("always", Driver::ReproLevel::Always)
+ .Default(None);
+if (!Level) {
+  llvm::errs() << "Unknown value for " << A->getSpelling() << ": '"
+   << A->getValue() << "'\n";
+  return 1;
+}
+ReproLevel = *Level;
+  }
+  if (!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
+ReproLevel = Driver::ReproLevel::Always;
+
   int Res = 1;
   bool IsCrash = false;
+  Driver::CommandStatus CommandStatus = Driver::CommandStatus::Ok;
+  // Pretend the first command failed if ReproStatus is Always.
+  const Command *FailingCommand = &*C->getJobs().begin();
   if (C && !C->containsError()) {
 SmallVector, 4> FailingCommands;
 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
 
-// Force a crash to test the diagnostics.
-if (TheDriver.GenReproducer) {
-  Diags.Report(diag::err_drv_force_crash)
-<< !::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH");
-
-  // Pretend that every command failed.
-  FailingCommands.clear();
-  for (const auto  : C->getJobs())
-if (const Command *C = dyn_cast())
-  FailingCommands.push_back(std::make_pair(-1, C));
-
-  // Print the bug report message that would be printed if we did actually
-  // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
-  if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
-llvm::dbgs() << llvm::getBugReportMsg();
-}
-
 for (const auto  : FailingCommands) {
   int CommandRes = P.first;
-  const Command *FailingCommand = P.second;
+  FailingCommand = P.second;
   if (!Res)
 Res = CommandRes;
 
@@ -526,13 +531,21 @@
   // https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html
   IsCrash |= CommandRes > 128;
 #endif
-  if (IsCrash) {
-TheDriver.generateCompilationDiagnostics(*C, *FailingCommand);
+  CommandStatus =
+  IsCrash ? Driver::CommandStatus::Crash : Driver::CommandStatus::Error;
+  if (IsCrash)
 break;
-  }
 }
   }
 
+  // Print the bug report message that would be printed if we did actually
+  // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
+  if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
+llvm::dbgs() << llvm::getBugReportMsg();
+  if (TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
+*C, *FailingCommand))
+Res = 1;
+
   Diags.getClient()->finish();
 
   if (!UseNewCC1Process && IsCrash) {
Index: clang/test/Driver/emit-reproducer.c
===
--- /dev/null
+++ clang/test/Driver/emit-reproducer.c
@@ -0,0 +1,39 @@
+// RUN: rm -rf %t && mkdir %t
+
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -gen-reproducer=off2>&1 | FileCheck %s --check-prefix=NOT
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -fno-crash-diagnostics 2>&1 | FileCheck %s --check-prefix=NOT
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t2>&1 | FileCheck %s
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -gen-reproducer=crash  2>&1 | FileCheck %s
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -gen-reproducer=error  2>&1 | FileCheck %s
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -gen-reproducer=always 2>&1 | FileCheck %s
+// RUN: not %clang -DFATAL %s -fcrash-diagnostics-dir=%t -gen-reproducer2>&1 | FileCheck %s
+
+// RUN: not %clang -DERROR %s -fcrash-diagnostics-dir=%t -gen-reproducer=off2>&1 | FileCheck %s --check-prefix=NOT
+// 

[clang] 684c080 - [Clang] Extend -gen-reproducer flag

2022-05-27 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2022-05-27T15:49:13Z
New Revision: 684c080108766b4f112f172fed4a49059484614d

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

LOG: [Clang] Extend -gen-reproducer flag

-gen-reproducer causes crash reproduction to be emitted even
when clang didn't crash, and now can optionally take an argument
of never, on-crash (default), on-error and always.

Differential revision: https://reviews.llvm.org/D120201

Added: 
clang/test/Driver/emit-reproducer.c

Modified: 
clang/include/clang/Driver/Driver.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/Driver.cpp
clang/tools/driver/driver.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index f0f294a669d9..86eea9375f67 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -276,11 +276,6 @@ class Driver {
   unsigned ProbePrecompiled : 1;
 
 public:
-  /// Force clang to emit reproducer for driver invocation. This is enabled
-  /// indirectly by setting FORCE_CLANG_DIAGNOSTICS_CRASH environment variable
-  /// or when using the -gen-reproducer driver flag.
-  unsigned GenReproducer : 1;
-
   // getFinalPhase - Determine which compilation mode we are in and record
   // which option we used to determine the final phase.
   // TODO: Much of what getFinalPhase returns are not actually true compiler
@@ -505,6 +500,32 @@ class Driver {
   StringRef AdditionalInformation = "",
   CompilationDiagnosticReport *GeneratedReport = nullptr);
 
+  enum class CommandStatus {
+Crash = 1,
+Error,
+Ok,
+  };
+
+  enum class ReproLevel {
+Off = 0,
+OnCrash = static_cast(CommandStatus::Crash),
+OnError = static_cast(CommandStatus::Error),
+Always = static_cast(CommandStatus::Ok),
+  };
+
+  bool maybeGenerateCompilationDiagnostics(
+  CommandStatus CS, ReproLevel Level, Compilation ,
+  const Command , StringRef AdditionalInformation = "",
+  CompilationDiagnosticReport *GeneratedReport = nullptr) {
+if (static_cast(CS) > static_cast(Level))
+  return false;
+// Hack to ensure that diagnostic notes get emitted.
+Diags.setLastDiagnosticIgnored(false);
+generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation,
+   GeneratedReport);
+return true;
+  }
+
   /// @}
   /// @name Helper Methods
   /// @{

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index e19baac5860a..2a5e8bf27e35 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -558,7 +558,10 @@ def arcmt_migrate_report_output : Separate<["-"], 
"arcmt-migrate-report-output">
 def arcmt_migrate_emit_arc_errors : Flag<["-"], "arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">, 
Flags<[CC1Option]>,
   MarshallingInfoFlag>;
+def gen_reproducer_eq: Joined<["-"], "gen-reproducer=">, 
Flags<[NoArgumentUnused, CoreOption]>,
+  HelpText<"Emit reproducer on (option: off, crash (default), error, always)">;
 def gen_reproducer: Flag<["-"], "gen-reproducer">, InternalDebugOpt,
+  Alias, AliasArgs<["always"]>,
   HelpText<"Auto-generates preprocessed source files and a reproduction 
script">;
 def gen_cdb_fragment_path: Separate<["-"], "gen-cdb-fragment-path">, 
InternalDebugOpt,
   HelpText<"Emit a compilation database fragment to the specified directory">;
@@ -1397,6 +1400,7 @@ def fexperimental_new_constant_interpreter : Flag<["-"], 
"fexperimental-new-cons
 def fconstexpr_backtrace_limit_EQ : Joined<["-"], 
"fconstexpr-backtrace-limit=">,
 Group;
 def fno_crash_diagnostics : Flag<["-"], "fno-crash-diagnostics">, 
Group, Flags<[NoArgumentUnused, CoreOption]>,
+  Alias, AliasArgs<["off"]>,
   HelpText<"Disable auto-generation of preprocessed source files and a script 
for reproduction during a clang crash">;
 def fcrash_diagnostics_dir : Joined<["-"], "fcrash-diagnostics-dir=">,
   Group, Flags<[NoArgumentUnused, CoreOption]>,

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 94925568aec2..aaef2e1ded32 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -198,8 +198,7 @@ Driver::Driver(StringRef ClangExecutable, StringRef 
TargetTriple,
   CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false),
   CCGenDiagnostics(false), CCPrintProcessStats(false),
   TargetTriple(TargetTriple), Saver(Alloc), CheckInputsExist(true),
-  ProbePrecompiled(true), GenReproducer(false),
-  SuppressMissingInputWarning(false) {
+  ProbePrecompiled(true), SuppressMissingInputWarning(false) {
   // Provide a sane fallback if no 

[PATCH] D125052: [HLSL] Enable vector types for hlsl.

2022-05-27 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 432574.
python3kgae added a comment.

Add newline at end of file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125052

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/hlsl.h
  clang/lib/Headers/hlsl/hlsl_basic_types.h
  clang/test/CodeGenHLSL/basic_types.hlsl
  clang/test/Driver/hlsl_no_stdinc.hlsl

Index: clang/test/Driver/hlsl_no_stdinc.hlsl
===
--- /dev/null
+++ clang/test/Driver/hlsl_no_stdinc.hlsl
@@ -0,0 +1,12 @@
+// RUN: %clang_dxc  -Tlib_6_7 -fcgl -Fo - %s -### 2>&1 | FileCheck %s --check-prefix=STDINC
+// RUN: %clang_dxc  -Tlib_6_7 -hlsl-no-stdinc -fcgl -Fo - %s -### 2>&1 | FileCheck %s --check-prefix=NOSTDINC
+
+// RUN: %clang -cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o - %s -verify
+
+// Make sure hlsl-no-stdinc is translated into finclude-default-header.
+// STDINC:"-finclude-default-header"
+// NOSTDINC-NOT:"-finclude-default-header"
+
+// Make sure uint not work when finclude-default-header is off.
+// expected-error@+1 {{unknown type name 'uint'}}
+uint a;
Index: clang/test/CodeGenHLSL/basic_types.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/basic_types.hlsl
@@ -0,0 +1,76 @@
+// RUN: %clang_dxc  -Tlib_6_7 -fcgl -Fo - %s | FileCheck %s
+
+// FIXME: check 16bit types once enable-16bit-types is ready.
+
+// CHECK:@uint_Val = global i32 0, align 4
+// CHECK:@uint64_t_Val = global i64 0, align 8
+// CHECK:@int64_t_Val = global i64 0, align 8
+// CHECK:@int2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@int3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@int4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@uint2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@uint3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@uint4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@int64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@int64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@int64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@uint64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@float2_Val = global <2 x float> zeroinitializer, align 8
+// CHECK:@float3_Val = global <3 x float> zeroinitializer, align 16
+// CHECK:@float4_Val = global <4 x float> zeroinitializer, align 16
+// CHECK:@double2_Val = global <2 x double> zeroinitializer, align 16
+// CHECK:@double3_Val = global <3 x double> zeroinitializer, align 32
+// CHECK:@double4_Val = global <4 x double> zeroinitializer, align 32
+
+#define TYPE_DECL(T)  T T##_Val
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(uint16_t);
+TYPE_DECL(int16_t);
+#endif
+
+// unsigned 32-bit integer.
+TYPE_DECL(uint);
+
+// 64-bit integer.
+TYPE_DECL(uint64_t);
+TYPE_DECL(int64_t);
+
+// built-in vector data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(int16_t2   );
+TYPE_DECL(int16_t3   );
+TYPE_DECL(int16_t4   );
+TYPE_DECL( uint16_t2 );
+TYPE_DECL( uint16_t3 );
+TYPE_DECL( uint16_t4 );
+#endif
+
+TYPE_DECL( int2  );
+TYPE_DECL( int3  );
+TYPE_DECL( int4  );
+TYPE_DECL( uint2 );
+TYPE_DECL( uint3 );
+TYPE_DECL( uint4 );
+TYPE_DECL( int64_t2  );
+TYPE_DECL( int64_t3  );
+TYPE_DECL( int64_t4  );
+TYPE_DECL( uint64_t2 );
+TYPE_DECL( uint64_t3 );
+TYPE_DECL( uint64_t4 );
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(half2 );
+TYPE_DECL(half3 );
+TYPE_DECL(half4 );
+#endif
+
+TYPE_DECL( float2  );
+TYPE_DECL( float3  );
+TYPE_DECL( float4  );
+TYPE_DECL( double2 );
+TYPE_DECL( double3 );
+TYPE_DECL( double4 );
Index: clang/lib/Headers/hlsl/hlsl_basic_types.h
===
--- /dev/null
+++ clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -0,0 +1,64 @@
+//===- hlsl_basic_types.h - HLSL definitions for basic types --===//
+//
+// 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
+//
+//===--===//
+
+#ifndef _HLSL_HLSL_BASIC_TYPES_H_
+#define _HLSL_HLSL_BASIC_TYPES_H_
+
+// built-in scalar data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+// 16-bit integer.
+typedef unsigned short uint16_t;
+typedef short int16_t;
+#endif
+
+// unsigned 32-bit integer.
+typedef unsigned int uint;
+
+// 64-bit integer.
+typedef unsigned long uint64_t;
+typedef long 

[PATCH] D72386: [ThinLTO] pass UnrollLoops/VectorizeLoop/VectorizeSLP in CGOpts down to pass builder in ltobackend

2022-05-27 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added inline comments.
Herald added a subscriber: StephenFan.



Comment at: lld/ELF/LTO.cpp:96
 
+  c.PTO.LoopVectorization = c.OptLevel > 1;
+  c.PTO.SLPVectorization = c.OptLevel > 1;

xbolva00 wrote:
> COFF?
This came up recently on discourse: 
https://discourse.llvm.org/t/unintended-lto-configuration-differences-between-elf-and-coff/62636

This patch is a couple years old now and @wmi isn't working actively on LLVM 
anymore, maybe someone working on COFF who can test it there can send a patch 
to make this consistent?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72386

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


[PATCH] D126549: [Clang][OpenMP] Don't overload "extension" in status doc

2022-05-27 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny created this revision.
jdenny added reviewers: ABataev, jdoerfert, RaviNarayanaswamy.
jdenny added a project: OpenMP.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jdenny requested review of this revision.
Herald added a subscriber: sstefan1.
Herald added a project: clang.

In Clang's OpenMPSupport.rst, "extension" is currently overloaded to
describe both:

1. Standard OpenMP features that appear only in recent versions of the OpenMP 
spec.
2. Non-standard features supported by Clang.  This usage appears in the final 
table on the page.

Last fall, we discussed this issue in the OpenMP in LLVM call and 
agreed it should be corrected.  This patch takes the simple approach
of dropping the word "extension" for all occurrences of the first
usage.  The result seems to read well.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126549

Files:
  clang/docs/OpenMPSupport.rst

Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -117,19 +117,19 @@
 +--+--+--+---+
 |Category  | Feature  | Status   | Reviews   |
 +==+==+==+===+
-| loop extension   | support != in the canonical loop form| :good:`done` | D54441|
+| loop | support != in the canonical loop form| :good:`done` | D54441|
 +--+--+--+---+
-| loop extension   | #pragma omp loop (directive) | :part:`worked on`|   |
+| loop | #pragma omp loop (directive) | :part:`worked on`|   |
 +--+--+--+---+
-| loop extension   | collapse imperfectly nested loop | :good:`done` |   |
+| loop | collapse imperfectly nested loop | :good:`done` |   |
 +--+--+--+---+
-| loop extension   | collapse non-rectangular nested loop | :good:`done` |   |
+| loop | collapse non-rectangular nested loop | :good:`done` |   |
 +--+--+--+---+
-| loop extension   | C++ range-base for loop  | :good:`done` |   |
+| loop | C++ range-base for loop  | :good:`done` |   |
 +--+--+--+---+
-| loop extension   | clause: if for SIMD directives   | :good:`done` |   |
+| loop | clause: if for SIMD directives   | :good:`done` |   

[PATCH] D126289: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-27 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 432568.
egorzhdan marked an inline comment as done.
egorzhdan added a comment.

Rebase & fix formatting


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126289

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/bin/.keep
  
clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/crtbegin.o
  clang/test/Driver/linux-header-search.cpp

Index: clang/test/Driver/linux-header-search.cpp
===
--- clang/test/Driver/linux-header-search.cpp
+++ clang/test/Driver/linux-header-search.cpp
@@ -16,6 +16,22 @@
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/x86_64-unknown-linux-gnu/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
+
+// Test include paths when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/x86_64-unknown-linux-gnu/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/local/include"
+
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
 // RUN: -stdlib=libc++ \
@@ -56,7 +72,20 @@
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/x86_64-unknown-linux-gnu/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-//
+
+// Test Linux with libstdc++ when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libstdc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libstdcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/../../../../x86_64-unknown-linux-gnu/include"
+
 // Test Linux with both libc++ and libstdc++ installed.
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -97,9 +97,9 @@
   case llvm::Triple::mips64: {
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
   return "mips64-linux-gnu";
 break;
   }
@@ -108,14 +108,14 @@
   return "mips64el-linux-android";
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
   return "mips64el-linux-gnu";
 break;
   }
   case llvm::Triple::ppc:
-if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
   return "powerpc-linux-gnuspe";
 return "powerpc-linux-gnu";
   case llvm::Triple::ppcle:
@@ -269,13 +269,13 @@
   // 

[PATCH] D126547: [OpenACC][OpenMP] Document atomic-in-teams extension

2022-05-27 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny created this revision.
jdenny added reviewers: ABataev, jdoerfert, clementval.
jdenny added projects: OpenMP, OpenACC.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jdenny requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

That is, put D126323  in the status doc and 
explain its relationship to
OpenACC support.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126547

Files:
  clang/docs/OpenMPSupport.rst
  openmp/docs/openacc/OpenMPExtensions.rst


Index: openmp/docs/openacc/OpenMPExtensions.rst
===
--- openmp/docs/openacc/OpenMPExtensions.rst
+++ openmp/docs/openacc/OpenMPExtensions.rst
@@ -137,3 +137,36 @@
 the runtime level.  That is, OpenACC's dynamic reference count is
 OpenMP's dynamic reference count, and OpenACC's structured reference
 count is our OpenMP hold reference count extension.
+
+.. _atomicWithinTeams:
+
+``atomic`` Strictly Nested Within ``teams``
+---
+
+Example
+^^^
+
+OpenMP 5.2, sec. 10.2 "teams Construct", p. 232, L9-12 restricts what
+regions can be strictly nested within a ``teams`` region.  As an
+extension, Clang relaxes that restriction in the case of the
+``atomic`` construct so that, for example, the following case is
+permitted:
+
+.. code-block:: c++
+
+  #pragma omp target teams map(tofrom:x)
+  #pragma omp atomic update
+  x++;
+
+Relationship with OpenACC
+^
+
+This extension is important when translating OpenACC to OpenMP because
+OpenACC does not have the same restriction for its corresponding
+constructs.  For example, the following is conforming OpenACC:
+
+.. code-block:: c++
+
+  #pragma acc parallel copy(x)
+  #pragma acc atomic update
+  x++;
Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -369,9 +369,12 @@
 considered for standardization.  Please contact *openmp-dev* at
 *lists.llvm.org* to provide feedback.
 
-+--+---+--++
-|Category  | Feature   
| Status   | Reviews
|
-+==+===+==++
-| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, D106510   
|
-|  | 
`_  | 
 ||
-+--+---+--++
++--+---+--++
+|Category  | Feature   
| Status   | Reviews
|
++==+===+==++
+| atomic extension | `'atomic' strictly nested within 'teams'  
| :good:`prototyped`   | D126323
|
+|  | 
`_
  |  |  
  |
++--+---+--++
+| device extension | `'ompx_hold' map type modifier
| :good:`prototyped`   | D106509, 
D106510   |
+|  | 
`_
  |  |  
  |

[PATCH] D124751: [HLSL] Support -E option for HLSL.

2022-05-27 Thread Xiang Li via Phabricator via cfe-commits
python3kgae marked 3 inline comments as done.
python3kgae added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:11721
+  Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads) << "Compute";
+  FD->setInvalidDecl();
+}

bruno wrote:
> Since this is both checking and invalidating a decl, perhaps it should return 
> a bool (maybe some asserts in the default case?) and be renamed 
> `CheckAndInvalidateHLSLEntryPoint`?
The name is following CheckMain and CheckMSVCRTEntryPoint which also checking 
and invalidating.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124751

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


[PATCH] D124751: [HLSL] Support -E option for HLSL.

2022-05-27 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 432563.
python3kgae added a comment.

Add hlsl-entry for cc1 option.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124751

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TargetOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/HLSL.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Driver/dxc_E.hlsl
  clang/test/Driver/hlsl-entry.cpp
  clang/test/SemaHLSL/entry.hlsl
  clang/test/SemaHLSL/prohibit_pointer.hlsl
  clang/test/SemaHLSL/shader_type_attr.hlsl

Index: clang/test/SemaHLSL/shader_type_attr.hlsl
===
--- clang/test/SemaHLSL/shader_type_attr.hlsl
+++ clang/test/SemaHLSL/shader_type_attr.hlsl
@@ -53,10 +53,11 @@
 [shader(1)]
 // expected-warning@+1 {{'shader' attribute argument not supported: cs}}
 [shader("cs")]
-
+// expected-warning@+1 {{'shader' attribute argument not supported: library}}
+[shader("library")]
 #endif // END of FAIL
 
-// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
+// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
 [shader("compute")]
 int entry() {
   return 1;
@@ -64,11 +65,11 @@
 
 // Because these two attributes match, they should both appear in the AST
 [shader("compute")]
-// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
+// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
 int secondFn();
 
 [shader("compute")]
-// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
+// CHECK:HLSLShaderAttr 0x{{[0-9a-fA-F]+}}  Compute
 int secondFn() {
   return 1;
 }
Index: clang/test/SemaHLSL/prohibit_pointer.hlsl
===
--- clang/test/SemaHLSL/prohibit_pointer.hlsl
+++ clang/test/SemaHLSL/prohibit_pointer.hlsl
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -o - -fsyntax-only %s -verify
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library -x hlsl -o - -fsyntax-only %s -verify
 
 // expected-error@+1 {{pointers are unsupported in HLSL}}
 typedef int (*fn_int)(int);
Index: clang/test/SemaHLSL/entry.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/entry.hlsl
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-compute -x hlsl -hlsl-entry foo -DWITH_NUM_THREADS -ast-dump -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-compute -x hlsl -hlsl-entry foo  -o - %s  -verify
+
+
+// Make sure add HLSLShaderAttr along with HLSLNumThreadsAttr.
+// CHECK:HLSLNumThreadsAttr 0x{{.*}}  1 1 1
+// CHECK:HLSLShaderAttr 0x{{.*}}  Compute
+
+#ifdef WITH_NUM_THREADS
+[numthreads(1,1,1)]
+#endif
+// expected-error@+1 {{missing numthreads attribute for compute shader entry}}
+void foo() {
+
+}
Index: clang/test/Driver/hlsl-entry.cpp
===
--- /dev/null
+++ clang/test/Driver/hlsl-entry.cpp
@@ -0,0 +1,3 @@
+// RUN:not %clang -cc1 -triple dxil-pc-shadermodel6.3-compute -x c++ -hlsl-entry foo  %s  2>&1 | FileCheck %s --check-prefix=NOTHLSL
+
+// NOTHLSL:invalid argument '-hlsl-entry' not allowed with 'C++'
Index: clang/test/Driver/dxc_E.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_E.hlsl
@@ -0,0 +1,4 @@
+// RUN: %clang_dxc -Efoo foo.hlsl -### %s 2>&1 | FileCheck %s
+
+// Make sure E option flag which translated into "-hlsl-entry".
+// CHECK:"-hlsl-entry" "foo"
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -6947,7 +6947,11 @@
 return;
 
   HLSLShaderAttr::ShaderType ShaderType;
-  if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType)) {
+  if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType) ||
+  // Library is added to help convert HLSLShaderAttr::ShaderType to
+  // llvm::Triple::EnviromentType. It is not a legal
+  // HLSLShaderAttr::ShaderType.
+  ShaderType == HLSLShaderAttr::Library) {
 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
 << AL << Str << ArgLoc;
 return;
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -9867,6 +9867,28 @@
 }
   }
 
+  if (getLangOpts().HLSL) {
+auto  = getASTContext().getTargetInfo();
+if (!NewFD->isInvalidDecl() &&
+// Skip operator overload which not identifier.
+Name.isIdentifier() &&
+NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
+// 

[PATCH] D126534: [analyzer] Deadstore static analysis: Fix false positive on C++17 assignments

2022-05-27 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource marked an inline comment as done.
frederic-tingaud-sonarsource added a comment.

Thanks for looking at the PR!

In D126534#3542402 , @steakhal wrote:

> You also mentioned this copy elision, but I don't see anywhere checks for the 
> standard version in code. I would expect that your change should apply only 
> to C++17 and above.

The false-positive due to copy elision in C++17 is the main pain point that 
this patch fixes, which is why I mention it in the title, but it does in fact 
also solve other cases for all C++ versions if there are parentheses or casts 
involved.


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

https://reviews.llvm.org/D126534

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


[PATCH] D126534: [analyzer] Deadstore static analysis: Fix false positive on C++17 assignments

2022-05-27 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource updated this revision to Diff 432558.
frederic-tingaud-sonarsource added a comment.

Document tests better


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

https://reviews.llvm.org/D126534

Files:
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -11,6 +11,10 @@
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11\
 // RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
 // RUN:  -verify=non-nested,nested %s
+//
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++17\
+// RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
+// RUN:  -verify=non-nested,nested %s
 
 //===--===//
 // Basic dead store checking (but in C++ mode).
@@ -52,6 +56,18 @@
   return x;
 }
 
+class TestConstructor {
+public:
+  TestConstructor(int );
+};
+void copy(int x) {
+  // All these calls might have side effects in the opaque constructor
+  TestConstructor tc1 = x;// no-warning potential side effects
+  TestConstructor tc2 = TestConstructor(x);   // no-warning potential side effects
+  TestConstructor tc3 = (TestConstructor(x)); // no-warning potential side effects
+  TestConstructor tc4 = (TestConstructor)(x); // no-warning potential side effects
+}
+
 //===--===//
 // Dead store checking involving CXXTemporaryExprs
 //===--===//
Index: clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
===
--- clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
+++ clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
@@ -432,7 +432,7 @@

 
  line139
- col13
+ col35
  file0
 
 
@@ -500,7 +500,7 @@

 
  line144
- col13
+ col33
  file0
 
 
@@ -568,7 +568,7 @@

 
  line145
- col13
+ col26
  file0
 
 
@@ -636,7 +636,7 @@

 
  line146
- col13
+ col33
  file0
 
 
@@ -1046,7 +1046,7 @@

 
  line150
- col19
+ col48
  file0
 
 
@@ -1114,7 +1114,7 @@

 
  line151
- col21
+ col52
  file0
 
 
@@ -1182,7 +1182,7 @@

 
  line152
- col19
+ col39
  file0
 
 
@@ -1250,7 +1250,7 @@

 
  line153
- col21
+ col43
  file0
 
 
Index: clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
@@ -103,8 +103,8 @@
 static const Expr *
 LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
   while (Ex) {
-const BinaryOperator *BO =
-  dyn_cast(Ex->IgnoreParenCasts());
+Ex = Ex->IgnoreParenCasts();
+const BinaryOperator *BO = dyn_cast(Ex);
 if (!BO)
   break;
 BinaryOperatorKind Op = BO->getOpcode();
@@ -331,8 +331,7 @@
   // Special case: check for assigning null to a pointer.
   //  This is a common form of defensive programming.
   const Expr *RHS =
-LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
-  RHS = RHS->IgnoreParenCasts();
+  LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
 
   QualType T = VD->getType();
   if (T.isVolatileQualified())
@@ -415,8 +414,7 @@
   if (isConstant(E))
 return;
 
-  if (const DeclRefExpr *DRE =
-  dyn_cast(E->IgnoreParenCasts()))
+  if (const DeclRefExpr *DRE = dyn_cast(E))
 if (const VarDecl *VD = dyn_cast(DRE->getDecl())) {
   // Special case: check for initialization from constant
   //  variables.
@@ -450,8 +448,9 @@
   bool isConstant(const InitListExpr *Candidate) const {
 // We consider init list to be constant if each member of the list can be
 // interpreted as constant.
-return llvm::all_of(Candidate->inits(),
-[this](const Expr *Init) { return isConstant(Init); });
+return 

[PATCH] D126534: [analyzer] Deadstore static analysis: Fix false positive on C++17 assignments

2022-05-27 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I haven't checked the implementation; the Deadstores checker was always a 
nemesis for me.

Off the top of my head, I think in the analyzer we have the 
`elide-constructors=true/false` analyzer config option, which quotes:

> Whether elidable C++ copy-constructors and move-constructors should be 
> actually elided during analysis. Both behaviors are allowed by the C++ 
> standard, and the analyzer, like CodeGen, defaults to eliding. Starting with 
> C++17 some elisions become mandatory, and in these cases the option will be 
> ignored.

You also mentioned this copy elision, but I don't see anywhere checks for the 
standard version in code. I would expect that your change should apply only to 
C++17 and above.




Comment at: clang/test/Analysis/dead-stores.cpp:63-68
+void copy(int x) {
+  TestConstructor tc1 = x;// no-warning
+  TestConstructor tc2 = TestConstructor(x);   // no-warning
+  TestConstructor tc3 = (TestConstructor(x)); // no-warning
+  TestConstructor tc4 = (TestConstructor)(x); // no-warning
+}

So we don't warn for these since the opaque ctor call might introduce some 
side-effects.
Please note this after the `no-warning` tag.


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

https://reviews.llvm.org/D126534

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


[PATCH] D126540: PowerPC] Emit warning for incompatible vector types that are currently diagnosed with -fno-lax-vector-conversions

2022-05-27 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo updated this revision to Diff 432553.
maryammo added a comment.

NFC update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126540

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Parser/cxx-altivec.cpp

Index: clang/test/Parser/cxx-altivec.cpp
===
--- clang/test/Parser/cxx-altivec.cpp
+++ clang/test/Parser/cxx-altivec.cpp
@@ -1,10 +1,10 @@
-// RUN: %clang_cc1 -triple=powerpc-apple-darwin8 -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature +altivec -target-feature +vsx -fsyntax-only -verify=expected,nonaix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature +vsx -target-cpu pwr7 -fsyntax-only -verify=expected,nonaix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature -vsx -target-cpu pwr7 -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc-apple-darwin8 -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -target-feature +vsx -fsyntax-only -verify=expected,nonaix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +vsx -target-cpu pwr7 -fsyntax-only -verify=expected,nonaix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature -vsx -target-cpu pwr7 -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
 #include 
 
 __vector char vv_c;
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -1617,8 +1617,9 @@
 ///
 /// \param ICK Will be set to the vector conversion kind, if this is a vector
 /// conversion.
-static bool IsVectorConversion(Sema , QualType FromType,
-   QualType ToType, ImplicitConversionKind ) {
+static bool IsVectorConversion(Sema , QualType FromType, QualType ToType,
+   ImplicitConversionKind , Expr *From,
+   bool InOverloadResolution) {
   // We need at least one of these types to be a vector type to have a vector
   // conversion.
   if (!ToType->isVectorType() && !FromType->isVectorType())
@@ -1660,6 +1661,14 @@
 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
 (S.isLaxVectorConversion(FromType, ToType) &&
  !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
+  if (!InOverloadResolution &&
+  FromType->castAs()->getVectorKind() ==
+  VectorType::AltiVecVector &&
+  ToType->castAs()->getVectorKind() ==
+  VectorType::AltiVecVector) {
+S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
+<< FromType << ToType;
+  }
   ICK = ICK_Vector_Conversion;
   return true;
 }
@@ -1908,7 +1917,8 @@
  InOverloadResolution, FromType)) {
 // Pointer to member conversions (4.11).
 SCS.Second = ICK_Pointer_Member;
-  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
+  } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
+InOverloadResolution)) {
 SCS.Second = SecondICK;
 FromType = ToType.getUnqualifiedType();
   } else if (!S.getLangOpts().CPlusPlus &&
@@ -13014,6 +13024,7 @@
   // This shouldn't cause an infinite loop because we're giving it
   // an expression with viable lookup results, which should never
   // end up here.
+  //
   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
MultiExprArg(Args.data(), Args.size()),
 

[PATCH] D126534: [analyzer] Deadstore static analysis: Fix false positive on C++17 assignments

2022-05-27 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource updated this revision to Diff 432552.
frederic-tingaud-sonarsource added a comment.

Fix formatting


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

https://reviews.llvm.org/D126534

Files:
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -11,6 +11,10 @@
 // RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++11\
 // RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
 // RUN:  -verify=non-nested,nested %s
+//
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++17\
+// RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
+// RUN:  -verify=non-nested,nested %s
 
 //===--===//
 // Basic dead store checking (but in C++ mode).
@@ -52,6 +56,17 @@
   return x;
 }
 
+class TestConstructor {
+public:
+  TestConstructor(int );
+};
+void copy(int x) {
+  TestConstructor tc1 = x;// no-warning
+  TestConstructor tc2 = TestConstructor(x);   // no-warning
+  TestConstructor tc3 = (TestConstructor(x)); // no-warning
+  TestConstructor tc4 = (TestConstructor)(x); // no-warning
+}
+
 //===--===//
 // Dead store checking involving CXXTemporaryExprs
 //===--===//
Index: clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
===
--- clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
+++ clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
@@ -432,7 +432,7 @@

 
  line139
- col13
+ col35
  file0
 
 
@@ -500,7 +500,7 @@

 
  line144
- col13
+ col33
  file0
 
 
@@ -568,7 +568,7 @@

 
  line145
- col13
+ col26
  file0
 
 
@@ -636,7 +636,7 @@

 
  line146
- col13
+ col33
  file0
 
 
@@ -1046,7 +1046,7 @@

 
  line150
- col19
+ col48
  file0
 
 
@@ -1114,7 +1114,7 @@

 
  line151
- col21
+ col52
  file0
 
 
@@ -1182,7 +1182,7 @@

 
  line152
- col19
+ col39
  file0
 
 
@@ -1250,7 +1250,7 @@

 
  line153
- col21
+ col43
  file0
 
 
Index: clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
@@ -103,8 +103,8 @@
 static const Expr *
 LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
   while (Ex) {
-const BinaryOperator *BO =
-  dyn_cast(Ex->IgnoreParenCasts());
+Ex = Ex->IgnoreParenCasts();
+const BinaryOperator *BO = dyn_cast(Ex);
 if (!BO)
   break;
 BinaryOperatorKind Op = BO->getOpcode();
@@ -331,8 +331,7 @@
   // Special case: check for assigning null to a pointer.
   //  This is a common form of defensive programming.
   const Expr *RHS =
-LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
-  RHS = RHS->IgnoreParenCasts();
+  LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
 
   QualType T = VD->getType();
   if (T.isVolatileQualified())
@@ -415,8 +414,7 @@
   if (isConstant(E))
 return;
 
-  if (const DeclRefExpr *DRE =
-  dyn_cast(E->IgnoreParenCasts()))
+  if (const DeclRefExpr *DRE = dyn_cast(E))
 if (const VarDecl *VD = dyn_cast(DRE->getDecl())) {
   // Special case: check for initialization from constant
   //  variables.
@@ -450,8 +448,9 @@
   bool isConstant(const InitListExpr *Candidate) const {
 // We consider init list to be constant if each member of the list can be
 // interpreted as constant.
-return llvm::all_of(Candidate->inits(),
-[this](const Expr *Init) { return isConstant(Init); });
+return llvm::all_of(Candidate->inits(), [this](const Expr *Init) {
+  return isConstant(Init->IgnoreParenCasts());
+});
   }
 
   /// Return true if the given expression can be 

[PATCH] D126198: [analyzer][NFCi] Annotate major nonnull returning functions

2022-05-27 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

A sanitizer buildbot caught a wrong annotation, fixed by 
e651ed8621c3719937517ddb0b0815b18ec888e4 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[clang] e651ed8 - [analyzer] Fix wrong annotation of LazyCompoundVal::getStore

2022-05-27 Thread Balazs Benics via cfe-commits

Author: Balazs Benics
Date: 2022-05-27T16:07:33+02:00
New Revision: e651ed8621c3719937517ddb0b0815b18ec888e4

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

LOG: [analyzer] Fix wrong annotation of LazyCompoundVal::getStore

The build bot https://lab.llvm.org/buildbot#builders/5/builds/24183
uncovered a wrong nonnull annotation intoduced by D126198.

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index ec7f05333f7b..7c5f23b6d466 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -421,7 +421,7 @@ class LazyCompoundVal : public NonLoc {
 return static_cast(Data);
   }
 
-  LLVM_ATTRIBUTE_RETURNS_NONNULL
+  /// It might return null.
   const void *getStore() const;
 
   LLVM_ATTRIBUTE_RETURNS_NONNULL



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


[PATCH] D126540: PowerPC] Emit warning for incompatible vector types that are currently diagnosed with -fno-lax-vector-conversions

2022-05-27 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo created this revision.
Herald added subscribers: shchenz, nemanjai.
Herald added a project: All.
maryammo requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch is the last prerequisite to switch the default behaviour to 
-fno-lax-vector-conversions in the future.
The first path ;D124093 ; fixed the altivec 
implicit castings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126540

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Parser/cxx-altivec.cpp

Index: clang/test/Parser/cxx-altivec.cpp
===
--- clang/test/Parser/cxx-altivec.cpp
+++ clang/test/Parser/cxx-altivec.cpp
@@ -1,10 +1,10 @@
-// RUN: %clang_cc1 -triple=powerpc-apple-darwin8 -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature +altivec -target-feature +vsx -fsyntax-only -verify=expected,nonaix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature +vsx -target-cpu pwr7 -fsyntax-only -verify=expected,nonaix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature -vsx -target-cpu pwr7 -fsyntax-only -verify=expected,novsx -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
-// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc-apple-darwin8 -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -target-feature +vsx -fsyntax-only -verify=expected,nonaix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature +vsx -target-cpu pwr7 -fsyntax-only -verify=expected,nonaix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -Wno-deprecate-lax-vec-conv-all -target-feature -vsx -target-cpu pwr7 -fsyntax-only -verify=expected,novsx -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -Wno-deprecate-lax-vec-conv-all -target-feature +altivec -fsyntax-only -verify=expected,aix -std=c++11 %s
 #include 
 
 __vector char vv_c;
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -1617,8 +1617,9 @@
 ///
 /// \param ICK Will be set to the vector conversion kind, if this is a vector
 /// conversion.
-static bool IsVectorConversion(Sema , QualType FromType,
-   QualType ToType, ImplicitConversionKind ) {
+static bool IsVectorConversion(Sema , QualType FromType, QualType ToType,
+   ImplicitConversionKind , Expr *From,
+   bool InOverloadResolution) {
   // We need at least one of these types to be a vector type to have a vector
   // conversion.
   if (!ToType->isVectorType() && !FromType->isVectorType())
@@ -1660,6 +1661,14 @@
 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
 (S.isLaxVectorConversion(FromType, ToType) &&
  !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
+  if (!InOverloadResolution &&
+  FromType->castAs()->getVectorKind() ==
+  VectorType::AltiVecVector &&
+  ToType->castAs()->getVectorKind() ==
+  VectorType::AltiVecVector) {
+S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
+<< FromType << ToType;
+  }
   ICK = ICK_Vector_Conversion;
   return true;
 }
@@ -1908,7 +1917,8 @@
  InOverloadResolution, FromType)) {
 // Pointer to member conversions (4.11).
 SCS.Second = ICK_Pointer_Member;
-  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
+  } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
+InOverloadResolution)) {
 SCS.Second = SecondICK;
 FromType = ToType.getUnqualifiedType();
   } else if (!S.getLangOpts().CPlusPlus &&
@@ -13014,6 +13024,7 @@
   // This shouldn't cause an infinite loop 

[PATCH] D126419: [clang][dataflow] Improve handling of constructor initializers.

2022-05-27 Thread Yitzhak Mandelbaum 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 rG3682e22ef404: [clang][dataflow] Improve handling of 
constructor initializers. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126419

Files:
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1296,6 +1296,49 @@
   });
 }
 
+TEST_F(TransferTest, BaseClassInitializer) {
+  using ast_matchers::cxxConstructorDecl;
+  using ast_matchers::hasName;
+  using ast_matchers::ofClass;
+
+  std::string Code = R"(
+class A {
+public:
+  A(int I) : Bar(I) {}
+  int Bar;
+};
+
+class B : public A {
+public:
+  B(int I) : A(I) {
+(void)0;
+// [[p]]
+  }
+};
+  )";
+  ASSERT_THAT_ERROR(
+  test::checkDataflow(
+  Code, cxxConstructorDecl(ofClass(hasName("B"))),
+  [](ASTContext , Environment &) {
+return NoopAnalysis(C, /*ApplyBuiltinTransfer=*/true);
+  },
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+// Regression test to verify that base-class initializers do not
+// trigger an assertion. If we add support for such initializers in
+// the future, we can expand this test to check more specific
+// properties.
+EXPECT_THAT(Results, ElementsAre(Pair("p", _)));
+  },
+  {"-fsyntax-only", "-fno-delayed-template-parsing",
+   "-std=" + std::string(LangStandard::getLangStandardForKind(
+ LangStandard::lang_cxx17)
+ .getName())}),
+  llvm::Succeeded());
+}
+
 TEST_F(TransferTest, ReferenceMember) {
   std::string Code = R"(
 struct A {
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -257,6 +257,11 @@
   const CXXCtorInitializer *Initializer = CfgInit.getInitializer();
   assert(Initializer != nullptr);
 
+  const FieldDecl *Member = Initializer->getMember();
+  if (Member == nullptr)
+// Not a field initializer.
+return;
+
   auto *InitStmt = Initializer->getInit();
   assert(InitStmt != nullptr);
 
@@ -269,9 +274,6 @@
   if (InitStmtVal == nullptr)
 return;
 
-  const FieldDecl *Member = Initializer->getMember();
-  assert(Member != nullptr);
-
   if (Member->getType()->isReferenceType()) {
 auto  = ThisLoc.getChild(*Member);
 State.Env.setValue(MemberLoc,


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1296,6 +1296,49 @@
   });
 }
 
+TEST_F(TransferTest, BaseClassInitializer) {
+  using ast_matchers::cxxConstructorDecl;
+  using ast_matchers::hasName;
+  using ast_matchers::ofClass;
+
+  std::string Code = R"(
+class A {
+public:
+  A(int I) : Bar(I) {}
+  int Bar;
+};
+
+class B : public A {
+public:
+  B(int I) : A(I) {
+(void)0;
+// [[p]]
+  }
+};
+  )";
+  ASSERT_THAT_ERROR(
+  test::checkDataflow(
+  Code, cxxConstructorDecl(ofClass(hasName("B"))),
+  [](ASTContext , Environment &) {
+return NoopAnalysis(C, /*ApplyBuiltinTransfer=*/true);
+  },
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+// Regression test to verify that base-class initializers do not
+// trigger an assertion. If we add support for such initializers in
+// the future, we can expand this test to check more specific
+// properties.
+EXPECT_THAT(Results, ElementsAre(Pair("p", _)));
+  },
+  {"-fsyntax-only", "-fno-delayed-template-parsing",
+   "-std=" + std::string(LangStandard::getLangStandardForKind(
+ LangStandard::lang_cxx17)
+ .getName())}),
+  llvm::Succeeded());
+}
+
 TEST_F(TransferTest, ReferenceMember) {
   std::string Code = R"(
 struct A {
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

[clang] 3682e22 - [clang][dataflow] Improve handling of constructor initializers.

2022-05-27 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2022-05-27T13:54:11Z
New Revision: 3682e22ef404e1314ee1eab9daf6de99dc9ea8ee

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

LOG: [clang][dataflow] Improve handling of constructor initializers.

Currently, we assert that `CXXCtorInitializer`s are field initializers. Replace
the assertion with an early return. Otherwise, we crash every time we process a
constructor with a non-field (e.g. base class) initializer.

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index ee1723dcd8cc..8a5d5ca386af 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -257,6 +257,11 @@ static void transferCFGInitializer(const CFGInitializer 
,
   const CXXCtorInitializer *Initializer = CfgInit.getInitializer();
   assert(Initializer != nullptr);
 
+  const FieldDecl *Member = Initializer->getMember();
+  if (Member == nullptr)
+// Not a field initializer.
+return;
+
   auto *InitStmt = Initializer->getInit();
   assert(InitStmt != nullptr);
 
@@ -269,9 +274,6 @@ static void transferCFGInitializer(const CFGInitializer 
,
   if (InitStmtVal == nullptr)
 return;
 
-  const FieldDecl *Member = Initializer->getMember();
-  assert(Member != nullptr);
-
   if (Member->getType()->isReferenceType()) {
 auto  = ThisLoc.getChild(*Member);
 State.Env.setValue(MemberLoc,

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index dbf59bf69556..efea7797b45f 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1296,6 +1296,49 @@ TEST_F(TransferTest, ClassMember) {
   });
 }
 
+TEST_F(TransferTest, BaseClassInitializer) {
+  using ast_matchers::cxxConstructorDecl;
+  using ast_matchers::hasName;
+  using ast_matchers::ofClass;
+
+  std::string Code = R"(
+class A {
+public:
+  A(int I) : Bar(I) {}
+  int Bar;
+};
+
+class B : public A {
+public:
+  B(int I) : A(I) {
+(void)0;
+// [[p]]
+  }
+};
+  )";
+  ASSERT_THAT_ERROR(
+  test::checkDataflow(
+  Code, cxxConstructorDecl(ofClass(hasName("B"))),
+  [](ASTContext , Environment &) {
+return NoopAnalysis(C, /*ApplyBuiltinTransfer=*/true);
+  },
+  [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext ) {
+// Regression test to verify that base-class initializers do not
+// trigger an assertion. If we add support for such initializers in
+// the future, we can expand this test to check more specific
+// properties.
+EXPECT_THAT(Results, ElementsAre(Pair("p", _)));
+  },
+  {"-fsyntax-only", "-fno-delayed-template-parsing",
+   "-std=" + std::string(LangStandard::getLangStandardForKind(
+ LangStandard::lang_cxx17)
+ .getName())}),
+  llvm::Succeeded());
+}
+
 TEST_F(TransferTest, ReferenceMember) {
   std::string Code = R"(
 struct A {



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


[clang] 67136d0 - [clang][dataflow] Remove private-field filtering from `StorageLocation` creation.

2022-05-27 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2022-05-27T13:39:53Z
New Revision: 67136d0e8fb57251dece4be0907414fdbe081f7a

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

LOG: [clang][dataflow] Remove private-field filtering from `StorageLocation` 
creation.

The API for `AggregateStorageLocation` does not allow for missing fields (it 
asserts). Therefore, it is incorrect to filter out any fields at 
location-creation time which may be accessed by the code. Currently, we limit 
filtering to private, base-calss fields on the assumption that those can never 
be accessed. However, `friend` declarations can invalidate that assumption, 
thereby breaking our invariants.

This patch removes said field filtering to avoid violating the invariant of "no 
missing fields" for `AggregateStorageLocation`.

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index fe573bbf9f379..13fef0d4286cf 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -148,39 +148,26 @@ static void initGlobalVars(const Stmt , Environment 
) {
   }
 }
 
+// FIXME: Does not precisely handle non-virtual diamond inheritance. A single
+// field decl will be modeled for all instances of the inherited field.
 static void
-getFieldsFromClassHierarchy(QualType Type, bool IgnorePrivateFields,
+getFieldsFromClassHierarchy(QualType Type,
 llvm::DenseSet ) {
   if (Type->isIncompleteType() || Type->isDependentType() ||
   !Type->isRecordType())
 return;
 
-  for (const FieldDecl *Field : Type->getAsRecordDecl()->fields()) {
-if (IgnorePrivateFields &&
-(Field->getAccess() == AS_private ||
- (Field->getAccess() == AS_none && 
Type->getAsRecordDecl()->isClass(
-  continue;
+  for (const FieldDecl *Field : Type->getAsRecordDecl()->fields())
 Fields.insert(Field);
-  }
-  if (auto *CXXRecord = Type->getAsCXXRecordDecl()) {
-for (const CXXBaseSpecifier  : CXXRecord->bases()) {
-  // Ignore private fields (including default access in C++ classes) in
-  // base classes, because they are not visible in derived classes.
-  getFieldsFromClassHierarchy(Base.getType(), /*IgnorePrivateFields=*/true,
-  Fields);
-}
-  }
+  if (auto *CXXRecord = Type->getAsCXXRecordDecl())
+for (const CXXBaseSpecifier  : CXXRecord->bases())
+  getFieldsFromClassHierarchy(Base.getType(), Fields);
 }
 
-/// Gets the set of all fields accesible from the type.
-///
-/// FIXME: Does not precisely handle non-virtual diamond inheritance. A single
-/// field decl will be modeled for all instances of the inherited field.
-static llvm::DenseSet
-getAccessibleObjectFields(QualType Type) {
+/// Gets the set of all fields in the type.
+static llvm::DenseSet getObjectFields(QualType Type) {
   llvm::DenseSet Fields;
-  // Don't ignore private fields for the class itself, only its super classes.
-  getFieldsFromClassHierarchy(Type, /*IgnorePrivateFields=*/false, Fields);
+  getFieldsFromClassHierarchy(Type, Fields);
   return Fields;
 }
 
@@ -324,9 +311,8 @@ StorageLocation 
::createStorageLocation(QualType Type) {
 // FIXME: Explore options to avoid eager initialization of fields as some 
of
 // them might not be needed for a particular analysis.
 llvm::DenseMap FieldLocs;
-for (const FieldDecl *Field : getAccessibleObjectFields(Type)) {
+for (const FieldDecl *Field : getObjectFields(Type))
   FieldLocs.insert({Field, (Field->getType())});
-}
 return takeOwnership(
 std::make_unique(Type, 
std::move(FieldLocs)));
   }
@@ -392,7 +378,7 @@ void Environment::setValue(const StorageLocation , 
Value ) {
 const QualType Type = AggregateLoc.getType();
 assert(Type->isStructureOrClassType());
 
-for (const FieldDecl *Field : getAccessibleObjectFields(Type)) {
+for (const FieldDecl *Field : getObjectFields(Type)) {
   assert(Field != nullptr);
   StorageLocation  = AggregateLoc.getChild(*Field);
   MemberLocToStruct[] = std::make_pair(StructVal, Field);
@@ -508,7 +494,7 @@ Value *Environment::createValueUnlessSelfReferential(
 // FIXME: Initialize only fields that are accessed in the context that is
 // being analyzed.
 llvm::DenseMap FieldValues;
-for (const FieldDecl *Field : getAccessibleObjectFields(Type)) {
+for (const FieldDecl *Field : getObjectFields(Type)) {
   assert(Field != nullptr);
 
   QualType 

[PATCH] D126420: [clang][dataflow] Remove private-field filtering from `StorageLocation` creation.

2022-05-27 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
ymandel marked an inline comment as done.
Closed by commit rG67136d0e8fb5: [clang][dataflow] Remove private-field 
filtering from `StorageLocation`… (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126420

Files:
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -1154,8 +1154,8 @@
 // two.
 
 // Base-class fields.
-EXPECT_THAT(FooVal.getChild(*ADefaultDecl), IsNull());
-EXPECT_THAT(FooVal.getChild(*APrivateDecl), IsNull());
+EXPECT_THAT(FooVal.getChild(*ADefaultDecl), NotNull());
+EXPECT_THAT(FooVal.getChild(*APrivateDecl), NotNull());
 
 EXPECT_THAT(FooVal.getChild(*AProtectedDecl), NotNull());
 EXPECT_EQ(Env.getValue(FooLoc.getChild(*APublicDecl)),
@@ -1177,6 +1177,40 @@
   });
 }
 
+static void derivedBaseMemberExpectations(
+llvm::ArrayRef>>
+Results,
+ASTContext ) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment  = Results[0].second.Env;
+
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
+
+  ASSERT_TRUE(FooDecl->getType()->isRecordType());
+  const FieldDecl *BarDecl = nullptr;
+  for (const clang::CXXBaseSpecifier  :
+   FooDecl->getType()->getAsCXXRecordDecl()->bases()) {
+QualType BaseType = Base.getType();
+ASSERT_TRUE(BaseType->isStructureType());
+
+for (const FieldDecl *Field : BaseType->getAsRecordDecl()->fields()) {
+  if (Field->getNameAsString() == "Bar") {
+BarDecl = Field;
+  } else {
+FAIL() << "Unexpected field: " << Field->getNameAsString();
+  }
+}
+  }
+  ASSERT_THAT(BarDecl, NotNull());
+
+  const auto  = *cast(
+  Env.getStorageLocation(*FooDecl, SkipPast::None));
+  const auto  = *cast(Env.getValue(FooLoc));
+  EXPECT_THAT(FooVal.getChild(*BarDecl), NotNull());
+  EXPECT_EQ(Env.getValue(FooLoc.getChild(*BarDecl)), FooVal.getChild(*BarDecl));
+}
+
 TEST_F(TransferTest, DerivedBaseMemberStructDefault) {
   std::string Code = R"(
 struct A {
@@ -1190,41 +1224,28 @@
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext ) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment  = Results[0].second.Env;
-
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
-
-ASSERT_TRUE(FooDecl->getType()->isRecordType());
-const FieldDecl *BarDecl = nullptr;
-for (const clang::CXXBaseSpecifier  :
- FooDecl->getType()->getAsCXXRecordDecl()->bases()) {
-  QualType BaseType = Base.getType();
-  ASSERT_TRUE(BaseType->isStructureType());
+  runDataflow(Code, derivedBaseMemberExpectations);
+}
 
-  for (const FieldDecl *Field : BaseType->getAsRecordDecl()->fields()) {
-if (Field->getNameAsString() == "Bar") {
-  BarDecl = Field;
-} else {
-  FAIL() << "Unexpected field: " << Field->getNameAsString();
-}
-  }
-}
-ASSERT_THAT(BarDecl, NotNull());
+TEST_F(TransferTest, DerivedBaseMemberPrivateFriend) {
+  // Include an access to `Foo.Bar` to verify the analysis doesn't crash on that
+  // access.
+  std::string Code = R"(
+struct A {
+private:
+  friend void target();
+  int Bar;
+};
+struct B : public A {
+};
 
-const auto  = *cast(
-Env.getStorageLocation(*FooDecl, SkipPast::None));
-const auto  = *cast(Env.getValue(FooLoc));
-EXPECT_THAT(FooVal.getChild(*BarDecl), NotNull());
-EXPECT_EQ(Env.getValue(FooLoc.getChild(*BarDecl)),
-  FooVal.getChild(*BarDecl));
-  });
+void target() {
+  B Foo;
+  (void)Foo.Bar;
+  // [[p]]
+}
+  )";
+  runDataflow(Code, derivedBaseMemberExpectations);
 }
 
 TEST_F(TransferTest, ClassMember) {
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -148,39 +148,26 @@
   }
 }
 
+// FIXME: Does not precisely handle non-virtual diamond inheritance. A single
+// field decl will be modeled for all instances of the inherited field.
 static void
-getFieldsFromClassHierarchy(QualType 

[PATCH] D126524: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

The differential I linked doesn't contain the right diff. Here's the commit I 
meant to point out: 3a75330f573a31c7e0f7e27c5d34501c293673a5.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126524

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


[PATCH] D126524: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added a comment.
This revision is now accepted and ready to land.

Nice. This is the patch that makes the condition obsolete: D60871 
. You might also remove the `else`, since the 
first `if` now has an unconditional early return.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126524

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


[PATCH] D126536: [pseudo] Add grammar annotations support.

2022-05-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h:87
+// Defines the built-in attribute keys.
+enum class AttributeKey : uint8_t {
+  // A guard controls whether a reduction of a rule will be conducted by the 
GLR

new names are welcome. Attribute is the name I came up with (I think it is 
clearer than the original `Hook`), 



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h:94
+// It is the index into a table of attribute values.
+// NOTE: value among attributes must be unique even within different keys!
+using AttributeID = uint16_t;

I'm not quite happy with using the value as the ID, I think we can encode the 
Key into the ID as well (ID := Key | Value). 

Similar to the generated enum name, currently we just use the name of Value 
(`Override`), it will be more confusing when we add more keys/values, one idea 
is to add key as well (`GuardOverride` etc?).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126536

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


[PATCH] D126289: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-27 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan marked 2 inline comments as done.
egorzhdan added inline comments.



Comment at: clang/lib/Driver/ToolChain.cpp:917
 
+/*static*/ std::string ToolChain::concat(const std::string ,
+ const Twine , const Twine ,

MaskRay wrote:
> I think the first argument of `concat` should be `StringRef`, then we can 
> avoid changing the signature of `getMultiarchTriple`
You're right, thanks!



Comment at: clang/test/Driver/linux-header-search.cpp:76
+
+// Test Linux with libstdc++.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \

MaskRay wrote:
> I suspect this test does not add more coverage than linux-cross.cpp.
> 
> To test --sysroot with a trailing `/`, just modify the previous 
> `CHECK-BASIC-LIBCXXV2` by appending a `/`
`CHECK-BASIC-LIBCXXV2 ` is not quite the same: I'd like to test the libstdc++ 
detection logic (e.g. `GCCInstallationDetector`) which doesn't get invoked for 
libc++.

I removed the unnecessary test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126289

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


[PATCH] D126536: [pseudo] Add grammar annotations support.

2022-05-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

This patch might cover too many things (at least we could split the guide/glr 
implementation bit), but want to give you an overview of the picture first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126536

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


[PATCH] D126289: [Clang][Driver] Fix include paths for `--sysroot /` on Linux

2022-05-27 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 432539.
egorzhdan added a comment.

- Change arg type from `std::string` to `StringRef`
- Remove unnecessary `//`

• Remove unneeded test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126289

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/bin/.keep
  
clang/test/Driver/Inputs/basic_linux_libstdcxx_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/crtbegin.o
  clang/test/Driver/linux-header-search.cpp

Index: clang/test/Driver/linux-header-search.cpp
===
--- clang/test/Driver/linux-header-search.cpp
+++ clang/test/Driver/linux-header-search.cpp
@@ -16,6 +16,22 @@
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/x86_64-unknown-linux-gnu/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/include/c++/v1"
 // CHECK-BASIC-LIBCXX-SYSROOT: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
+
+// Test include paths when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/x86_64-unknown-linux-gnu/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/include/c++/v1"
+// CHECK-BASIC-LIBCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/local/include"
+
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
 // RUN: -stdlib=libc++ \
@@ -56,7 +72,20 @@
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/x86_64-unknown-linux-gnu/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/bin/../include/c++/v2"
 // CHECK-BASIC-LIBCXXV2-INSTALL: "-internal-isystem" "[[SYSROOT]]/usr/local/include"
-//
+
+// Test Linux with libstdc++ when the sysroot path ends with `/`.
+// RUN: %clang -### %s -fsyntax-only 2>&1 \
+// RUN: --target=x86_64-unknown-linux-gnu \
+// RUN: -stdlib=libstdc++ \
+// RUN: -ccc-install-dir %S/Inputs/basic_linux_tree/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: --sysroot=%S/Inputs/basic_linux_libstdcxx_tree/ \
+// RUN: --gcc-toolchain="" \
+// RUN:   | FileCheck --check-prefix=CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH %s
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH: "-cc1"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-isysroot" "[[SYSROOT:[^"]+/]]"
+// CHECK-BASIC-LIBSTDCXX-SYSROOT-SLASH-SAME: "-internal-isystem" "[[SYSROOT]]usr/lib/gcc/x86_64-unknown-linux-gnu/4.8/../../../../x86_64-unknown-linux-gnu/include"
+
 // Test Linux with both libc++ and libstdc++ installed.
 // RUN: %clang -### %s -fsyntax-only 2>&1 \
 // RUN: --target=x86_64-unknown-linux-gnu \
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -97,9 +97,9 @@
   case llvm::Triple::mips64: {
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
   return "mips64-linux-gnu";
 break;
   }
@@ -108,14 +108,14 @@
   return "mips64el-linux-android";
 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
  "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
-if (D.getVFS().exists(SysRoot + "/lib/" + MT))
+if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
   return MT;
-if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
   return "mips64el-linux-gnu";
 break;
   }
   case llvm::Triple::ppc:
-if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
+if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
   return "powerpc-linux-gnuspe";
 return "powerpc-linux-gnu";
   case 

[PATCH] D126536: [pseudo] Add grammar annotations support.

2022-05-27 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: mgrang, mgorny.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: alextsao1999.
Herald added a project: clang-tools-extra.

- Add annotation handling ([key=value]) in the BNF grammar parser;
- Define and setup the API in the grammar for attributes;
- Implement a builtin guard for two simple c++ contexual-override/final use 
cases;


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126536

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/cxx.bnf
  clang-tools-extra/pseudo/lib/cxx/CMakeLists.txt
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -99,6 +99,14 @@
   EXPECT_LT(ruleFor("x"), ruleFor("_"));
 }
 
+TEST_F(GrammarTest, Annotation) {
+  build(R"bnf(
+_ := IDENTIFIER [guard=override]
+  )bnf");
+  ASSERT_TRUE(Diags.empty());
+  EXPECT_NE(G->lookupRule(ruleFor("_")).Guard, NoneAttribute);
+}
+
 TEST_F(GrammarTest, Diagnostics) {
   build(R"cpp(
 _ := ,_opt
@@ -110,17 +118,25 @@
 # cycle
 a := b
 b := a
+
+_ := IDENTIFIER [guard=override;unknown=value]
+_ := IDENTIFIER [guard=override] ;
+_ := [guard=override] ;
   )cpp");
 
   EXPECT_EQ(G->underscore(), id("_"));
-  EXPECT_THAT(Diags, UnorderedElementsAre(
- "Rule '_ := ,_opt' has a nullable RHS",
- "Rule 'null := ' has a nullable RHS",
- "No rules for nonterminal: undefined-sym",
- "Failed to parse 'invalid': no separator :=",
- "Token-like name IDENFIFIE is used as a nonterminal",
- "No rules for nonterminal: IDENFIFIE",
- "The grammar contains a cycle involving symbol a"));
+  EXPECT_THAT(
+  Diags, UnorderedElementsAre(
+ "Rule '_ := ,_opt' has a nullable RHS",
+ "Rule 'null := ' has a nullable RHS",
+ "No rules for nonterminal: undefined-sym",
+ "Failed to parse 'invalid': no separator :=",
+ "Token-like name IDENFIFIE is used as a nonterminal",
+ "No rules for nonterminal: IDENFIFIE",
+ "The grammar contains a cycle involving symbol a",
+ "Unknown attribute key 'unknown'",
+ "Attribute 'guard' can only be specified at the end of a rule",
+ "Attributes are not allowed at the beginning of the rule"));
 }
 
 TEST_F(GrammarTest, FirstAndFollowSets) {
Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -158,7 +158,7 @@
   std::vector PendingReduce = {
   {GSSNode1, Action::reduce(ruleFor("class-name"))},
   {GSSNode1, Action::reduce(ruleFor("enum-name"))}};
-  glrReduce(PendingReduce, {*G, Table, Arena, GSStack},
+  glrReduce(PendingReduce, TokenStream(), {*G, Table, Arena, GSStack},
 captureNewHeads());
   EXPECT_THAT(NewHeadResults,
   testing::UnorderedElementsAre(
@@ -195,7 +195,7 @@
{/*State=*/3, id("ptr-operator"), Action::goTo(/*NextState=*/6)}});
   std::vector PendingReduce = {
   {GSSNode4, Action::reduce(ruleFor("ptr-operator"))}};
-  glrReduce(PendingReduce, {*G, Table, Arena, GSStack},
+  glrReduce(PendingReduce, TokenStream(), {*G, Table, Arena, GSStack},
 captureNewHeads());
 
   EXPECT_THAT(NewHeadResults,
@@ -250,7 +250,7 @@
   {
   GSSNode4, Action::reduce(/*RuleID=*/1) // type-name := enum-name
   }};
-  glrReduce(PendingReduce, {*G, Table, Arena, GSStack},
+  glrReduce(PendingReduce, TokenStream(), {*G, Table, Arena, GSStack},
 captureNewHeads());
 
   // Verify that the stack heads are joint at state 5 after reduces.
@@ -306,7 +306,7 @@
   {
   GSSNode4, Action::reduce(/*RuleID=*/1) // pointer := enum-name *
   }};
-  glrReduce(PendingReduce, {*G, Table, Arena, GSStack},
+  glrReduce(PendingReduce, TokenStream(), {*G, Table, Arena, GSStack},
 captureNewHeads());
 
   EXPECT_THAT(NewHeadResults, testing::UnorderedElementsAre(
Index: 

[PATCH] D126067: [analyzer] Deprecate the unused 'analyzer-opt-analyze-nested-blocks' cc1 flag

2022-05-27 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

I plan to land this stack next Wednesday.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126067

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


[PATCH] D126534: Deadstore static analysis: Fix false positive on C++17 assignments

2022-05-27 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource created this revision.
frederic-tingaud-sonarsource added a reviewer: dcoughlin.
Herald added a subscriber: martong.
Herald added a project: All.
frederic-tingaud-sonarsource requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Dead store detection automatically checks that an expression is a 
CXXConstructor and skips it because of potential side effects. In C++17, with 
guaranteed copy elision, this check can fail because we actually receive the 
implicit cast of a CXXConstructor.
Most checks in the dead store analysis were already stripping all casts and 
parenthesis and those that weren't were either forgotten (like the constructor) 
or would not suffer from it, so this patch proposes to factorize the stripping.
It has an impact on where the dead store warning is reported in the case of an 
explicit cast, from

  auto a = static_cast(A());
   ^~~

to

  auto a = static_cast(A());
  ^~~

which we think is an improvement.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126534

Files:
  clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
  clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
  clang/test/Analysis/dead-stores.cpp

Index: clang/test/Analysis/dead-stores.cpp
===
--- clang/test/Analysis/dead-stores.cpp
+++ clang/test/Analysis/dead-stores.cpp
@@ -12,6 +12,10 @@
 // RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
 // RUN:  -verify=non-nested,nested %s
 
+// RUN: %clang_analyze_cc1 -fcxx-exceptions -fexceptions -fblocks -std=c++17\
+// RUN:  -analyzer-checker=deadcode.DeadStores -Wno-unreachable-code\
+// RUN:  -verify=non-nested,nested %s
+
 //===--===//
 // Basic dead store checking (but in C++ mode).
 //===--===//
@@ -52,6 +56,17 @@
   return x;
 }
 
+class TestConstructor {
+public:
+  TestConstructor(int );
+};
+void copy(int x) {
+  TestConstructor tc1 = x; // no-warning
+  TestConstructor tc2 = TestConstructor(x);   // no-warning
+  TestConstructor tc3 = (TestConstructor(x)); // no-warning
+  TestConstructor tc4 = (TestConstructor)(x); // no-warning
+}
+
 //===--===//
 // Dead store checking involving CXXTemporaryExprs
 //===--===//
Index: clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
===
--- clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
+++ clang/test/Analysis/Inputs/expected-plists/objc-arc.m.plist
@@ -432,7 +432,7 @@

 
  line139
- col13
+ col35
  file0
 
 
@@ -500,7 +500,7 @@

 
  line144
- col13
+ col33
  file0
 
 
@@ -568,7 +568,7 @@

 
  line145
- col13
+ col26
  file0
 
 
@@ -636,7 +636,7 @@

 
  line146
- col13
+ col33
  file0
 
 
@@ -1046,7 +1046,7 @@

 
  line150
- col19
+ col48
  file0
 
 
@@ -1114,7 +1114,7 @@

 
  line151
- col21
+ col52
  file0
 
 
@@ -1182,7 +1182,7 @@

 
  line152
- col19
+ col39
  file0
 
 
@@ -1250,7 +1250,7 @@

 
  line153
- col21
+ col43
  file0
 
 
Index: clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp
@@ -103,8 +103,9 @@
 static const Expr *
 LookThroughTransitiveAssignmentsAndCommaOperators(const Expr *Ex) {
   while (Ex) {
+Ex = Ex->IgnoreParenCasts();
 const BinaryOperator *BO =
-  dyn_cast(Ex->IgnoreParenCasts());
+  dyn_cast(Ex);
 if (!BO)
   break;
 BinaryOperatorKind Op = BO->getOpcode();
@@ -332,7 +333,6 @@
   //  This is a common form of defensive programming.
   const Expr *RHS =
 LookThroughTransitiveAssignmentsAndCommaOperators(B->getRHS());
-  RHS = RHS->IgnoreParenCasts();
 
   QualType T = VD->getType();
   if (T.isVolatileQualified())
@@ -416,7 +416,7 @@
 return;
 
   if (const DeclRefExpr *DRE =
-  dyn_cast(E->IgnoreParenCasts()))
+  dyn_cast(E))
 if 

[PATCH] D72386: [ThinLTO] pass UnrollLoops/VectorizeLoop/VectorizeSLP in CGOpts down to pass builder in ltobackend

2022-05-27 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added inline comments.
Herald added a reviewer: MaskRay.
Herald added subscribers: vporpo, pmatos, asb.
Herald added a project: All.



Comment at: lld/ELF/LTO.cpp:96
 
+  c.PTO.LoopVectorization = c.OptLevel > 1;
+  c.PTO.SLPVectorization = c.OptLevel > 1;

COFF?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72386

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


[PATCH] D126215: [analyzer] Deprecate `-analyzer-store region` flag

2022-05-27 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

Still looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126215

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


[PATCH] D119675: Also remove the empty StoredDeclsList entry from the lookup table

2022-05-27 Thread Vassil Vassilev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8c0eb32d2aa0: Also remove the empty StoredDeclsList entry 
from the lookup table (authored by v.g.vassilev).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119675

Files:
  clang/lib/AST/DeclBase.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -4279,6 +4279,10 @@
   // This asserts in the old implementation.
   DC->removeDecl(A0);
   EXPECT_FALSE(DC->containsDecl(A0));
+
+  // Make sure we do not leave a StoredDeclsList with no entries.
+  DC->removeDecl(A1);
+  ASSERT_EQ(Map->find(A1->getDeclName()), Map->end());
 }
 
 struct ImportFunctionTemplateSpecializations
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1537,7 +1537,11 @@
   if (Map) {
 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
 assert(Pos != Map->end() && "no lookup entry for decl");
-Pos->second.remove(ND);
+StoredDeclsList  = Pos->second;
+List.remove(ND);
+// Clean up the entry if there are no more decls.
+if (List.isNull())
+  Map->erase(Pos);
   }
 } while (DC->isTransparentContext() && (DC = DC->getParent()));
   }


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -4279,6 +4279,10 @@
   // This asserts in the old implementation.
   DC->removeDecl(A0);
   EXPECT_FALSE(DC->containsDecl(A0));
+
+  // Make sure we do not leave a StoredDeclsList with no entries.
+  DC->removeDecl(A1);
+  ASSERT_EQ(Map->find(A1->getDeclName()), Map->end());
 }
 
 struct ImportFunctionTemplateSpecializations
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1537,7 +1537,11 @@
   if (Map) {
 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
 assert(Pos != Map->end() && "no lookup entry for decl");
-Pos->second.remove(ND);
+StoredDeclsList  = Pos->second;
+List.remove(ND);
+// Clean up the entry if there are no more decls.
+if (List.isNull())
+  Map->erase(Pos);
   }
 } while (DC->isTransparentContext() && (DC = DC->getParent()));
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8c0eb32 - Also remove the empty StoredDeclsList entry from the lookup table

2022-05-27 Thread Vassil Vassilev via cfe-commits

Author: Vassil Vassilev
Date: 2022-05-27T12:36:37Z
New Revision: 8c0eb32d2aa0bc73c176d7b25f47bdf37f967d3b

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

LOG: Also remove the empty StoredDeclsList entry from the lookup table

In case where we have removed all declarations for a given declaration name
entry we should remove the whole StoredDeclsMap entry.

This patch improves consistency in the lookup tables and helps cling/clang-repl
error recovery.

Differential revision: https://reviews.llvm.org/D119675

Added: 


Modified: 
clang/lib/AST/DeclBase.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/DeclBase.cpp b/clang/lib/AST/DeclBase.cpp
index d5ad636810544..13dd6da3f24fe 100644
--- a/clang/lib/AST/DeclBase.cpp
+++ b/clang/lib/AST/DeclBase.cpp
@@ -1537,7 +1537,11 @@ void DeclContext::removeDecl(Decl *D) {
   if (Map) {
 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
 assert(Pos != Map->end() && "no lookup entry for decl");
-Pos->second.remove(ND);
+StoredDeclsList  = Pos->second;
+List.remove(ND);
+// Clean up the entry if there are no more decls.
+if (List.isNull())
+  Map->erase(Pos);
   }
 } while (DC->isTransparentContext() && (DC = DC->getParent()));
   }

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 896e3cb7a956c..f1965235c9a6d 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -4279,6 +4279,10 @@ TEST_P(DeclContextTest,
   // This asserts in the old implementation.
   DC->removeDecl(A0);
   EXPECT_FALSE(DC->containsDecl(A0));
+
+  // Make sure we do not leave a StoredDeclsList with no entries.
+  DC->removeDecl(A1);
+  ASSERT_EQ(Map->find(A1->getDeclName()), Map->end());
 }
 
 struct ImportFunctionTemplateSpecializations



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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-05-27 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:621
 
+void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
+  while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())

iains wrote:
> ChuanqiXu wrote:
> > iains wrote:
> > > ChuanqiXu wrote:
> > > > Recommend to comment related part in your summary. It should be much 
> > > > helpful for other to read the codes.
> > > Hmm. I am not sure exactly what you mean here - there is a comment about 
> > > the purpose of the method, where the method is declared.
> > > The commit message describes what this method does in the first part.  
> > > I'm happy to make things more clear, but not sure where you want to see 
> > > some change,
> > I mean the paragraph:
> > ```
> > For a module (instead of the generic CXX initializer) we emit a module init
> > that:
> > 
> > - wraps the contained initializations in a control variable to ensure that 
> > the inits only happen once, even if a module is imported many times by 
> > imports of the main unit.
> > - calls module initialisers for imported modules first. Note that the order 
> > of module import is not significant, and therefore neither is the order of 
> > imported module initializers.
> > - We then call initializers for the Global Module Fragment (if present)
> > - We then call initializers for the current module.
> > - We then call initializers for the Private Module Fragment (if present)
> > ```
> > 
> > I understand people might feel like this is wordy. But, **personally**, I 
> > prefer readability.
> so, to clarify - you would like me to add this description as a comment block 
> on the new initializer method (I am OK with doing this)
Yeah, I feel it is helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D126524: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Yuki Okushi via Phabricator via cfe-commits
JohnTitor updated this revision to Diff 432527.
JohnTitor added a comment.

Fix the indention


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126524

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,13 +710,10 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,13 +710,10 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
   Loc.Line, Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126524: [CompilerInstance] Fix weird condition on `createCodeCompletionConsumer`

2022-05-27 Thread Yuki Okushi via Phabricator via cfe-commits
JohnTitor updated this revision to Diff 432526.
JohnTitor added a comment.

[CompilerInstance] Tweak the condition on `createCodeCompletionConsumer`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126524

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,15 +710,12 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
-  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
-  Loc.Line, Loc.Column)) {
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
+  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, Loc.Line,
+  Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
 return;
   }


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -710,15 +710,12 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation  = getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-setCodeCompletionConsumer(
-  createCodeCompletionConsumer(getPreprocessor(),
-   Loc.FileName, Loc.Line, Loc.Column,
-   getFrontendOpts().CodeCompleteOpts,
-   llvm::outs()));
-if (!CompletionConsumer)
-  return;
-  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
-  Loc.Line, Loc.Column)) {
+setCodeCompletionConsumer(createCodeCompletionConsumer(
+getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column,
+getFrontendOpts().CodeCompleteOpts, llvm::outs()));
+return;
+  } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, Loc.Line,
+  Loc.Column)) {
 setCodeCompletionConsumer(nullptr);
 return;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126067: [analyzer] Deprecate the unused 'analyzer-opt-analyze-nested-blocks' cc1 flag

2022-05-27 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 432525.
steakhal retitled this revision from "[analyzer] Drop the unused 
'analyzer-opt-analyze-nested-blocks' cc1 flag" to "[analyzer] Deprecate the 
unused 'analyzer-opt-analyze-nested-blocks' cc1 flag".
steakhal edited the summary of this revision.
steakhal added a comment.

- Rebase on top of D126215 
- Accept the flag with a warning, rather than erroring out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126067

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Driver/Options.td
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Analysis/OSAtomic_mac.cpp
  clang/test/Analysis/analyzer-stats.c
  clang/test/Analysis/blocks.m
  clang/test/Analysis/blocks.mm
  clang/test/Analysis/deprecated-flags-and-options.cpp
  clang/test/Analysis/misc-ps-arm.m
  clang/test/Analysis/misc-ps-region-store.cpp
  clang/test/Analysis/misc-ps-region-store.m
  clang/test/Analysis/misc-ps-region-store.mm
  clang/test/Analysis/objc-arc.m
  clang/test/Analysis/unreachable-code-path.c

Index: clang/test/Analysis/unreachable-code-path.c
===
--- clang/test/Analysis/unreachable-code-path.c
+++ clang/test/Analysis/unreachable-code-path.c
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,deadcode.DeadStores,alpha.deadcode.UnreachableCode -verify -analyzer-opt-analyze-nested-blocks -Wno-unused-value %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,deadcode.DeadStores,alpha.deadcode.UnreachableCode -verify -Wno-unused-value %s
 
 extern void foo(int a);
 
Index: clang/test/Analysis/objc-arc.m
===
--- clang/test/Analysis/objc-arc.m
+++ clang/test/Analysis/objc-arc.m
@@ -1,4 +1,4 @@
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 -analyzer-checker=core,osx.cocoa.RetainCount,deadcode -verify -fblocks -analyzer-opt-analyze-nested-blocks -fobjc-arc -analyzer-output=plist-multi-file -analyzer-config deadcode.DeadStores:ShowFixIts=true -o %t.plist %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 -analyzer-checker=core,osx.cocoa.RetainCount,deadcode -verify -fblocks -fobjc-arc -analyzer-output=plist-multi-file -analyzer-config deadcode.DeadStores:ShowFixIts=true -o %t.plist %s
 // RUN: %normalize_plist <%t.plist | diff -ub %S/Inputs/expected-plists/objc-arc.m.plist -
 
 typedef signed char BOOL;
Index: clang/test/Analysis/misc-ps-region-store.mm
===
--- clang/test/Analysis/misc-ps-region-store.mm
+++ clang/test/Analysis/misc-ps-region-store.mm
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 -analyzer-checker=core,alpha.core -verify -fblocks -analyzer-opt-analyze-nested-blocks %s
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 -analyzer-checker=core,alpha.core -verify -fblocks   -analyzer-opt-analyze-nested-blocks %s
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9   -analyzer-checker=core,alpha.core -verify -fblocks %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 -analyzer-checker=core,alpha.core -verify -fblocks %s
 // expected-no-diagnostics
 
 //===--===//
Index: clang/test/Analysis/misc-ps-region-store.m
===
--- clang/test/Analysis/misc-ps-region-store.m
+++ clang/test/Analysis/misc-ps-region-store.m
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks -analyzer-opt-analyze-nested-blocks -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 -DTEST_64 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks   -analyzer-opt-analyze-nested-blocks -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin9 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin9 -DTEST_64 -analyzer-checker=core,alpha.core.CastToStruct,alpha.security.ReturnPtrRange,alpha.security.ArrayBound -verify -fblocks -Wno-objc-root-class -Wno-strict-prototypes -Wno-error=implicit-function-declaration %s
 
 typedef long unsigned int size_t;
 

[PATCH] D123924: [clang-apply-replacements] Added an option to ignore insert conflict.

2022-05-27 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 432522.
Sockke added a comment.

rebased.


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

https://reviews.llvm.org/D123924

Files:
  
clang-tools-extra/clang-apply-replacements/include/clang-apply-replacements/Tooling/ApplyReplacements.h
  clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp
  clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
  
clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/file1.yaml
  
clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/ignore-conflict.cpp
  clang-tools-extra/test/clang-apply-replacements/ignore-conflict.cpp
  clang/include/clang/Tooling/Refactoring/AtomicChange.h

Index: clang/include/clang/Tooling/Refactoring/AtomicChange.h
===
--- clang/include/clang/Tooling/Refactoring/AtomicChange.h
+++ clang/include/clang/Tooling/Refactoring/AtomicChange.h
@@ -116,6 +116,8 @@
   /// Returns a const reference to existing replacements.
   const Replacements () const { return Replaces; }
 
+  Replacements () { return Replaces; }
+
   llvm::ArrayRef getInsertedHeaders() const {
 return InsertedHeaders;
   }
Index: clang-tools-extra/test/clang-apply-replacements/ignore-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/ignore-conflict.cpp
@@ -0,0 +1,5 @@
+// RUN: mkdir -p %T/Inputs/ignore-conflict
+// RUN: grep -Ev "// *[A-Z-]+:" %S/Inputs/ignore-conflict/ignore-conflict.cpp > %T/Inputs/ignore-conflict/ignore-conflict.cpp
+// RUN: sed "s#\$(path)#%/T/Inputs/ignore-conflict#" %S/Inputs/ignore-conflict/file1.yaml > %T/Inputs/ignore-conflict/file1.yaml
+// RUN: clang-apply-replacements --ignore-insert-conflict %T/Inputs/ignore-conflict
+// RUN: FileCheck -input-file=%T/Inputs/ignore-conflict/ignore-conflict.cpp %S/Inputs/ignore-conflict/ignore-conflict.cpp
Index: clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/ignore-conflict.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/ignore-conflict.cpp
@@ -0,0 +1,4 @@
+class MyType {};
+// CHECK: #include 
+// CHECK-NEXT: #include 
+// CEHCK-NEXT: class MyType {};
Index: clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/file1.yaml
===
--- /dev/null
+++ clang-tools-extra/test/clang-apply-replacements/Inputs/ignore-conflict/file1.yaml
@@ -0,0 +1,24 @@
+---
+MainSourceFile: ignore-conflict.cpp
+Diagnostics:
+  - DiagnosticName: test-ignore-conflict-insertion
+DiagnosticMessage:
+  Message: Fix
+  FilePath: $(path)/ignore-conflict.cpp
+  FileOffset: 0
+  Replacements:
+- FilePath:$(path)/ignore-conflict.cpp
+  Offset:  0
+  Length:  0
+  ReplacementText: "#include \n"
+  - DiagnosticName: test-ignore-conflict-insertion
+DiagnosticMessage:
+  Message: Fix
+  FilePath: $(path)/ignore-conflict.cpp
+  FileOffset: 0
+  Replacements:
+- FilePath:$(path)/ignore-conflict.cpp
+  Offset:  0
+  Length:  0
+  ReplacementText: "#include \n"
+...
Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -180,6 +180,7 @@
 def apply_fixes(args, clang_apply_replacements_binary, tmpdir):
   """Calls clang-apply-fixes on a given directory."""
   invocation = [clang_apply_replacements_binary]
+  invocation.append('-ignore-insert-conflict')
   if args.format:
 invocation.append('-format')
   if args.style:
Index: clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
===
--- clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
+++ clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
@@ -42,6 +42,11 @@
  "merging/replacing."),
 cl::init(false), cl::cat(ReplacementCategory));
 
+static cl::opt IgnoreInsertConflict(
+"ignore-insert-conflict",
+cl::desc("Ignore insert conflict and keep running to fix."),
+cl::init(false), cl::cat(ReplacementCategory));
+
 static cl::opt DoFormat(
 "format",
 cl::desc("Enable formatting of code changed by applying replacements.\n"
@@ -131,7 +136,7 @@
   SourceManager SM(Diagnostics, Files);
 
   FileToChangesMap Changes;
-  if (!mergeAndDeduplicate(TURs, TUDs, Changes, SM))
+  if (!mergeAndDeduplicate(TURs, TUDs, Changes, SM, IgnoreInsertConflict))

[PATCH] D126364: Fix interaction of pragma FENV_ACCESS with other pragmas

2022-05-27 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

In D126364#3540673 , @efriedma wrote:

> For FENV_ROUND, I think we should try to stick to the standard as closely as 
> possible in Sema; since the standard models FENV_ROUND as a separate state, 
> Sema should also model it as a separate state.

I try to figure out the difference between rounding mode as specified by 
FENV_ROUND and that represented by `Sema::CufFPFeatures`. The standard uses two 
notions for rounding mode:

- dynamic rounding mode, which is actually bits in a control register, and
- constant rounding mode, which is used for floating-point operators, implicit 
conversions and so on.

Dynamic rounding mode is set/queried by fegetround/fesetround/FLT_ROUNDS. It is 
unknown at compile time except that in default FP mode it is expected to be 
FE_TONEAREST.

What compiler can know is constant rounding mode, it is just the mode set by 
pragma FENV_ROUND.

It looks like `Sema::CufFPFeatures` is exactly what FENV_ROUND controls.
Do I miss something?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-05-27 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 432520.
Sockke added a comment.

Rebased and added '-fno-delayed-template-parsing' option for the test file.


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

https://reviews.llvm.org/D116593

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t
+// RUN: %check_clang_tidy %s performance-unnecessary-value-param %t -- -- -fno-delayed-template-parsing
 
 // CHECK-FIXES: #include 
 
@@ -109,7 +109,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
@@ -381,3 +381,24 @@
   // CHECK-FIXES: void templateFunction(ExpensiveToCopyType E) {
   E.constReference();
 }
+
+template 
+T templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:54: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: T templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return T();
+}
+
+template <>
+bool templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:57: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: bool templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return true;
+}
+
+template <>
+int templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:56: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: int templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return 0;
+}
Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
@@ -69,7 +69,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -202,6 +202,10 @@
   ` to simplify expressions
   using DeMorgan's Theorem.
 
+- Fixed a crash in :doc:`performance-unnecessary-value-param
+  ` when the specialization
+  template has an unnecessary value paramter. Removed the fix for a template.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -51,18 +51,6 @@
   return Matches.empty();
 }
 
-bool isExplicitTemplateSpecialization(const FunctionDecl ) {
-  if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
-if (SpecializationInfo->getTemplateSpecializationKind() ==
-TSK_ExplicitSpecialization)
-  return true;
-  if (const auto *Method = llvm::dyn_cast())
-if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
-Method->getMemberSpecializationInfo()->isExplicitSpecialization())
-  return true;
-  return false;
-}
-
 } // namespace
 
 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
@@ -147,11 +135,12 @@
   // 2. the function is virtual as it might break overrides
   // 3. the function is referenced outside of a call expression within the
   //compilation unit as the signature change could introduce build errors.
-  // 4. the function is an explicit template specialization.
+  // 4. the function is a primary template or an 

[PATCH] D121413: [clang-repl] Add an accessor to our underlying execution engine

2022-05-27 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev closed this revision.
v.g.vassilev added a comment.
Herald added a subscriber: StephenFan.

Landed in 
https://github.com/llvm/llvm-project/commit/788e0f7f3e96a9d61c2412e452c4589e2693b79a


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

https://reviews.llvm.org/D121413

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


[PATCH] D124690: [clangd] add inlay hints for std::forward-ed parameter packs

2022-05-27 Thread Tobias Ribizel via Phabricator via cfe-commits
upsj updated this revision to Diff 432518.
upsj added a comment.

Of course, I forgot to create a new diff. There is some debug output and logic 
errors for some of the tests, but the simple ones already show the issue.
The function in question is `getPackTemplateParameter`, which provides similar 
functionality to `isExpandedParameter` before


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124690

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -174,6 +174,44 @@
   )cpp");
 }
 
+TEST(ParameterHints, NoNameVariadicDeclaration) {
+  // No hint for anonymous variadic parameter
+  assertParameterHints(R"cpp(
+template 
+void foo(Args&& ...);
+void bar() {
+  foo(42);
+}
+  )cpp");
+}
+
+TEST(ParameterHints, NoNameVariadicForwarded) {
+  // No hint for anonymous variadic parameter
+  // This prototype of std::forward is sufficient for clang to recognize it
+  assertParameterHints(R"cpp(
+namespace std { template  T&& forward(T&); }
+void foo(int);
+template 
+void bar(Args&&... args) { return foo(std::forward($fwd[[args]])...); }
+void baz() {
+  bar(42);
+}
+  )cpp",
+   ExpectedHint{"&: ", "fwd"});
+}
+
+TEST(ParameterHints, NoNameVariadicPlain) {
+  // No hint for anonymous variadic parameter
+  assertParameterHints(R"cpp(
+void foo(int);
+template 
+void bar(Args&&... args) { return foo(args...); }
+void baz() {
+  bar(42);
+}
+  )cpp");
+}
+
 TEST(ParameterHints, NameInDefinition) {
   // Parameter name picked up from definition if necessary.
   assertParameterHints(R"cpp(
@@ -186,6 +224,19 @@
ExpectedHint{"param: ", "param"});
 }
 
+TEST(ParameterHints, NamePartiallyInDefinition) {
+  // Parameter name picked up from definition if necessary.
+  assertParameterHints(R"cpp(
+void foo(int, int b);
+void bar() {
+  foo($param1[[42]], $param2[[42]]);
+}
+void foo(int a, int) {};
+  )cpp",
+   ExpectedHint{"a: ", "param1"},
+   ExpectedHint{"b: ", "param2"});
+}
+
 TEST(ParameterHints, NameMismatch) {
   // Prefer name from declaration.
   assertParameterHints(R"cpp(
@@ -258,6 +309,276 @@
ExpectedHint{"param: ", "param"});
 }
 
+TEST(ParameterHints, VariadicForwardedConstructor) {
+  // Name hint for variadic parameter
+  // This prototype of std::forward is sufficient for clang to recognize it
+  assertParameterHints(R"cpp(
+namespace std { template  T&& forward(T&); }
+struct S { S(int a); };
+template 
+T bar(Args&&... args) { return T{std::forward($fwd[[args]])...}; }
+void baz() {
+  int b;
+  bar($param[[b]]);
+}
+  )cpp",
+   ExpectedHint{"&: ", "fwd"},
+   ExpectedHint{"a: ", "param"});
+}
+
+TEST(ParameterHints, VariadicPlainConstructor) {
+  // Name hint for variadic parameter
+  assertParameterHints(R"cpp(
+struct S { S(int a); };
+template 
+T bar(Args&&... args) { return T{args...}; }
+void baz() {
+  int b;
+  bar($param[[b]]);
+}
+  )cpp",
+   ExpectedHint{"a: ", "param"});
+}
+
+TEST(ParameterHints, VariadicForwardedNewConstructor) {
+  // Name hint for variadic parameter
+  // This prototype of std::forward is sufficient for clang to recognize it
+  assertParameterHints(R"cpp(
+namespace std { template  T&& forward(T&); }
+struct S { S(int a); };
+template 
+T* bar(Args&&... args) { return new T{std::forward($fwd[[args]])...}; }
+void baz() {
+  int b;
+  bar($param[[b]]);
+}
+  )cpp",
+   ExpectedHint{"&: ", "fwd"},
+   ExpectedHint{"a: ", "param"});
+}
+
+TEST(ParameterHints, VariadicPlainNewConstructor) {
+  // Name hint for variadic parameter
+  assertParameterHints(R"cpp(
+struct S { S(int a); };
+template 
+T* bar(Args&&... args) { return new T{args...}; }
+void baz() {
+  int b;
+  bar($param[[b]]);
+}
+  )cpp",
+   ExpectedHint{"a: ", "param"});
+}
+
+TEST(ParameterHints, VariadicForwarded) {
+  // Name for variadic parameter
+  // This prototype of std::forward is sufficient for clang to recognize it
+  assertParameterHints(R"cpp(
+namespace std { template  T&& forward(T&); }
+void foo(int a);
+template 
+void bar(Args&&... args) { return foo(std::forward($fwd[[args]])...); }
+void baz() {
+  int b;
+  bar($param[[b]]);
+}
+  )cpp",
+   

  1   2   >