[PATCH] D123836: [Driver] Move Lanai IAS enabling to Generic_GCC::IsIntegratedAssemblerDefault, NFC

2022-04-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

Looks great!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123836

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


[PATCH] D123836: [Driver] Move Lanai IAS enabling to Generic_GCC::IsIntegratedAssemblerDefault, NFC

2022-04-15 Thread Jacques Pienaar via Phabricator via cfe-commits
jpienaar accepted this revision.
jpienaar added a comment.

Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123836

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


[PATCH] D123831: [POC][WIP] Use relative include in extract-api

2022-04-15 Thread Daniel Grumberg via Phabricator via cfe-commits
dang added inline comments.



Comment at: clang/lib/ExtractAPI/ExtractAPIConsumer.cpp:65
+  // Matches framework include patterns
+  const llvm::Regex Rule("/(.+)\\.framework/(.+)?Headers/(.+)");
+  StringRef WorkingDir = CI.getFileSystemOpts().WorkingDir;

This does rely on the path separator being "/". If stick with this regex, do we 
need to convert all paths to POSIX format? I think the best thing to do is to 
iterate through the given path components and match for just "(.+)\\.framework" 
to match just the framework name and the use the base name of the file directly 
instead of matching it via the regex as well...



Comment at: clang/lib/ExtractAPI/ExtractAPIConsumer.cpp:185-186
+ CI.getPreprocessor().getHeaderSearchInfo().search_dir_range()) {
+  if (!DL.isHeaderMap())
+continue;
+

Not sure that just accounting for the header map case is the correct thing to 
do here. Ideally we would like to know what the include string was, e.g. 
 and match that with how we included one of the 
original files. This would account for all remapping functionality.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire created this revision.
junaire added reviewers: aaron.ballman, rsmith, erichkeane, dblaikie, rjmccall.
Herald added a project: All.
junaire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Because lambda will create its own scope, so we shouldn't consider variables
defined with the same name as redefinition error, if the new one is in a
lambda.

After this patch, clang is supposed to accept code below:

void foo() {

  for (int x = [] { int x = 0; return x; }(); ;) ;

}

Fixes https://github.com/llvm/llvm-project/issues/54913


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123840

Files:
  clang/lib/Sema/IdentifierResolver.cpp
  clang/test/SemaCXX/cxx1z-init-statement.cpp


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Sema/init-randomized-struct.c:30
+} __attribute__((randomize_layout));
+
+struct other_test t5 = { .a = foo, .b[0] = foo }; // Okay

Perhaps test an empty struct with randomize_layout and a struct with one field 
with randomize_layout?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[PATCH] D123837: [C++20] [Modules] Judge isInCurrentModule currently

2022-04-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 423030.
ChuanqiXu added a comment.

Fix tests


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

https://reviews.llvm.org/D123837

Files:
  clang/include/clang/Basic/Module.h
  clang/lib/Sema/SemaLookup.cpp
  clang/test/CXX/module/module.import/p2.cpp
  clang/test/Modules/cxx20-10-1-ex2.cpp


Index: clang/test/Modules/cxx20-10-1-ex2.cpp
===
--- clang/test/Modules/cxx20-10-1-ex2.cpp
+++ clang/test/Modules/cxx20-10-1-ex2.cpp
@@ -56,7 +56,14 @@
 int &c = n; // expected-error {{use of undeclared identifier}}
 
 //--- std10-1-ex2-tu7.cpp
+// expected-no-diagnostics
 module B:X3; // does not implicitly import B
-import :X2;  // X2 is an implementation so exports nothing.
- // error: n not visible here.
-int &c = n;  // expected-error {{use of undeclared identifier }}
+import : X2; // X2 is an implementation unit import B.
+// According to [module.import]p7:
+//   Additionally, when a module-import-declaration in a module unit of some
+//   module M imports another module unit U of M, it also imports all 
+//   translation units imported by non-exported module-import-declarations in
+//   the module unit purview of U.
+//
+// So B is imported in B:X3 due to B:X2 imported B. So n is visible here.
+int &c = n;
Index: clang/test/CXX/module/module.import/p2.cpp
===
--- /dev/null
+++ clang/test/CXX/module/module.import/p2.cpp
@@ -0,0 +1,21 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -std=c++20 %t/impl.cppm -emit-module-interface -o 
%t/M-impl.pcm
+// RUN: %clang_cc1 -std=c++20 %t/M.cppm -emit-module-interface 
-fprebuilt-module-path=%t -o %t/M.pcm
+// RUN: %clang_cc1 -std=c++20 %t/Use.cpp -fprebuilt-module-path=%t -verify 
-fsyntax-only
+
+//--- impl.cppm
+module M : impl;
+class A {};
+
+//--- M.cppm
+export module M;
+import : impl;
+export A f();
+
+//--- Use.cpp
+import M;
+void test() {
+  A a; // expected-error {{unknown type name 'A'}}
+}
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -1561,12 +1561,11 @@
 static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
   // If M is the global module fragment of a module that we've not yet finished
   // parsing, then it must be part of the current module.
-  // If it's a partition, then it must be visible to an importer (since only
-  // another partition or the named module can import it).
-  return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
- (M->Kind == Module::GlobalModuleFragment && !M->Parent) ||
- M->Kind == Module::ModulePartitionInterface ||
- M->Kind == Module::ModulePartitionImplementation;
+  if (M->isGlobalModule() && !M->Parent)
+return true;
+
+  return M->getPrimaryModuleInterfaceName() ==
+ Module::getPrimaryModuleInterfaceName(LangOpts.CurrentModule);
 }
 
 bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
Index: clang/include/clang/Basic/Module.h
===
--- clang/include/clang/Basic/Module.h
+++ clang/include/clang/Basic/Module.h
@@ -534,13 +534,13 @@
 return Kind == ModuleInterfaceUnit || isModulePartition();
   }
 
+  static StringRef getPrimaryModuleInterfaceName(StringRef Name) {
+return Name.split(':').first;
+  }
+
   /// Get the primary module interface name from a partition.
   StringRef getPrimaryModuleInterfaceName() const {
-if (isModulePartition()) {
-  auto pos = Name.find(':');
-  return StringRef(Name.data(), pos);
-}
-return Name;
+return getPrimaryModuleInterfaceName(getTopLevelModuleName());
   }
 
   /// Retrieve the full name of this module, including the path from


Index: clang/test/Modules/cxx20-10-1-ex2.cpp
===
--- clang/test/Modules/cxx20-10-1-ex2.cpp
+++ clang/test/Modules/cxx20-10-1-ex2.cpp
@@ -56,7 +56,14 @@
 int &c = n; // expected-error {{use of undeclared identifier}}
 
 //--- std10-1-ex2-tu7.cpp
+// expected-no-diagnostics
 module B:X3; // does not implicitly import B
-import :X2;  // X2 is an implementation so exports nothing.
- // error: n not visible here.
-int &c = n;  // expected-error {{use of undeclared identifier }}
+import : X2; // X2 is an implementation unit import B.
+// According to [module.import]p7:
+//   Additionally, when a module-import-declaration in a module unit of some
+//   module M imports another module unit U of M, it also imports all 
+//   translation units imported by non-exported module-import-declarations in
+//   the module unit purview of U.
+//
+// So B is imported in B:X3 due to B:X2 imported B. So n is visible here.
+int &c = n;
Index: clang/test/CXX/module/module.import/p2.cp

[clang] 5206c2c - [Driver] Move Lanai IAS enabling to Generic_GCC::IsIntegratedAssemblerDefault, NFC

2022-04-15 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2022-04-15T03:55:59-04:00
New Revision: 5206c2c167ed8826bf233d0e424a87c5e11bc807

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

LOG: [Driver] Move Lanai IAS enabling to 
Generic_GCC::IsIntegratedAssemblerDefault, NFC

Reviewed By: MaskRay, jpienaar

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/Lanai.h

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index bc681e4d180ef..ae848cfe81c93 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2813,6 +2813,7 @@ bool Generic_GCC::IsIntegratedAssemblerDefault() const {
   case llvm::Triple::bpfeb:
   case llvm::Triple::csky:
   case llvm::Triple::hexagon:
+  case llvm::Triple::lanai:
   case llvm::Triple::m68k:
   case llvm::Triple::mips:
   case llvm::Triple::mipsel:

diff  --git a/clang/lib/Driver/ToolChains/Lanai.h 
b/clang/lib/Driver/ToolChains/Lanai.h
index dc04b0cfe2ee1..33701f7cc0454 100644
--- a/clang/lib/Driver/ToolChains/Lanai.h
+++ b/clang/lib/Driver/ToolChains/Lanai.h
@@ -29,8 +29,6 @@ class LLVM_LIBRARY_VISIBILITY LanaiToolChain : public 
Generic_ELF {
   void addLibStdCxxIncludePaths(
   const llvm::opt::ArgList &DriverArgs,
   llvm::opt::ArgStringList &CC1Args) const override {}
-
-  bool IsIntegratedAssemblerDefault() const override { return true; }
 };
 
 } // end namespace toolchains



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


[PATCH] D123836: [Driver] Move Lanai IAS enabling to Generic_GCC::IsIntegratedAssemblerDefault, NFC

2022-04-15 Thread Brad Smith 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 rG5206c2c167ed: [Driver] Move Lanai IAS enabling to 
Generic_GCC::IsIntegratedAssemblerDefault… (authored by brad).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123836

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Lanai.h


Index: clang/lib/Driver/ToolChains/Lanai.h
===
--- clang/lib/Driver/ToolChains/Lanai.h
+++ clang/lib/Driver/ToolChains/Lanai.h
@@ -29,8 +29,6 @@
   void addLibStdCxxIncludePaths(
   const llvm::opt::ArgList &DriverArgs,
   llvm::opt::ArgStringList &CC1Args) const override {}
-
-  bool IsIntegratedAssemblerDefault() const override { return true; }
 };
 
 } // end namespace toolchains
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2813,6 +2813,7 @@
   case llvm::Triple::bpfeb:
   case llvm::Triple::csky:
   case llvm::Triple::hexagon:
+  case llvm::Triple::lanai:
   case llvm::Triple::m68k:
   case llvm::Triple::mips:
   case llvm::Triple::mipsel:


Index: clang/lib/Driver/ToolChains/Lanai.h
===
--- clang/lib/Driver/ToolChains/Lanai.h
+++ clang/lib/Driver/ToolChains/Lanai.h
@@ -29,8 +29,6 @@
   void addLibStdCxxIncludePaths(
   const llvm::opt::ArgList &DriverArgs,
   llvm::opt::ArgStringList &CC1Args) const override {}
-
-  bool IsIntegratedAssemblerDefault() const override { return true; }
 };
 
 } // end namespace toolchains
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2813,6 +2813,7 @@
   case llvm::Triple::bpfeb:
   case llvm::Triple::csky:
   case llvm::Triple::hexagon:
+  case llvm::Triple::lanai:
   case llvm::Triple::m68k:
   case llvm::Triple::mips:
   case llvm::Triple::mipsel:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80344: [Windows SEH]: HARDWARE EXCEPTION HANDLING (MSVC -EHa) - Part 1

2022-04-15 Thread Bo Wang via Phabricator via cfe-commits
bowang added a comment.

> Hi, this patch is just part-1 of Windows SEH feature support.  Part-2 work 
> had been sitting in https://reviews.llvm.org/D102817/new/ since last May 
> 2021.  It's been reviewed, and feedbacks had been addressed. but nobody has 
> approved it.  To handle Hardware Exception in Clang & LLVM, we both patches 
> in.  thanks.

Thanks for the feedback. This feature is really useful.

We are attempting to switch from MSVC to Clang company-wise. We resolved most 
issues but lastly got stuck by Clang not supporting SEH. I believe we are not 
an unique case running into this issue. I'd be very happy to see this feature 
get merged in.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80344

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


[PATCH] D113545: [C++20] [Module] Support reachable definition initially/partially

2022-04-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 423044.
ChuanqiXu marked 18 inline comments as done.
ChuanqiXu added a comment.
Herald added a subscriber: MaskRay.

Address @rsmith's comments.


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

https://reviews.llvm.org/D113545

Files:
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/Module.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Sema/Lookup.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  
clang/test/CXX/basic/basic.lookup/basic.lookup.argdep/Inputs/Friend-in-reachable-class.cppm
  
clang/test/CXX/basic/basic.lookup/basic.lookup.argdep/p4-friend-in-reachable-class.cpp
  clang/test/CXX/basic/basic.scope/basic.scope.namespace/p2.cpp
  clang/test/CXX/module/module.import/p2.cpp
  clang/test/CXX/module/module.interface/Inputs/p7.cppm
  clang/test/CXX/module/module.interface/p2.cpp
  clang/test/CXX/module/module.interface/p7.cpp
  clang/test/CXX/module/module.reach/Inputs/p4/bar.cppm
  clang/test/CXX/module/module.reach/Inputs/p4/foo.cppm
  clang/test/CXX/module/module.reach/Inputs/p5-A.cppm
  clang/test/CXX/module/module.reach/p2.cpp
  clang/test/CXX/module/module.reach/p4/TransitiveImport.cpp
  clang/test/CXX/module/module.reach/p5.cpp
  clang/test/CXX/module/module.unit/p7/t6.cpp
  clang/test/CXX/modules-ts/basic/basic.link/p2/other.cpp
  clang/test/Modules/Inputs/Reachability-Private/Private.cppm
  clang/test/Modules/Inputs/Reachability-func-default-arg/func_default_arg.cppm
  clang/test/Modules/Inputs/Reachability-func-ret/func_ret.cppm
  
clang/test/Modules/Inputs/Reachability-template-default-arg/template_default_arg.cppm
  clang/test/Modules/Inputs/Reachability-template-instantiation/Templ.cppm
  clang/test/Modules/Inputs/Reachability-template-instantiation/Templ.h
  clang/test/Modules/Inputs/Reachability-template-instantiation/Use.cppm
  clang/test/Modules/Inputs/Reachability-using-templates/mod-templates.cppm
  clang/test/Modules/Inputs/Reachability-using/mod.cppm
  clang/test/Modules/Inputs/derived_class/bar.h
  clang/test/Modules/Inputs/derived_class/foo.cppm
  clang/test/Modules/Inputs/explicitly-specialized-template/X.cppm
  clang/test/Modules/Inputs/explicitly-specialized-template/foo.h
  clang/test/Modules/Inputs/template-function-specialization/foo.cppm
  clang/test/Modules/Inputs/template_default_argument/B.cppm
  clang/test/Modules/Inputs/template_default_argument/templ.h
  clang/test/Modules/Reachability-Private.cpp
  clang/test/Modules/Reachability-func-default-arg.cpp
  clang/test/Modules/Reachability-func-ret.cpp
  clang/test/Modules/Reachability-template-default-arg.cpp
  clang/test/Modules/Reachability-template-instantiation.cpp
  clang/test/Modules/Reachability-using-templates.cpp
  clang/test/Modules/Reachability-using.cpp
  clang/test/Modules/cxx20-10-1-ex2.cpp
  clang/test/Modules/derived_class.cpp
  clang/test/Modules/explicitly-specialized-template.cpp
  clang/test/Modules/module-private.cpp
  clang/test/Modules/template-function-specialization.cpp
  clang/test/Modules/template_default_argument.cpp

Index: clang/test/Modules/template_default_argument.cpp
===
--- /dev/null
+++ clang/test/Modules/template_default_argument.cpp
@@ -0,0 +1,9 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: %clang_cc1 -std=c++20 %S/Inputs/template_default_argument/B.cppm -emit-module-interface -o %t/B.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %s -fsyntax-only -verify
+// expected-no-diagnostics
+import B;
+auto foo() {
+  return bar();
+}
Index: clang/test/Modules/template-function-specialization.cpp
===
--- /dev/null
+++ clang/test/Modules/template-function-specialization.cpp
@@ -0,0 +1,18 @@
+// RUN: rm -fr %t
+// RUN: mkdir %t
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %S/Inputs/template-function-specialization/foo.cppm -o %t/foo.pcm
+// RUN: %clang_cc1 -std=c++20 -fprebuilt-module-path=%t %s -verify -fsyntax-only
+import foo;
+void use() {
+  foo();
+  foo();
+  foo2(); // expected-error {{missing '#include'; 'foo2' must be declared before it is used}}
+ // expected-note@* {{declaration here is not visible}}
+  foo2();   // expected-error {{missing '#include'; 'foo2' must be declared before it is used}}
+ // expected-note@* {{declaration here is not visible}}
+  foo3();
+  foo3();
+
+  foo4();
+  foo4();
+}
Index: clang/test/Modules/module-private.cpp
==

[PATCH] D113545: [C++20] [Module] Support reachable definition initially/partially

2022-04-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

@rsmith Thanks for your valuable input!




Comment at: clang/lib/Sema/SemaLookup.cpp:2000-2004
+  // Class and enumeration member names can be found by name lookup in any
+  // context in which a definition of the type is reachable.
+  if (auto *ECD = dyn_cast(ND))
+return getSema().hasReachableDeclaration(
+cast(ECD->getDeclContext()));

rsmith wrote:
> I don't think this is quite right. Given:
> 
> ```
> export module M {
> export enum E1 { e1 };
> enum E2 { e2 };
> export using E2U = E2;
> enum E3 { e3 };
> export E3 f();
> ```
> 
> ... the intent is:
> 
> ```
> import M;
> int main() {
>   auto a = E1::e1; // OK, namespace-scope name E1 is visible and e1 is 
> reachable
>   auto b = e1; // OK, namespace-scope name e1 is visible
>   auto c = E2::e2; // error, namespace-scope name E2 is not visible
>   auto d = e2; // error, namespace-scope name e2 is not visible
>   auto e = E2U::e2; // OK, namespace-scope name E2U is visible and E2::e2 is 
> reachable
>   auto f = E3::e3; // error, namespace-scope name E3 is not visible
>   auto g = e3; // error, namespace-scope name e3 is not visible
>   auto h = decltype(f())::e3; // OK, namespace-scope name f is visible and 
> E3::e3 is reachable
> }
> ```
> 
> Instead of doing the check in this function, I think we need to consider the 
> scope in which we're doing a lookup: if that scope is a class or enumeration 
> scope, and the class or enumeration has a reachable definition, then we don't 
> do any visibility checks for its members.
Oh, your example makes sense. The current implementation would accept `d` and 
`g` unexpectedly. I spent some time to look into this one. And I find it is not 
so easy to fix. I left a FIXME below and I would file an issue if this patch 
landed. Do you think this is OK?

BTW, I feel like the wording of spec need to be adjusted too. From the wording, 
I feel like `d` and `g` should be accepted.



Comment at: clang/lib/Sema/SemaLookup.cpp:3754
+  //  reachable definition in the set of associated entities,
+  if (AssociatedClasses.count(RD) && hasReachableDeclaration(D)) {
 Visible = true;

rsmith wrote:
> We should look for a reachable definition here, not a reachable declaration.
Yeah, from the wording it should be reachable definition. But it would cause 
many failures if I write hasReachableDefinition/hasVisibleDefinition here. So 
it looks like a legacy defect. I chose to follow the original style here.


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

https://reviews.llvm.org/D113545

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


[PATCH] D123850: [Clang] Fix Unevaluated Lambdas Backport to Clang 14.0.1

2022-04-15 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a subscriber: martong.
Herald added a reviewer: shafik.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Unlike other types, when lambdas are instanciated,
they are recreated from scratch.
When an unevaluated lambdas appear in the type of a function,
parameter it is instanciated in the wrong declaration context,
as parameters are transformed before the function.

To support lambda in function parameters, we try to
compute whether they are dependant without looking at the
declaration context.

This is a short term stopgap solution to avoid clang
iceing. A better fix might be to inject some kind of
transparent declaration with correctly computed dependency
for function parameters, variable templates, etc.

Fixes https://github.com/llvm/llvm-project/issues/50376
Fixes https://github.com/llvm/llvm-project/issues/51414
Fixes https://github.com/llvm/llvm-project/issues/51416
Fixes https://github.com/llvm/llvm-project/issues/51641
Fixes https://github.com/llvm/llvm-project/issues/54296


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123850

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/SemaCXX/lambda-unevaluated.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1021,7 +1021,11 @@
 
   Lambdas in unevaluated contexts
   https://wg21.link/p0315r4";>P0315R4
-  Partial
+  
+Partial
+  temp.deduct/9 is not implemented yet.
+
+  
 
 
 
Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5824,6 +5824,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_FALSE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
@@ -5843,6 +5844,7 @@
   std::distance(FromL->decls().begin(), FromL->decls().end());
   EXPECT_NE(ToLSize, 0u);
   EXPECT_EQ(ToLSize, FromLSize);
+  EXPECT_TRUE(FromL->isDependentLambda());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, LambdaInGlobalScope) {
Index: clang/test/SemaCXX/lambda-unevaluated.cpp
===
--- clang/test/SemaCXX/lambda-unevaluated.cpp
+++ clang/test/SemaCXX/lambda-unevaluated.cpp
@@ -30,6 +30,27 @@
 auto e = g(0); // expected-error{{no matching function for call}}
 // expected-note@-2 {{substitution failure}}
 
+template 
+auto foo(decltype([] {
+  return [] { return T(); }();
+})) {}
+
+void test() {
+  foo({});
+}
+
+template 
+struct C {
+  template 
+  auto foo(decltype([] {
+return [] { return T(); }();
+  })) {}
+};
+
+void test2() {
+  C{}.foo({});
+}
+
 namespace PR52073 {
 // OK, these are distinct functions not redefinitions.
 template void f(decltype([]{})) {} // expected-note {{candidate}}
@@ -40,6 +61,62 @@
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 template void g(const char (*)[([]{ return N; })()]) {} // expected-note {{candidate}}
 // FIXME: We instantiate the lambdas into the context of the function template,
-// so we think they're dependent and can't evaluate a call to them.
+//  so we think they're dependent and can't evaluate a call to them.
 void use_g() { g<6>(&"hello"); } // expected-error {{no matching function}}
 }
+
+namespace GH51416 {
+
+template 
+struct A {
+  void spam(decltype([] {}));
+};
+
+template 
+void A::spam(decltype([] {})) // expected-error{{out-of-line definition of 'spam' does not match}}
+{}
+
+struct B {
+  template 
+  void spam(decltype([] {}));
+};
+
+template 
+void B::spam(decltype([] {})) {} // expected-error{{out-of-line definition of 'spam' does not match}}
+
+} // namespace GH51416
+
+namespace GH50376 {
+
+template 
+struct foo_t {// expected-note 2{{candidate constructor}}
+  foo_t(T ptr) {} // expected-note{{candidate constructor}}
+};
+
+template 
+using alias = foo_t;
+
+template 
+auto fun(T const &t) -> alias {
+  return alias{t}; // expected-error{{no viable conversion from returned value of type 'alias<...>'}}
+}
+
+void f() {
+  int i;
+  auto const error = fun(i); // expected-note{{in instantiation}}
+}
+
+} // namespace GH50376
+
+namespace GH51414 {
+templa

[PATCH] D123850: [Clang] Fix Unevaluated LambdasBackport to Clang 14.0.1

2022-04-15 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

@tstellar I wasn't sure what the procedure was for backporting fixes, so I made 
a PR. I think your suggestion of keeping the old signature works well.
This also modifies the serialized AST, is that an issue for backports? (If it 
is, I'm not sure i see a way to move forward with this!)

Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123850

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


[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2022-04-15 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.
Herald added a subscriber: MaskRay.
Herald added a project: All.

Is it expected that `__FLT_EVAL_METHOD__` is not set at all anymore by default 
after this change?


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

https://reviews.llvm.org/D109239

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


[PATCH] D123345: Treat `std::move`, `forward`, and `move_if_noexcept` as builtins.

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

In D123345#3452933 , @rsmith wrote:

> In D123345#3452496 , @aaron.ballman 
> wrote:
>
>> Do you have ideas on how we can improve the debugging checkpoint behavior 
>> (if at all)?
>
> I think we just live with it, like we do for other builtin functions. (There 
> might be things we can do by emitting inlining info into the debug info. If 
> we do that, we should presumably do it for all builtin lib functions.)

Okie dokie, so be it.

The changes LGTM aside from a previous question about diagnostic wording (feel 
free to accept the suggestion or not as you see fit). Thanks for working on 
this!




Comment at: clang/docs/ReleaseNotes.rst:121-124
+- Improved ``-O0`` code generation for calls to ``std::move``, 
``std::forward``,
+  and ``std::move_if_noexcept``. These are now treated as compiler builtins and
+  implemented directly, rather than instantiating the definition from the
+  standard library.

Probably worth moving down to the C++ language changes section because it's C++ 
specific.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6577-6578
+// FIXME: This should also be in -Wc++23-compat once we have it.
+def warn_use_of_unaddressable_function : Warning<
+  "taking address of non-addressable standard library function">,
+  InGroup;

aaron.ballman wrote:
> Thank you for making this one on by default :-)
Thoughts on this one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123345

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122983#3452994 , @rsmith wrote:

> In D122983#3451920 , @erichkeane 
> wrote:
>
>> I think Aaron's approach provides a proper 'depreciation' period in our 
>> compiler, as best as we have the ability to do.
>
> We've been warning by default for a decade that this code is not valid in 
> C99; that was our deprecation period.

I thought about this perspective a bunch overnight and I think I agree that 
this is reasonable given that the warning explicitly calls the code out as 
being *invalid*.

> If the aim is to provide a deprecation period, the end goal should be that in 
> some future Clang version we complete the transition and change the C99 
> default to reject too. Otherwise, that's not a deprecation period, that's a 
> permanent language extension in our C99 mode -- and it seems capricious to 
> provide that extension by default in C99 mode but not C11 / C17 mode. Given 
> that this extension is, well, bad, I think we shouldn't be providing it by 
> default anywhere. It's not hard for people to turn the warning flag off, and 
> people intentionally using this in C99 onwards probably already have done so.

FWIW, I misunderstood your original suggestion:

> I think we should just make this an error by default in C99 onwards;

I thought you meant this should be an *error* (not a warning defaulting to an 
error) in C99 and later. That would be too aggressive of an approach for me to 
support because it gives no upgrade path to users to easily get onto Clang 15. 
Now that I understand you better, I like your approach and rationale.


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

https://reviews.llvm.org/D122983

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


[PATCH] D123826: Fix size of flexible array initializers, and re-enable assertions.

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

Couple nits, otherwise LGTM.




Comment at: clang/lib/AST/Decl.cpp:2731
+return false;
+  auto *List = dyn_cast(getInit()->IgnoreParens());
+  if (!List)





Comment at: clang/lib/AST/Decl.cpp:2732
+  auto *List = dyn_cast(getInit()->IgnoreParens());
+  if (!List)
+return false;





Comment at: clang/lib/AST/Decl.cpp:2735
+  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
+  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
+  if (!InitTy)

Same here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123826

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


[clang] 33d3fc4 - [C89/C2x] Diagnose calls to a function without a prototype but passes arguments

2022-04-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-15T09:08:54-04:00
New Revision: 33d3fc4466479285121cbb1a62db249454da0bda

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

LOG: [C89/C2x] Diagnose calls to a function without a prototype but passes 
arguments

This catches places where a function without a prototype is
accidentally used, potentially passing an incorrect number of
arguments, and is a follow-up to the work done in
https://reviews.llvm.org/D122895 and described in the RFC
(https://discourse.llvm.org/t/rfc-enabling-wstrict-prototypes-by-default-in-c).
The diagnostic is grouped under the new -Wdeprecated-non-prototypes
warning group and is enabled by default.

The diagnostic is disabled if the function being called was implicitly
declared (the user already gets an on-by-default warning about the
creation of the implicit function declaration, so no need to warn them
twice on the same line). Additionally, the diagnostic is disabled if
the declaration of the function without a prototype was in a location
where the user explicitly disabled deprecation warnings for functions
without prototypes (this allows the provider of the API a way to
disable the diagnostic at call sites because the lack of prototype is
intentional).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaExpr.cpp
clang/test/Analysis/nullability.c
clang/test/Analysis/svalbuilder-float-cast.c
clang/test/Sema/warn-deprecated-non-prototype.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 91fc57dfac595..f5d3793225bfb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -142,8 +142,12 @@ Improvements to Clang's diagnostics
   diagnostic remains off by default but is now enabled via ``-pedantic`` due to
   it being a deprecation warning. ``-Wdeprecated-non-prototype`` will diagnose
   cases where the deprecated declarations or definitions of a function without
-  a prototype will change behavior in C2x. This diagnostic is grouped under the
-  ``-Wstrict-prototypes`` warning group, but is enabled by default.
+  a prototype will change behavior in C2x. Additionally, it will diagnose calls
+  which pass arguments to a function without a prototype. This warning is
+  enabled only when the ``-Wdeprecated-non-prototype`` option is enabled at the
+  function declaration site, which allows a developer to disable the diagnostic
+  for all callers at the point of declaration. This diagnostic is grouped under
+  the ``-Wstrict-prototypes`` warning group, but is enabled by default.
 - Clang now appropriately issues an error in C when a definition of a function
   without a prototype and with no arguments is an invalid redeclaration of a
   function with a prototype. e.g., ``void f(int); void f() {}`` is now properly

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 7ffd12317167e..6547002b378f2 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5554,6 +5554,10 @@ def warn_missing_sentinel : Warning <
   InGroup;
 def note_sentinel_here : Note<
   "%select{function|method|block}0 has been explicitly marked sentinel here">;
+def warn_strict_uses_without_prototype : Warning<
+  "passing arguments to %select{a function|%1}0 without a prototype is "
+  "deprecated in all versions of C and is not supported in C2x">,
+  InGroup;
 def warn_missing_prototype : Warning<
   "no previous prototype for function %0">,
   InGroup>, DefaultIgnore;

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index db5ab0058843f..37e54a8603f15 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -7076,6 +7076,23 @@ ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, 
NamedDecl *NDecl,
 Proto = FDecl->getType()->getAs();
 }
 
+// If we still haven't found a prototype to use but there are arguments to
+// the call, diagnose this as calling a function without a prototype.
+// However, if we found a function declaration, check to see if
+// -Wdeprecated-non-prototype was disabled where the function was declared.
+// If so, we will silence the diagnostic here on the assumption that this
+// interface is intentional and the user knows what they're doing. We will
+// also silence the diagnostic if there is a function declaration but it
+// was implicitly defined (the user already gets diagnostics about the
+// creation of the implicit function declaration, so the additional warning
+// is not helpful).
+if (!Proto && !Args.empty() &&
+(!FDecl || (!FDecl->isImplicit() &&
+ 

[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2022-04-15 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:358
+  assert(!isEmpty());
+  return begin()->From().isUnsigned();
+}

martong wrote:
> Probably it is unrelated to this patch, but
> Could it happen that `(++begin())->From().isUnsigned()` gives a different 
> signedness? Or we had a separate assertion when we  added the second `Range`? 
> The same question applies to the below two functions as well. Seems like in 
> `unite` we don't have such validity check...
>Or we had a separate assertion when we added the second Range?
I didn't find any assertion while adding.
Moreover, I'm not sure if there can happen `APSInts` of different types in a 
single `Range`. We only have `assert(From < To)` in a ctor.
>Seems like in `unite` we don't have such validity check...
Not only `unite` doesn't have such, but all the rest don't as well. We rely on 
a fact that the caller garantees the validity of RangeSet by using 
`AdjustmentType`.
But, yes, it's worth to make some checks.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:687
+
+  if (IsConversion && (!IsPromotion || !What.isUnsigned()))
+return makePersistent(convertTo(What, Ty));

martong wrote:
> Could you please explain why do we need the `|| !What.isUnsigned()` part of 
> the condition?
> 
> This would make much more sense to me:
> ```
> if (IsConversion && !IsPromotion)
> return makePersistent(convertTo(What, Ty));
> ```
Look. Here we handle 2 cases:

  - `IsConversion && !IsPromotion`. In this case we handle changing a sign with 
same bitwidth: char -> uchar, uint -> int. Here we convert //negatives //to 
//positives //and //positives which is out of range// to //negatives//. We use 
`convertTo` function for that.
 
  - `IsConversion && IsPromotion && !What.isUnsigned()`. In this case we handle 
changing a sign from signeds to unsigneds with higher bitwidth: char -> uint, 
int-> uint64. The point is that we also need convert //negatives //to 
//positives //and use `convertTo` function as well. For example, we don't need 
such a convertion when converting //unsigned //to //signed with higher 
bitwidth//, because all the values of //unsigned //is valid for the such 
//signed//.
 






Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:690
+
+  // Promotion from unsigneds to signeds/unsigneds left.
+

martong wrote:
> martong wrote:
> > I think it would be more consistent with the other operations (truncate and 
> > convert) if we had this logic in its own separate function: `promoteTo`. 
> > And this function should be called only if `isPromotion` is set (?)
> This comment is confusing, since we can get here also if
> `isConversion` is false and
> `isPromotion` is false 
Nothing confusing is here.
We have 7 main cases:
NOOP: **u -> u, s -> s**
Conversion: **u -> s, s -> u**
Truncation: **U-> u, S -> s**
Promotion: `u->U`, `s -> S`
Truncation + Conversion: **U -> s, S -> u**
Promotion + Conversion: **s -> U**, `u -> S`

As you can see, we've handled all the **bolds** above this line .
So only promotions from //unsigneds// left. That means, `isPromotion` never 
should be `false` here. We could add an assertion here if you want.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:690-711
+  // Promotion from unsigneds to signeds/unsigneds left.
+
+  using llvm::APInt;
+  using llvm::APSInt;
+  ContainerType Result;
+  // We definitely know the size of the result set.
+  Result.reserve(What.size());

ASDenysPetrov wrote:
> martong wrote:
> > martong wrote:
> > > I think it would be more consistent with the other operations (truncate 
> > > and convert) if we had this logic in its own separate function: 
> > > `promoteTo`. And this function should be called only if `isPromotion` is 
> > > set (?)
> > This comment is confusing, since we can get here also if
> > `isConversion` is false and
> > `isPromotion` is false 
> Nothing confusing is here.
> We have 7 main cases:
> NOOP: **u -> u, s -> s**
> Conversion: **u -> s, s -> u**
> Truncation: **U-> u, S -> s**
> Promotion: `u->U`, `s -> S`
> Truncation + Conversion: **U -> s, S -> u**
> Promotion + Conversion: **s -> U**, `u -> S`
> 
> As you can see, we've handled all the **bolds** above this line .
> So only promotions from //unsigneds// left. That means, `isPromotion` never 
> should be `false` here. We could add an assertion here if you want.
That makes sense. I'll do.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:792
+  //unite -> uchar(-2, 1)
+  auto CastRange = [Ty, &VF = ValueFactory](const Range &R) -> Bounds {
+// Get bounds of the given range.

martong wrote:
> Why not `-> Range`?
Because `Range` requires `from < to` in its contract. But I need to store the 
values after conversions. You 

[clang] f263dac - [clang][parse] NFCI: Use FileEntryRef in Parser::ParseModuleImport()

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T15:16:17+02:00
New Revision: f263dac4465c251e37af9787baf5e9f56138e369

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

LOG: [clang][parse] NFCI: Use FileEntryRef in Parser::ParseModuleImport()

This patch removes use of the deprecated `DirectoryEntry::getName()` from 
`Parser` by using `{File,Directory}EntryRef` instead.

Reviewed By: bnbarham

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

Added: 


Modified: 
clang/lib/Parse/Parser.cpp

Removed: 




diff  --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index 2550cdd9f5bbf..229af18f7 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -2518,8 +2518,8 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   // the header is parseable. Emit a warning to make the user aware.
   if (IsObjCAtImport && AtLoc.isValid()) {
 auto &SrcMgr = PP.getSourceManager();
-auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
-if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
+auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
+if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
   .endswith(".framework"))
   Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
   }



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


[clang] 99b4874 - [clang] NFCI: Use DirectoryEntryRef in collectIncludePCH

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T15:16:17+02:00
New Revision: 99b4874a53cf4cd39a164a63b5505baace825d7c

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

LOG: [clang] NFCI: Use DirectoryEntryRef in collectIncludePCH

This patch removes use of the deprecated `DirectoryEntry::getName()` from 
`collectIncludePCH` by using `{File,Directory}EntryRef` instead.

Reviewed By: bnbarham

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 2465a7e2453be..bb896449b621f 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -232,7 +232,7 @@ static void collectIncludePCH(CompilerInstance &CI,
 
   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
   FileManager &FileMgr = CI.getFileManager();
-  auto PCHDir = FileMgr.getDirectory(PCHInclude);
+  auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
   if (!PCHDir) {
 MDC->addFile(PCHInclude);
 return;
@@ -240,7 +240,7 @@ static void collectIncludePCH(CompilerInstance &CI,
 
   std::error_code EC;
   SmallString<128> DirNative;
-  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
+  llvm::sys::path::native(PCHDir->getName(), DirNative);
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   SimpleASTReaderListener Validator(CI.getPreprocessor());
   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;



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


[clang] 9d98f58 - [clang][CodeGen] NFCI: Use FileEntryRef

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T15:16:17+02:00
New Revision: 9d98f58959b12b6ddab5ac10453e1464bb830e96

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

LOG: [clang][CodeGen] NFCI: Use FileEntryRef

This patch removes use of the deprecated `DirectoryEntry::getName()` from 
clangCodeGen by using `{File,Directory}EntryRef` instead.

Reviewed By: bnbarham

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

Added: 


Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGObjCGNU.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index c18dbccf82936..4bfa8461eefea 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -519,8 +519,9 @@ void CGDebugInfo::CreateCompileUnit() {
   // a relative path, so we look into the actual file entry for the main
   // file to determine the real absolute path for the file.
   std::string MainFileDir;
-  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-MainFileDir = std::string(MainFile->getDir()->getName());
+  if (Optional MainFile =
+  SM.getFileEntryRefForID(SM.getMainFileID())) {
+MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);
   llvm::sys::path::append(MainFileDirSS, MainFileName);

diff  --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index 0301076f26f46..ec459f07f307d 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -3862,9 +3862,10 @@ llvm::Function *CGObjCGNU::ModuleInitFunction() {
 
 // The path to the source file where this module was declared
 SourceManager &SM = CGM.getContext().getSourceManager();
-const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
+Optional mainFile =
+SM.getFileEntryRefForID(SM.getMainFileID());
 std::string path =
-  (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
+(mainFile->getDir().getName() + "/" + mainFile->getName()).str();
 module.add(MakeConstantString(path, ".objc_source_file_name"));
 module.add(symtab);
 



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


[PATCH] D123767: [clang][parse] NFCI: Use FileEntryRef in Parser::ParseModuleImport()

2022-04-15 Thread Jan Svoboda 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 rGf263dac4465c: [clang][parse] NFCI: Use FileEntryRef in 
Parser::ParseModuleImport() (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123767

Files:
  clang/lib/Parse/Parser.cpp


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2518,8 +2518,8 @@
   // the header is parseable. Emit a warning to make the user aware.
   if (IsObjCAtImport && AtLoc.isValid()) {
 auto &SrcMgr = PP.getSourceManager();
-auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
-if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
+auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
+if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
   .endswith(".framework"))
   Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
   }


Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2518,8 +2518,8 @@
   // the header is parseable. Emit a warning to make the user aware.
   if (IsObjCAtImport && AtLoc.isValid()) {
 auto &SrcMgr = PP.getSourceManager();
-auto *FE = SrcMgr.getFileEntryForID(SrcMgr.getFileID(AtLoc));
-if (FE && llvm::sys::path::parent_path(FE->getDir()->getName())
+auto FE = SrcMgr.getFileEntryRefForID(SrcMgr.getFileID(AtLoc));
+if (FE && llvm::sys::path::parent_path(FE->getDir().getName())
   .endswith(".framework"))
   Diags.Report(AtLoc, diag::warn_atimport_in_framework_header);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 713e716 - [clang] NFCI: Use FileEntryRef in FileManagerTest

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T15:16:17+02:00
New Revision: 713e716cdaef1ee069f27bb71fd232a782565e0a

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

LOG: [clang] NFCI: Use FileEntryRef in FileManagerTest

This patch removes use of the deprecated `{File,Directory}Entry::getName()` 
from `FileManager` unit tests by using `{File,Directory}EntryRef` instead.

Reviewed By: bnbarham

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

Added: 


Modified: 
clang/unittests/Basic/FileManagerTest.cpp

Removed: 




diff  --git a/clang/unittests/Basic/FileManagerTest.cpp 
b/clang/unittests/Basic/FileManagerTest.cpp
index 31cb2bbac3cf2..b8b12a91483d5 100644
--- a/clang/unittests/Basic/FileManagerTest.cpp
+++ b/clang/unittests/Basic/FileManagerTest.cpp
@@ -99,22 +99,13 @@ class FileManagerTest : public ::testing::Test {
   FileManager manager;
 };
 
-// When a virtual file is added, its getDir() field is set correctly
-// (not NULL, correct name).
+// When a virtual file is added, its getDir() field has correct name.
 TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
-  const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
-  ASSERT_TRUE(file != nullptr);
-
-  const DirectoryEntry *dir = file->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ(".", dir->getName());
-
-  file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
-  ASSERT_TRUE(file != nullptr);
+  FileEntryRef file = manager.getVirtualFileRef("foo.cpp", 42, 0);
+  EXPECT_EQ(".", file.getDir().getName());
 
-  dir = file->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("x/y", dir->getName());
+  file = manager.getVirtualFileRef("x/y/z.cpp", 42, 0);
+  EXPECT_EQ("x/y", file.getDir().getName());
 }
 
 // Before any virtual file is added, no virtual directory exists.
@@ -138,16 +129,16 @@ TEST_F(FileManagerTest, 
getVirtualFileCreatesDirectoryEntriesForAncestors) {
   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
   ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
 
-  auto dir = manager.getDirectory("virtual/dir");
-  ASSERT_TRUE(dir);
-  EXPECT_EQ("virtual/dir", (*dir)->getName());
+  auto dir = manager.getDirectoryRef("virtual/dir");
+  ASSERT_THAT_EXPECTED(dir, llvm::Succeeded());
+  EXPECT_EQ("virtual/dir", dir->getName());
 
-  dir = manager.getDirectory("virtual");
-  ASSERT_TRUE(dir);
-  EXPECT_EQ("virtual", (*dir)->getName());
+  dir = manager.getDirectoryRef("virtual");
+  ASSERT_THAT_EXPECTED(dir, llvm::Succeeded());
+  EXPECT_EQ("virtual", dir->getName());
 }
 
-// getFile() returns non-NULL if a real file exists at the given path.
+// getFileRef() succeeds if a real file exists at the given path.
 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
   // Inject fake files into the file system.
   auto statCache = std::make_unique();
@@ -163,37 +154,29 @@ TEST_F(FileManagerTest, 
getFileReturnsValidFileEntryForExistingRealFile) {
 
   manager.setStatCache(std::move(statCache));
 
-  auto file = manager.getFile("/tmp/test");
-  ASSERT_TRUE(file);
-  EXPECT_EQ("/tmp/test", (*file)->getName());
+  auto file = manager.getFileRef("/tmp/test");
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ("/tmp/test", file->getName());
 
-  const DirectoryEntry *dir = (*file)->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("/tmp", dir->getName());
+  EXPECT_EQ("/tmp", file->getDir().getName());
 
 #ifdef _WIN32
-  file = manager.getFile(FileName);
-  ASSERT_TRUE(file);
-
-  dir = (*file)->getDir();
-  ASSERT_TRUE(dir != NULL);
-  EXPECT_EQ(DirName, dir->getName());
+  file = manager.getFileRef(FileName);
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ(DirName, file->getDir().getName());
 #endif
 }
 
-// getFile() returns non-NULL if a virtual file exists at the given path.
+// getFileRef() succeeds if a virtual file exists at the given path.
 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
   // Fake an empty real file system.
   manager.setStatCache(std::make_unique());
 
   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
-  auto file = manager.getFile("virtual/dir/bar.h");
-  ASSERT_TRUE(file);
-  EXPECT_EQ("virtual/dir/bar.h", (*file)->getName());
-
-  const DirectoryEntry *dir = (*file)->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("virtual/dir", dir->getName());
+  auto file = manager.getFileRef("virtual/dir/bar.h");
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ("virtual/dir/bar.h", file->getName());
+  EXPECT_EQ("virtual/dir", file->getDir().getName());
 }
 
 // getFile() returns 
diff erent FileEntries for 
diff erent paths when



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.l

[clang] 0b09b5d - [clang][lex] NFC: Use FileEntryRef in PreprocessorLexer::getFileEntry()

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T15:16:17+02:00
New Revision: 0b09b5d44837ea71c6bf017607b33f283c4417c6

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

LOG: [clang][lex] NFC: Use FileEntryRef in PreprocessorLexer::getFileEntry()

This patch changes the return type of `PreprocessorLexer::getFileEntry()` so 
that its clients may stop using the deprecated APIs of `FileEntry`.

Reviewed By: bnbarham

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

Added: 


Modified: 
clang/include/clang/Lex/PreprocessorLexer.h
clang/lib/Lex/PreprocessorLexer.cpp
clang/lib/Sema/SemaCodeComplete.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/PreprocessorLexer.h 
b/clang/include/clang/Lex/PreprocessorLexer.h
index b43197a6031cb..356b8c4098fd8 100644
--- a/clang/include/clang/Lex/PreprocessorLexer.h
+++ b/clang/include/clang/Lex/PreprocessorLexer.h
@@ -165,7 +165,7 @@ class PreprocessorLexer {
 
   /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
   /// getFileID(), this only works for lexers with attached preprocessors.
-  const FileEntry *getFileEntry() const;
+  OptionalFileEntryRefDegradesToFileEntryPtr getFileEntry() const;
 
   /// Iterator that traverses the current stack of preprocessor
   /// conditional directives (\#if/\#ifdef/\#ifndef).

diff  --git a/clang/lib/Lex/PreprocessorLexer.cpp 
b/clang/lib/Lex/PreprocessorLexer.cpp
index 5f6f4a13419be..23c80d375214c 100644
--- a/clang/lib/Lex/PreprocessorLexer.cpp
+++ b/clang/lib/Lex/PreprocessorLexer.cpp
@@ -47,6 +47,7 @@ void PreprocessorLexer::LexIncludeFilename(Token 
&FilenameTok) {
 
 /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
 /// getFileID(), this only works for lexers with attached preprocessors.
-const FileEntry *PreprocessorLexer::getFileEntry() const {
-  return PP->getSourceManager().getFileEntryForID(getFileID());
+OptionalFileEntryRefDegradesToFileEntryPtr
+PreprocessorLexer::getFileEntry() const {
+  return PP->getSourceManager().getFileEntryRefForID(getFileID());
 }

diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 9d295941234f7..c1492ff8aa33c 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -9972,7 +9972,7 @@ void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, 
bool Angled) {
   using llvm::make_range;
   if (!Angled) {
 // The current directory is on the include path for "quoted" includes.
-auto *CurFile = PP.getCurrentFileLexer()->getFileEntry();
+const FileEntry *CurFile = PP.getCurrentFileLexer()->getFileEntry();
 if (CurFile && CurFile->getDir())
   AddFilesFromIncludeDir(CurFile->getDir()->getName(), false,
  DirectoryLookup::LT_NormalDir);



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


[PATCH] D123768: [clang][CodeGen] NFCI: Use FileEntryRef

2022-04-15 Thread Jan Svoboda 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 rG9d98f58959b1: [clang][CodeGen] NFCI: Use FileEntryRef 
(authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123768

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGObjCGNU.cpp


Index: clang/lib/CodeGen/CGObjCGNU.cpp
===
--- clang/lib/CodeGen/CGObjCGNU.cpp
+++ clang/lib/CodeGen/CGObjCGNU.cpp
@@ -3862,9 +3862,10 @@
 
 // The path to the source file where this module was declared
 SourceManager &SM = CGM.getContext().getSourceManager();
-const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
+Optional mainFile =
+SM.getFileEntryRefForID(SM.getMainFileID());
 std::string path =
-  (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
+(mainFile->getDir().getName() + "/" + mainFile->getName()).str();
 module.add(MakeConstantString(path, ".objc_source_file_name"));
 module.add(symtab);
 
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -519,8 +519,9 @@
   // a relative path, so we look into the actual file entry for the main
   // file to determine the real absolute path for the file.
   std::string MainFileDir;
-  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-MainFileDir = std::string(MainFile->getDir()->getName());
+  if (Optional MainFile =
+  SM.getFileEntryRefForID(SM.getMainFileID())) {
+MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);
   llvm::sys::path::append(MainFileDirSS, MainFileName);


Index: clang/lib/CodeGen/CGObjCGNU.cpp
===
--- clang/lib/CodeGen/CGObjCGNU.cpp
+++ clang/lib/CodeGen/CGObjCGNU.cpp
@@ -3862,9 +3862,10 @@
 
 // The path to the source file where this module was declared
 SourceManager &SM = CGM.getContext().getSourceManager();
-const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
+Optional mainFile =
+SM.getFileEntryRefForID(SM.getMainFileID());
 std::string path =
-  (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
+(mainFile->getDir().getName() + "/" + mainFile->getName()).str();
 module.add(MakeConstantString(path, ".objc_source_file_name"));
 module.add(symtab);
 
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -519,8 +519,9 @@
   // a relative path, so we look into the actual file entry for the main
   // file to determine the real absolute path for the file.
   std::string MainFileDir;
-  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-MainFileDir = std::string(MainFile->getDir()->getName());
+  if (Optional MainFile =
+  SM.getFileEntryRefForID(SM.getMainFileID())) {
+MainFileDir = std::string(MainFile->getDir().getName());
 if (!llvm::sys::path::is_absolute(MainFileName)) {
   llvm::SmallString<1024> MainFileDirSS(MainFileDir);
   llvm::sys::path::append(MainFileDirSS, MainFileName);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123769: [clang] NFCI: Use DirectoryEntryRef in collectIncludePCH

2022-04-15 Thread Jan Svoboda 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 rG99b4874a53cf: [clang] NFCI: Use DirectoryEntryRef in 
collectIncludePCH (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123769

Files:
  clang/lib/Frontend/CompilerInstance.cpp


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -232,7 +232,7 @@
 
   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
   FileManager &FileMgr = CI.getFileManager();
-  auto PCHDir = FileMgr.getDirectory(PCHInclude);
+  auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
   if (!PCHDir) {
 MDC->addFile(PCHInclude);
 return;
@@ -240,7 +240,7 @@
 
   std::error_code EC;
   SmallString<128> DirNative;
-  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
+  llvm::sys::path::native(PCHDir->getName(), DirNative);
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   SimpleASTReaderListener Validator(CI.getPreprocessor());
   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;


Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -232,7 +232,7 @@
 
   StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
   FileManager &FileMgr = CI.getFileManager();
-  auto PCHDir = FileMgr.getDirectory(PCHInclude);
+  auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude);
   if (!PCHDir) {
 MDC->addFile(PCHInclude);
 return;
@@ -240,7 +240,7 @@
 
   std::error_code EC;
   SmallString<128> DirNative;
-  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
+  llvm::sys::path::native(PCHDir->getName(), DirNative);
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   SimpleASTReaderListener Validator(CI.getPreprocessor());
   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123770: [clang] NFCI: Use FileEntryRef in FileManagerTest

2022-04-15 Thread Jan Svoboda 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 rG713e716cdaef: [clang] NFCI: Use FileEntryRef in 
FileManagerTest (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123770

Files:
  clang/unittests/Basic/FileManagerTest.cpp

Index: clang/unittests/Basic/FileManagerTest.cpp
===
--- clang/unittests/Basic/FileManagerTest.cpp
+++ clang/unittests/Basic/FileManagerTest.cpp
@@ -99,22 +99,13 @@
   FileManager manager;
 };
 
-// When a virtual file is added, its getDir() field is set correctly
-// (not NULL, correct name).
+// When a virtual file is added, its getDir() field has correct name.
 TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
-  const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
-  ASSERT_TRUE(file != nullptr);
-
-  const DirectoryEntry *dir = file->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ(".", dir->getName());
-
-  file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
-  ASSERT_TRUE(file != nullptr);
+  FileEntryRef file = manager.getVirtualFileRef("foo.cpp", 42, 0);
+  EXPECT_EQ(".", file.getDir().getName());
 
-  dir = file->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("x/y", dir->getName());
+  file = manager.getVirtualFileRef("x/y/z.cpp", 42, 0);
+  EXPECT_EQ("x/y", file.getDir().getName());
 }
 
 // Before any virtual file is added, no virtual directory exists.
@@ -138,16 +129,16 @@
   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
   ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
 
-  auto dir = manager.getDirectory("virtual/dir");
-  ASSERT_TRUE(dir);
-  EXPECT_EQ("virtual/dir", (*dir)->getName());
+  auto dir = manager.getDirectoryRef("virtual/dir");
+  ASSERT_THAT_EXPECTED(dir, llvm::Succeeded());
+  EXPECT_EQ("virtual/dir", dir->getName());
 
-  dir = manager.getDirectory("virtual");
-  ASSERT_TRUE(dir);
-  EXPECT_EQ("virtual", (*dir)->getName());
+  dir = manager.getDirectoryRef("virtual");
+  ASSERT_THAT_EXPECTED(dir, llvm::Succeeded());
+  EXPECT_EQ("virtual", dir->getName());
 }
 
-// getFile() returns non-NULL if a real file exists at the given path.
+// getFileRef() succeeds if a real file exists at the given path.
 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
   // Inject fake files into the file system.
   auto statCache = std::make_unique();
@@ -163,37 +154,29 @@
 
   manager.setStatCache(std::move(statCache));
 
-  auto file = manager.getFile("/tmp/test");
-  ASSERT_TRUE(file);
-  EXPECT_EQ("/tmp/test", (*file)->getName());
+  auto file = manager.getFileRef("/tmp/test");
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ("/tmp/test", file->getName());
 
-  const DirectoryEntry *dir = (*file)->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("/tmp", dir->getName());
+  EXPECT_EQ("/tmp", file->getDir().getName());
 
 #ifdef _WIN32
-  file = manager.getFile(FileName);
-  ASSERT_TRUE(file);
-
-  dir = (*file)->getDir();
-  ASSERT_TRUE(dir != NULL);
-  EXPECT_EQ(DirName, dir->getName());
+  file = manager.getFileRef(FileName);
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ(DirName, file->getDir().getName());
 #endif
 }
 
-// getFile() returns non-NULL if a virtual file exists at the given path.
+// getFileRef() succeeds if a virtual file exists at the given path.
 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
   // Fake an empty real file system.
   manager.setStatCache(std::make_unique());
 
   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
-  auto file = manager.getFile("virtual/dir/bar.h");
-  ASSERT_TRUE(file);
-  EXPECT_EQ("virtual/dir/bar.h", (*file)->getName());
-
-  const DirectoryEntry *dir = (*file)->getDir();
-  ASSERT_TRUE(dir != nullptr);
-  EXPECT_EQ("virtual/dir", dir->getName());
+  auto file = manager.getFileRef("virtual/dir/bar.h");
+  ASSERT_THAT_EXPECTED(file, llvm::Succeeded());
+  EXPECT_EQ("virtual/dir/bar.h", file->getName());
+  EXPECT_EQ("virtual/dir", file->getDir().getName());
 }
 
 // getFile() returns different FileEntries for different paths when
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123772: [clang][lex] NFC: Use FileEntryRef in PreprocessorLexer::getFileEntry()

2022-04-15 Thread Jan Svoboda 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 rG0b09b5d44837: [clang][lex] NFC: Use FileEntryRef in 
PreprocessorLexer::getFileEntry() (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123772

Files:
  clang/include/clang/Lex/PreprocessorLexer.h
  clang/lib/Lex/PreprocessorLexer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -9972,7 +9972,7 @@
   using llvm::make_range;
   if (!Angled) {
 // The current directory is on the include path for "quoted" includes.
-auto *CurFile = PP.getCurrentFileLexer()->getFileEntry();
+const FileEntry *CurFile = PP.getCurrentFileLexer()->getFileEntry();
 if (CurFile && CurFile->getDir())
   AddFilesFromIncludeDir(CurFile->getDir()->getName(), false,
  DirectoryLookup::LT_NormalDir);
Index: clang/lib/Lex/PreprocessorLexer.cpp
===
--- clang/lib/Lex/PreprocessorLexer.cpp
+++ clang/lib/Lex/PreprocessorLexer.cpp
@@ -47,6 +47,7 @@
 
 /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
 /// getFileID(), this only works for lexers with attached preprocessors.
-const FileEntry *PreprocessorLexer::getFileEntry() const {
-  return PP->getSourceManager().getFileEntryForID(getFileID());
+OptionalFileEntryRefDegradesToFileEntryPtr
+PreprocessorLexer::getFileEntry() const {
+  return PP->getSourceManager().getFileEntryRefForID(getFileID());
 }
Index: clang/include/clang/Lex/PreprocessorLexer.h
===
--- clang/include/clang/Lex/PreprocessorLexer.h
+++ clang/include/clang/Lex/PreprocessorLexer.h
@@ -165,7 +165,7 @@
 
   /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
   /// getFileID(), this only works for lexers with attached preprocessors.
-  const FileEntry *getFileEntry() const;
+  OptionalFileEntryRefDegradesToFileEntryPtr getFileEntry() const;
 
   /// Iterator that traverses the current stack of preprocessor
   /// conditional directives (\#if/\#ifdef/\#ifndef).


Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -9972,7 +9972,7 @@
   using llvm::make_range;
   if (!Angled) {
 // The current directory is on the include path for "quoted" includes.
-auto *CurFile = PP.getCurrentFileLexer()->getFileEntry();
+const FileEntry *CurFile = PP.getCurrentFileLexer()->getFileEntry();
 if (CurFile && CurFile->getDir())
   AddFilesFromIncludeDir(CurFile->getDir()->getName(), false,
  DirectoryLookup::LT_NormalDir);
Index: clang/lib/Lex/PreprocessorLexer.cpp
===
--- clang/lib/Lex/PreprocessorLexer.cpp
+++ clang/lib/Lex/PreprocessorLexer.cpp
@@ -47,6 +47,7 @@
 
 /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
 /// getFileID(), this only works for lexers with attached preprocessors.
-const FileEntry *PreprocessorLexer::getFileEntry() const {
-  return PP->getSourceManager().getFileEntryForID(getFileID());
+OptionalFileEntryRefDegradesToFileEntryPtr
+PreprocessorLexer::getFileEntry() const {
+  return PP->getSourceManager().getFileEntryRefForID(getFileID());
 }
Index: clang/include/clang/Lex/PreprocessorLexer.h
===
--- clang/include/clang/Lex/PreprocessorLexer.h
+++ clang/include/clang/Lex/PreprocessorLexer.h
@@ -165,7 +165,7 @@
 
   /// getFileEntry - Return the FileEntry corresponding to this FileID.  Like
   /// getFileID(), this only works for lexers with attached preprocessors.
-  const FileEntry *getFileEntry() const;
+  OptionalFileEntryRefDegradesToFileEntryPtr getFileEntry() const;
 
   /// Iterator that traverses the current stack of preprocessor
   /// conditional directives (\#if/\#ifdef/\#ifndef).
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 57a4f9b - Fix failing test case found by bots:

2022-04-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-15T09:20:16-04:00
New Revision: 57a4f9bd493bca0dc78b16951c7d3f3fadfbc2f2

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

LOG: Fix failing test case found by bots:

https://lab.llvm.org/buildbot#builders/109/builds/36683
https://lab.llvm.org/buildbot#builders/164/builds/15456
(and others)

Added: 


Modified: 
clang/test/SemaObjC/nonnull.m

Removed: 




diff  --git a/clang/test/SemaObjC/nonnull.m b/clang/test/SemaObjC/nonnull.m
index 303a201f48618..3b087b096d8f9 100644
--- a/clang/test/SemaObjC/nonnull.m
+++ b/clang/test/SemaObjC/nonnull.m
@@ -41,10 +41,8 @@ extern void func4 (void (^block1)(), void (^block2)()) 
__attribute__((nonnull(1)
   func4(0, cp1); // expected-warning {{null passed to a callee that requires a 
non-null argument}}
   func4(cp1, 0); // expected-warning {{null passed to a callee that requires a 
non-null argument}}
   
-  // Shouldn't these emit warnings?  Clang doesn't, and neither does GCC.  It
-  // seems that the checking should handle Objective-C pointers.
-  func6((NSObject*) 0); // no-warning
-  func7((NSObject*) 0); // no-warning
+  func6((NSObject*) 0); // expected-warning {{passing arguments to 'func6' 
without a prototype is deprecated in all versions of C and is not supported in 
C2x}}
+  func7((NSObject*) 0); // expected-warning {{passing arguments to 'func7' 
without a prototype is deprecated in all versions of C and is not supported in 
C2x}}
 }
 
 void func5(int) NONNULL_ATTR; //  no warning



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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire added a comment.

Hi @erichkeane , thanks for accepting this! But do you think we need to add a 
release note about it? (I'm a totally beginner so sometimes I'm confused about 
when we should do it.)  Also, Do you have any concerns about the wording? In 
fact, I am pretty embarrassed by the current wording in my commit message...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Ah, right, we SHOULD have a release note, please add one and I'll help review 
the wording.  Commit message is fine for a commit message, particularly with a 
good release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123771: [clang][lex] NFCI: Use DirectoryEntryRef in HeaderSearch::load*()

2022-04-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 marked 5 inline comments as done.
jansvoboda11 added inline comments.



Comment at: clang/lib/Lex/HeaderSearch.cpp:339
 // Search for a module map file in this directory.
-if (loadModuleMapFile(Dir.getDir(), IsSystem,
+if (loadModuleMapFile(*Dir.getDirRef(), IsSystem,
   /*IsFramework*/false) == LMM_NewlyLoaded) {

bnbarham wrote:
> I'd prefer the following since I had to specifically go and check 
> `getDirRef`, though I suppose I probably would have done so even with a 
> comment 😅 :
> ```
> // Only returns None if not a normal directory, which we just checked
> DirectoryEntryRef NormalDir = *Dir.getDirRef();
> ...loadModuleMapFile(NormalDir, ...
> ```
Fair enough.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1583
+::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
+assert(TopFrameworkDir && "Could not find the top-most framework dir");
 

bnbarham wrote:
> Can we just return false in this case, or is it definitely always a logic 
> error?
I agree returning `false` here would be better, but I wanted to keep this patch 
as NFC as possible. How about I make that change in a follow-up patch?



Comment at: clang/lib/Lex/HeaderSearch.cpp:1630
+  llvm::sys::path::parent_path(OriginalModuleMapFile))) {
+Dir = *MaybeDir;
   } else {

bnbarham wrote:
> Shouldn't need the * should it? Also doesn't seem necessary to actually check 
> here since `Dir` hasn't been set yet. Just `Dir = 
> FileMgr.getOptionalDirectoryRef...` should be fine.
Nice catch!



Comment at: clang/lib/Lex/HeaderSearch.cpp:1636
 } else {
-  Dir = File->getDir();
+  Dir = File->getLastRef().getDir();
 }

bnbarham wrote:
> I assume this is the place you mentioned in the message? (ie. to prevent 
> patch from growing even more)
Yes, that's the one.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1639
 
 StringRef DirName(Dir->getName());
 if (llvm::sys::path::filename(DirName) == "Modules") {

bnbarham wrote:
> Can't `Dir` still be `None` here? It *shouldn't* be since the directory for 
> `OriginalModuleMapFile` should exist, but I'd feel more comfortable with 
> either an early return or an assert here.
> 
> Same thing below at the switch as well.
I think `Dir` can't be `None` at this point - adding an assertion here sounds 
like a good idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123771

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 423079.
junaire added a comment.

Add a release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/IdentifierResolver.cpp
  clang/test/SemaCXX/cxx1z-init-statement.cpp


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,9 @@
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- No longer produce a wrong redefinition error if variables are defined in 
if/for/switch init statements
+  and lambda.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,9 @@
   This fixes Issue `Issue 52802 `_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed twice.
   This fixes Issue `Issue 54817 `_.
+- No longer produce a wrong redefinition error if variables are defined in if/for/switch init statements
+  and lambda.
+  This fixes `Issue 54913 `_.
 
 Improvements to Clang's diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire added a comment.

In D123840#3453903 , @erichkeane 
wrote:

> Ah, right, we SHOULD have a release note, please add one and I'll help review 
> the wording.  Commit message is fine for a commit message, particularly with 
> a good release note.

Thanks! I have updated it :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D103094: [analyzer] Implemented RangeSet::Factory::castTo function to perform promotions, truncations and conversions

2022-04-15 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 423080.
ASDenysPetrov added a comment.

Updated according to suggestions.
@martong thank you for the review.


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

https://reviews.llvm.org/D103094

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/unittests/StaticAnalyzer/RangeSetTest.cpp

Index: clang/unittests/StaticAnalyzer/RangeSetTest.cpp
===
--- clang/unittests/StaticAnalyzer/RangeSetTest.cpp
+++ clang/unittests/StaticAnalyzer/RangeSetTest.cpp
@@ -40,12 +40,18 @@
   const Range &R) {
   return OS << toString(R);
 }
+LLVM_ATTRIBUTE_UNUSED static std::ostream &operator<<(std::ostream &OS,
+  APSIntType Ty) {
+  return OS << (Ty.isUnsigned() ? "u" : "s") << Ty.getBitWidth();
+}
 
 } // namespace ento
 } // namespace clang
 
 namespace {
 
+template  constexpr bool is_signed_v = std::is_signed::value;
+
 template  struct TestValues {
   static constexpr T MIN = std::numeric_limits::min();
   static constexpr T MAX = std::numeric_limits::max();
@@ -53,7 +59,7 @@
   // which unary minus does not affect on,
   // e.g. int8/int32(0), uint8(128), uint32(2147483648).
   static constexpr T MID =
-  std::is_signed::value ? 0 : ~(static_cast(-1) / static_cast(2));
+  is_signed_v ? 0 : ~(static_cast(-1) / static_cast(2));
   static constexpr T A = MID - (MAX - MID) / 3 * 2;
   static constexpr T B = MID - (MAX - MID) / 3;
   static constexpr T C = -B;
@@ -61,8 +67,40 @@
 
   static_assert(MIN < A && A < B && B < MID && MID < C && C < D && D < MAX,
 "Values shall be in an ascending order");
+  // Clear bits in low bytes by the given amount.
+  template 
+  static constexpr T ClearLowBytes =
+  static_cast(static_cast(Value)
+ << ((Bytes >= CHAR_BIT) ? 0 : Bytes) * CHAR_BIT);
+
+  template 
+  static constexpr T TruncZeroOf = ClearLowBytes;
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T XAAA = static_cast(
+  0b10101010'10101010'10101010'10101010'10101010'10101010'10101010'10101010);
+  template 
+  static constexpr T XAAATruncZeroOf = TruncZeroOf; // 0x'AB00
+
+  // Random number with active bits in every byte. 0x'
+  static constexpr T X555 = static_cast(
+  0b01010101'01010101'01010101'01010101'01010101'01010101'01010101'01010101);
+  template 
+  static constexpr T X555TruncZeroOf = TruncZeroOf; // 0x'5600
+
+  // Numbers for ranges with the same bits in the lowest byte.
+  // 0x'AA2A
+  static constexpr T FromA = ClearLowBytes + 42;
+  static constexpr T ToA = FromA + 2; // 0x'AA2C
+  // 0x'552A
+  static constexpr T FromB = ClearLowBytes + 42;
+  static constexpr T ToB = FromB + 2; // 0x'552C
 };
 
+template 
+static constexpr APSIntType APSIntTy =
+APSIntType(sizeof(T) * CHAR_BIT, !is_signed_v);
+
 template  class RangeSetTest : public testing::Test {
 public:
   // Init block
@@ -74,21 +112,24 @@
   // End init block
 
   using Self = RangeSetTest;
-  using RawRange = std::pair;
-  using RawRangeSet = std::initializer_list;
-
-  const llvm::APSInt &from(BaseType X) {
-static llvm::APSInt Base{sizeof(BaseType) * CHAR_BIT,
- std::is_unsigned::value};
-Base = X;
-return BVF.getValue(Base);
+  template  using RawRangeT = std::pair;
+  template 
+  using RawRangeSetT = std::initializer_list>;
+  using RawRange = RawRangeT;
+  using RawRangeSet = RawRangeSetT;
+
+  template  const llvm::APSInt &from(T X) {
+static llvm::APSInt Int = APSIntTy.getZeroValue();
+Int = X;
+return BVF.getValue(Int);
   }
 
-  Range from(const RawRange &Init) {
+  template  Range from(const RawRangeT &Init) {
 return Range(from(Init.first), from(Init.second));
   }
 
-  RangeSet from(const RawRangeSet &Init) {
+  template 
+  RangeSet from(RawRangeSetT Init, APSIntType Ty = APSIntTy) {
 RangeSet RangeSet = F.getEmptySet();
 for (const auto &Raw : Init) {
   RangeSet = F.add(RangeSet, from(Raw));
@@ -211,9 +252,20 @@
RawRangeSet RawExpected) {
 wrap(&Self::checkDeleteImpl, Point, RawFrom, RawExpected);
   }
-};
 
-} // namespace
+  void checkCastToImpl(RangeSet What, APSIntType Ty, RangeSet Expected) {
+RangeSet Result = F.castTo(What, Ty);
+EXPECT_EQ(Result, Expected)
+<< "while casting " << toString(What) << " to " << Ty;
+  }
+
+  template 
+  void checkCastTo(RawRangeSetT What, RawRangeSetT Expected) {
+static constexpr APSIntType FromTy = APSIntTy;
+static constexpr APSIntType ToTy = APSIntTy;
+this->checkCastToImpl(from(What, FromTy), ToTy, from(Expected, ToTy));
+  }
+};
 
 using IntTypes 

[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D109239#3453770 , @glandium wrote:

> Is it expected that `__FLT_EVAL_METHOD__` is not set at all anymore by 
> default after this change?

Can you give a bit more details about what you're seeing? "not set at all" 
sounds like "not predefined as a macro" which is definitely not intended, but I 
can't reproduce.


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

https://reviews.llvm.org/D109239

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire added a comment.

I also find the code below really awkward:

  S->getParent()->getFlags() & Scope::ControlScope

I find that we have helpers like `Scope::isBlockScope()` 
`Scope::isisTryScope()` and etc, but no `Scope::isControlScope` and 
`Scope::isFnTryCatchScope`

I will add these helpers as a NFC patch after this one, that won't need a 
release note or review right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

>> I will add these helpers as a NFC patch after this one, that won't need a 
>> release note or review right?

I found that awkward as well, and almost requested that you fix this, but 
decided against it.  I'm ok with this being an NFC patch. It would be nice to 
grep for all uses of the getFlags that compares with ControlScope and 
FnTryCatchScope to see if we can replace those uses as well.




Comment at: clang/docs/ReleaseNotes.rst:122
   This fixes Issue `Issue 54817 
`_.
+- No longer produce a wrong redefinition error if variables are defined in 
if/for/switch init statements
+  and lambda.

I think this isn't accurate, right?  I thought this had to do with lambdas 
alone? Is the following accurate?

`Clang should no longer incorrectly diagnose a variable declaration inside of a 
lambda expression inside the scope of a if/while/for/switch init statement as a 
redeclaration.  This fixes ...'.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123771: [clang][lex] NFCI: Use DirectoryEntryRef in HeaderSearch::load*()

2022-04-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 423084.
jansvoboda11 marked 5 inline comments as done.
jansvoboda11 added a comment.

Rebase, address review feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123771

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/lib/Lex/HeaderSearch.cpp

Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -319,7 +319,8 @@
   SmallString<128> FrameworkDirName;
   FrameworkDirName += Dir.getFrameworkDir()->getName();
   llvm::sys::path::append(FrameworkDirName, SearchName + ".framework");
-  if (auto FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) {
+  if (auto FrameworkDir =
+  FileMgr.getOptionalDirectoryRef(FrameworkDirName)) {
 bool IsSystem = Dir.getDirCharacteristic() != SrcMgr::C_User;
 Module = loadFrameworkModule(ModuleName, *FrameworkDir, IsSystem);
 if (Module)
@@ -334,8 +335,10 @@
   continue;
 
 bool IsSystem = Dir.isSystemHeaderDirectory();
+// Only returns None if not a normal directory, which we just checked
+DirectoryEntryRef NormalDir = *Dir.getDirRef();
 // Search for a module map file in this directory.
-if (loadModuleMapFile(Dir.getDir(), IsSystem,
+if (loadModuleMapFile(NormalDir, IsSystem,
   /*IsFramework*/false) == LMM_NewlyLoaded) {
   // We just loaded a module map file; check whether the module is
   // available now.
@@ -507,7 +510,7 @@
 /// \param DirName The name of the framework directory.
 /// \param SubmodulePath Will be populated with the submodule path from the
 /// returned top-level module to the originally named framework.
-static const DirectoryEntry *
+static Optional
 getTopFrameworkDir(FileManager &FileMgr, StringRef DirName,
SmallVectorImpl &SubmodulePath) {
   assert(llvm::sys::path::extension(DirName) == ".framework" &&
@@ -527,12 +530,10 @@
   //
   // Similar issues occur when a top-level framework has moved into an
   // embedded framework.
-  const DirectoryEntry *TopFrameworkDir = nullptr;
-  if (auto TopFrameworkDirOrErr = FileMgr.getDirectory(DirName))
-TopFrameworkDir = *TopFrameworkDirOrErr;
+  auto TopFrameworkDir = FileMgr.getOptionalDirectoryRef(DirName);
 
   if (TopFrameworkDir)
-DirName = FileMgr.getCanonicalName(TopFrameworkDir);
+DirName = FileMgr.getCanonicalName(*TopFrameworkDir);
   do {
 // Get the parent directory name.
 DirName = llvm::sys::path::parent_path(DirName);
@@ -540,7 +541,7 @@
   break;
 
 // Determine whether this directory exists.
-auto Dir = FileMgr.getDirectory(DirName);
+auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
 if (!Dir)
   break;
 
@@ -1476,13 +1477,13 @@
   return false;
 
 // Determine whether this directory exists.
-auto Dir = FileMgr.getDirectory(DirName);
+auto Dir = FileMgr.getOptionalDirectoryRef(DirName);
 if (!Dir)
   return false;
 
 // Try to load the module map file in this directory.
 switch (loadModuleMapFile(*Dir, IsSystem,
-  llvm::sys::path::extension((*Dir)->getName()) ==
+  llvm::sys::path::extension(Dir->getName()) ==
   ".framework")) {
 case LMM_NewlyLoaded:
 case LMM_AlreadyLoaded:
@@ -1579,15 +1580,16 @@
   if (needModuleLookup(RequestingModule, SuggestedModule)) {
 // Find the top-level framework based on this framework.
 SmallVector SubmodulePath;
-const DirectoryEntry *TopFrameworkDir
-  = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
+Optional TopFrameworkDir =
+::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
+assert(TopFrameworkDir && "Could not find the top-most framework dir");
 
 // Determine the name of the top-level framework.
 StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName());
 
 // Load this framework module. If that succeeds, find the suggested module
 // for this header, if any.
-loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystemFramework);
+loadFrameworkModule(ModuleName, *TopFrameworkDir, IsSystemFramework);
 
 // FIXME: This can find a module not part of ModuleName, which is
 // important so that we're consistent about whether this header
@@ -1618,39 +1620,38 @@
  StringRef OriginalModuleMapFile) {
   // Find the directory for the module. For frameworks, that may require going
   // up from the 'Modules' directory.
-  const DirectoryEntry *Dir = nullptr;
+  Optional Dir;
   if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) {
-if (auto DirOrErr = FileMgr.getDirectory("."))
-  Dir = *DirOrErr;
+Dir = FileMgr.getOptionalDirectoryRef(".");
   } el

[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 423085.
junaire added a comment.

Fix bad wording.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/IdentifierResolver.cpp
  clang/test/SemaCXX/cxx1z-init-statement.cpp


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression inside the scope of a if/while/for/switch init statement
+  as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 `_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed twice.
   This fixes Issue `Issue 54817 `_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression inside the scope of a if/while/for/switch init statement
+  as a redeclaration.
+  This fixes `Issue 54913 `_.
 
 Improvements to Clang's diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:123
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression inside the scope of a if/while/for/switch init statement
+  as a redeclaration.

Sorry, re-read it:

Clang should no longer incorrectly diagnose a variable declaration inside of a 
lambda expression that shares the name of a variable in a containing 
if/while/for/switch init statement as a redeclaration.


Feel free to commit with that wording.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire marked an inline comment as done.
junaire added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:122
   This fixes Issue `Issue 54817 
`_.
+- No longer produce a wrong redefinition error if variables are defined in 
if/for/switch init statements
+  and lambda.

erichkeane wrote:
> I think this isn't accurate, right?  I thought this had to do with lambdas 
> alone? Is the following accurate?
> 
> `Clang should no longer incorrectly diagnose a variable declaration inside of 
> a lambda expression inside the scope of a if/while/for/switch init statement 
> as a redeclaration.  This fixes ...'.
> I think this isn't accurate, right?  I thought this had to do with lambdas 
> alone? Is the following accurate?
> 
> `Clang should no longer incorrectly diagnose a variable declaration inside of 
> a lambda expression inside the scope of a if/while/for/switch init statement 
> as a redeclaration.  This fixes ...'.

Thanks for the suggestion, It's my fault, I really shouldn't be sleeping in my 
English grammar class...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 423086.
junaire marked an inline comment as done.
junaire added a comment.

Update release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/IdentifierResolver.cpp
  clang/test/SemaCXX/cxx1z-init-statement.cpp


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 `_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed twice.
   This fixes Issue `Issue 54817 `_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 `_.
 
 Improvements to Clang's diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123853: [clang] NFCI: Use DirectoryEntryRef in FrontendAction::BeginSourceFile()

2022-04-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, bnbarham.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch removes use of the deprecated `DirectoryEntry::getName()` from 
`FrontendAction::BeginSourceFile()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123853

Files:
  clang/lib/Frontend/FrontendAction.cpp


Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -761,10 +761,10 @@
 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
-if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
+if (auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude)) {
   std::error_code EC;
   SmallString<128> DirNative;
-  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
+  llvm::sys::path::native(PCHDir->getName(), DirNative);
   bool Found = false;
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),


Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -761,10 +761,10 @@
 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
-if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
+if (auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude)) {
   std::error_code EC;
   SmallString<128> DirNative;
-  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
+  llvm::sys::path::native(PCHDir->getName(), DirNative);
   bool Found = false;
   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
   for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] be0905a - [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang via cfe-commits

Author: Jun Zhang
Date: 2022-04-15T21:54:39+08:00
New Revision: be0905a333d6f7c4d7f5c70c18211463e53473cd

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

LOG: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

Clang should no longer incorrectly diagnose a variable declaration inside of a
lambda expression that shares the name of a variable in a containing
if/while/for/switch init statement as a redeclaration.

After this patch, clang is supposed to accept code below:

void foo() {
  for (int x = [] { int x = 0; return x; }(); ;) ;
}

Fixes https://github.com/llvm/llvm-project/issues/54913

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/IdentifierResolver.cpp
clang/test/SemaCXX/cxx1z-init-statement.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f5d3793225bfb..2497280dfdd6d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@ Bug Fixes
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Sema/IdentifierResolver.cpp 
b/clang/lib/Sema/IdentifierResolver.cpp
index 333f4d70986a0..9c5d78fb25d9c 100644
--- a/clang/lib/Sema/IdentifierResolver.cpp
+++ b/clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@ bool IdentifierResolver::isDeclInScope(Decl *D, 
DeclContext *Ctx, Scope *S,
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;

diff  --git a/clang/test/SemaCXX/cxx1z-init-statement.cpp 
b/clang/test/SemaCXX/cxx1z-init-statement.cpp
index eea2589ab7c62..b963c9eabe79b 100644
--- a/clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ b/clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@ void test_constexpr_init_stmt() {
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}



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


[PATCH] D123840: [Clang][Sema] Fix invalid redefinition error in if/switch/for statement

2022-04-15 Thread Jun Zhang 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 rGbe0905a333d6: [Clang][Sema] Fix invalid redefinition error 
in if/switch/for statement (authored by junaire).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123840

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/IdentifierResolver.cpp
  clang/test/SemaCXX/cxx1z-init-statement.cpp


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 
`_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed 
twice.
   This fixes Issue `Issue 54817 
`_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 
`_.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/SemaCXX/cxx1z-init-statement.cpp
===
--- clang/test/SemaCXX/cxx1z-init-statement.cpp
+++ clang/test/SemaCXX/cxx1z-init-statement.cpp
@@ -90,3 +90,18 @@
   static_assert(constexpr_switch_init(-2) == 0, "");
   static_assert(constexpr_switch_init(-5) == -1, "");
 }
+
+int test_lambda_init() {
+  if (int x = []() {int x = 42; return x; }(); x) {
+  };
+
+  switch (int y = []() {int y = 42; return y; }(); y) {
+  case 42:
+return 1;
+  }
+
+  for (int x = [] { int x = 0; return x; }();;)
+;
+
+  return 0;
+}
Index: clang/lib/Sema/IdentifierResolver.cpp
===
--- clang/lib/Sema/IdentifierResolver.cpp
+++ clang/lib/Sema/IdentifierResolver.cpp
@@ -121,7 +121,10 @@
   // of the controlled statement.
   //
   assert(S->getParent() && "No TUScope?");
-  if (S->getParent()->getFlags() & Scope::ControlScope) {
+  // If the current decl is in a lambda, we shouldn't consider this is a
+  // redefinition as lambda has its own scope.
+  if (S->getParent()->getFlags() & Scope::ControlScope &&
+  !S->isFunctionScope()) {
 S = S->getParent();
 if (S->isDeclScope(D))
   return true;
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -119,6 +119,10 @@
   This fixes Issue `Issue 52802 `_.
 - Unknown type attributes with a ``[[]]`` spelling are no longer diagnosed twice.
   This fixes Issue `Issue 54817 `_.
+- Clang should no longer incorrectly diagnose a variable declaration inside of
+  a lambda expression that shares the name of a variable in a containing
+  if/while/for/switch init statement as a redeclaration.
+  This fixes `Issue 54913 `_.
 
 Improvements to Clang's diagnostics
 ^^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121984: [RISCV] Moving RVV intrinsic type related util to clang/Support

2022-04-15 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added a comment.

> Thank you for the explanation. I still don't think this is really "Support" 
> material, but I'm also struggling to think of a better place to put it in an 
> existing directory in Clang aside from Basic, but that would still be a bit 
> of a layering violation it feels like. So I think I'm convinced that Support 
> is a reasonable place to put it.

Actually I tried to put that on clang/Basic before, and end up with the 
clang/Basic is depended on clang-tblgen, and that made clang-tblgen depend on 
clang/Basic...then CMake report error for circular dependency :P

> Should it live within a RISCV direction inside of the Support directory? Or 
> should we use folders like that for host platform support files instead of 
> target platform support files (as the LLVM Support directory appears to do)?

I saw LLVM/Support are just target specific file on the folder instead of many 
target folder, I guess there should not be too much target specific files in 
clang/Support, and we could reorg the folder organization once it getting 
complicated? What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121984

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


[PATCH] D123854: [clang][lex] NFCI: Use DirectoryEntryRef in FrameworkCacheEntry

2022-04-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, bnbarham.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch changes the member of `FrameworkCacheEntry` from `const 
DirectoryEntry *` to `Optional` in order to remove uses of 
the deprecated `DirectoryEntry::getName()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123854

Files:
  clang/include/clang/Lex/HeaderSearch.h
  clang/lib/Lex/HeaderSearch.cpp


Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -581,7 +581,7 @@
 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
 
   // If it is known and in some other directory, fail.
-  if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
+  if (CacheEntry.Directory && *CacheEntry.Directory != getFrameworkDir())
 return None;
 
   // Otherwise, construct the path to this framework dir.
@@ -610,7 +610,7 @@
 
 // Otherwise, if it does, remember that this is the right direntry for this
 // framework.
-CacheEntry.Directory = getFrameworkDir();
+CacheEntry.Directory = getFrameworkDirRef();
 
 // If this is a user search directory, check if the framework has been
 // user-specified as a system framework.
@@ -625,7 +625,7 @@
 
   // Set out flags.
   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
-  IsFrameworkFound = CacheEntry.Directory;
+  IsFrameworkFound = CacheEntry.Directory.hasValue();
 
   if (RelativePath) {
 RelativePath->clear();
@@ -1183,7 +1183,7 @@
 ++NumSubFrameworkLookups;
 
 // If the framework dir doesn't exist, we fail.
-auto Dir = FileMgr.getDirectory(FrameworkName);
+auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
 if (!Dir)
   return None;
 
Index: clang/include/clang/Lex/HeaderSearch.h
===
--- clang/include/clang/Lex/HeaderSearch.h
+++ clang/include/clang/Lex/HeaderSearch.h
@@ -155,7 +155,7 @@
 /// This structure is used to record entries in our framework cache.
 struct FrameworkCacheEntry {
   /// The directory entry which should be used for the cached framework.
-  const DirectoryEntry *Directory;
+  Optional Directory;
 
   /// Whether this framework has been "user-specified" to be treated as if it
   /// were a system framework (even if it was found outside a system framework


Index: clang/lib/Lex/HeaderSearch.cpp
===
--- clang/lib/Lex/HeaderSearch.cpp
+++ clang/lib/Lex/HeaderSearch.cpp
@@ -581,7 +581,7 @@
 HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
 
   // If it is known and in some other directory, fail.
-  if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
+  if (CacheEntry.Directory && *CacheEntry.Directory != getFrameworkDir())
 return None;
 
   // Otherwise, construct the path to this framework dir.
@@ -610,7 +610,7 @@
 
 // Otherwise, if it does, remember that this is the right direntry for this
 // framework.
-CacheEntry.Directory = getFrameworkDir();
+CacheEntry.Directory = getFrameworkDirRef();
 
 // If this is a user search directory, check if the framework has been
 // user-specified as a system framework.
@@ -625,7 +625,7 @@
 
   // Set out flags.
   InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework;
-  IsFrameworkFound = CacheEntry.Directory;
+  IsFrameworkFound = CacheEntry.Directory.hasValue();
 
   if (RelativePath) {
 RelativePath->clear();
@@ -1183,7 +1183,7 @@
 ++NumSubFrameworkLookups;
 
 // If the framework dir doesn't exist, we fail.
-auto Dir = FileMgr.getDirectory(FrameworkName);
+auto Dir = FileMgr.getOptionalDirectoryRef(FrameworkName);
 if (!Dir)
   return None;
 
Index: clang/include/clang/Lex/HeaderSearch.h
===
--- clang/include/clang/Lex/HeaderSearch.h
+++ clang/include/clang/Lex/HeaderSearch.h
@@ -155,7 +155,7 @@
 /// This structure is used to record entries in our framework cache.
 struct FrameworkCacheEntry {
   /// The directory entry which should be used for the cached framework.
-  const DirectoryEntry *Directory;
+  Optional Directory;
 
   /// Whether this framework has been "user-specified" to be treated as if it
   /// were a system framework (even if it was found outside a system framework
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123856: [clang][lex] NFCI: Use FileEntryRef in ModuleMap::diagnoseHeaderInclusion()

2022-04-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, bnbarham.
Herald added a project: All.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch removes uses of the deprecated `DirectoryEntry::getName()` from the 
`ModuleMap::diagnoseHeaderInclusion()` function by using 
`{File,Directory}EntryRef` instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123856

Files:
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPDirectives.cpp


Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -905,7 +905,7 @@
 if (SuggestedModule && !LangOpts.AsmPreprocessor)
   HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
   RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
-  Filename, &FE->getFileEntry());
+  Filename, *FE);
 return FE;
   }
 
@@ -921,7 +921,7 @@
 if (SuggestedModule && !LangOpts.AsmPreprocessor)
   HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
   RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
-  Filename, &FE->getFileEntry());
+  Filename, *FE);
 return FE;
   }
 }
@@ -936,7 +936,7 @@
   if (SuggestedModule && !LangOpts.AsmPreprocessor)
 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
 RequestingModule, RequestingModuleIsModuleInterface,
-FilenameLoc, Filename, &FE->getFileEntry());
+FilenameLoc, Filename, *FE);
   return FE;
 }
   }
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -473,8 +473,7 @@
 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
 bool RequestingModuleIsModuleInterface,
 SourceLocation FilenameLoc,
-StringRef Filename,
-const FileEntry *File) {
+StringRef Filename, FileEntryRef File) 
{
   // No errors for indirect modules. This may be a bit of a problem for modules
   // with no source files.
   if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
@@ -542,7 +541,7 @@
 diag::warn_non_modular_include_in_framework_module :
 diag::warn_non_modular_include_in_module;
 Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
-<< File->getName();
+<< File.getName();
   }
 }
 
Index: clang/include/clang/Lex/ModuleMap.h
===
--- clang/include/clang/Lex/ModuleMap.h
+++ clang/include/clang/Lex/ModuleMap.h
@@ -479,7 +479,7 @@
   void diagnoseHeaderInclusion(Module *RequestingModule,
bool RequestingModuleIsModuleInterface,
SourceLocation FilenameLoc, StringRef Filename,
-   const FileEntry *File);
+   FileEntryRef File);
 
   /// Determine whether the given header is part of a module
   /// marked 'unavailable'.


Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -905,7 +905,7 @@
 if (SuggestedModule && !LangOpts.AsmPreprocessor)
   HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
   RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
-  Filename, &FE->getFileEntry());
+  Filename, *FE);
 return FE;
   }
 
@@ -921,7 +921,7 @@
 if (SuggestedModule && !LangOpts.AsmPreprocessor)
   HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
   RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
-  Filename, &FE->getFileEntry());
+  Filename, *FE);
 return FE;
   }
 }
@@ -936,7 +936,7 @@
   if (SuggestedModule && !LangOpts.AsmPreprocessor)
 HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
 RequestingModule, RequestingModuleIsModuleInterface,
-FilenameLoc, Filename, &FE->getFileEntry());
+FilenameLoc, Filename, *FE);
   return FE;
 }
   }
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -473,8 +473,7 @@
 void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
 bool RequestingModuleIsModuleInterface,
  

[clang] 7ed01ba - [clang][deps] NFC: Inline function with single caller

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T16:24:40+02:00
New Revision: 7ed01ba88d67a0eb79663547f9ec21d106f7b281

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

LOG: [clang][deps] NFC: Inline function with single caller

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
index aee4ddee9707b..3bb44e44187ba 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
@@ -56,10 +56,6 @@ struct FullDependencies {
 
   /// Get the full command line, excluding -fmodule-file=" arguments.
   std::vector getCommandLineWithoutModulePaths() const;
-
-  /// Get additional arguments suitable for appending to the original Clang
-  /// command line, excluding "-fmodule-file=" arguments.
-  std::vector getAdditionalArgsWithoutModulePaths() const;
 };
 
 struct FullDependenciesResult {

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
index 55d2c48af41a2..6fd3a83fd3f7b 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -27,9 +27,10 @@ std::vector
 FullDependencies::getCommandLineWithoutModulePaths() const {
   std::vector Args = OriginalCommandLine;
 
-  std::vector AdditionalArgs =
-  getAdditionalArgsWithoutModulePaths();
-  Args.insert(Args.end(), AdditionalArgs.begin(), AdditionalArgs.end());
+  Args.push_back("-fno-implicit-modules");
+  Args.push_back("-fno-implicit-module-maps");
+  for (const PrebuiltModuleDep &PMD : PrebuiltModuleDeps)
+Args.push_back("-fmodule-file=" + PMD.PCMFile);
 
   // This argument is unused in explicit compiles.
   llvm::erase_if(Args, [](const std::string &Arg) {
@@ -42,19 +43,6 @@ FullDependencies::getCommandLineWithoutModulePaths() const {
   return Args;
 }
 
-std::vector
-FullDependencies::getAdditionalArgsWithoutModulePaths() const {
-  std::vector Args{
-  "-fno-implicit-modules",
-  "-fno-implicit-module-maps",
-  };
-
-  for (const PrebuiltModuleDep &PMD : PrebuiltModuleDeps)
-Args.push_back("-fmodule-file=" + PMD.PCMFile);
-
-  return Args;
-}
-
 DependencyScanningTool::DependencyScanningTool(
 DependencyScanningService &Service)
 : Worker(Service) {}



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


[clang] 26b0ecb - [clang][deps] NFC: Update documentation

2022-04-15 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2022-04-15T16:24:41+02:00
New Revision: 26b0ecb8985b7e76a5ca0965d3d464611eda14f0

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

LOG: [clang][deps] NFC: Update documentation

Added: 


Modified: 
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 8b6697f020ab3..7e7747a36f27a 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -145,15 +145,15 @@ static llvm::cl::opt Format(
 // Build tools that want to put the PCM files in a 
diff erent location should use
 // the C++ APIs instead, of which there are two flavors:
 //
-// 1. APIs that generate arguments with paths to modulemap and PCM files via
-//callbacks provided by the client:
-// * ModuleDeps::getCanonicalCommandLine(LookupPCMPath, LookupModuleDeps)
-// * FullDependencies::getAdditionalArgs(LookupPCMPath, LookupModuleDeps)
+// 1. APIs that generate arguments with paths PCM files via a callback provided
+//by the client:
+// * ModuleDeps::getCanonicalCommandLine(LookupPCMPath)
+// * FullDependencies::getCommandLine(LookupPCMPath)
 //
-// 2. APIs that don't generate arguments with paths to modulemap or PCM files
-//and instead expect the client to append them manually after the fact:
+// 2. APIs that don't generate arguments with paths PCM files and instead 
expect
+// the client to append them manually after the fact:
 // * ModuleDeps::getCanonicalCommandLineWithoutModulePaths()
-// * FullDependencies::getAdditionalArgsWithoutModulePaths()
+// * FullDependencies::getCommandLineWithoutModulePaths()
 //
 static llvm::cl::opt GenerateModulesPathArgs(
 "generate-modules-path-args",



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


[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2022-04-15 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D109239#3453770 , @glandium wrote:

> Is it expected that `__FLT_EVAL_METHOD__` is not set at all anymore by 
> default after this change?

@glandium would you mind giving a reproducer. We might have missed a flow path 
where the macro is undefined.


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

https://reviews.llvm.org/D109239

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-15 Thread Corentin Jabot 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 rG04000c2f928a: [clang] Implement Change scope of lambda 
trailing-return-type (authored by cor3ntin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1356,7 +1356,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3";>P2036R3
-  No
+  Clang 15
 
 
   Multidimensional subscript operator
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,173 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [&x = y](
+ decltype([&](decltype(x)) { return 0; }) y) {
+return x;
+  };
+}
+
+void test_noexcept() {
+
+  int y;
+
+  static_assert(noexcept([x = 1] noexcept(is_same) {}()));
+  static_assert(noexcept([x = 1] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([y] noexcept(is_same) {}()));
+  static_assert(noexcept([y] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([=] noexcept(is_same) {}()));
+  static_assert(noexcept([=] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([&] noexcept(is_same) {}()));
+  static_assert(noexcept([&] mutable noexcept(is_same) {}()));
+
+  static_assert(noexcept([&] mutable noexcept(!is_same) {}())); // expected-error {{static_assert failed due}}
+}
+
+void test_requires() {
+
+  int x;
+
+  [x = 1]() requires is_same {}
+  ();
+  [x = 1]() mutable requires is_same {}
+  ();
+  [x]() requires is_same {}
+  ();
+  [x]() mutable requires is_same {}
+  ();
+  [=]() requires is_same {}
+  ();
+  [=]() mutable requires is_same {}
+  ();
+  [&]() requires is_same {}
+  ();
+  [&]() mutable requires is_same {}
+  ();
+  [&x]() requires is_same {}
+  ();
+  [&x]() mutable requires is_same {}
+  ();
+
+  [x = 1]() requires is_same {} (); //expected-error {{no matching function for call to object of type}} \
+   // expected-note {{candidate function not viable}} \
+   // expected-note {{'is_same' evaluated to false}}
+  [x = 1]() mutable requires is_same {} (); // expected-error {{no matching function for call to object of type}} \
+ // expected-note {{candidate function not viable}} \
+ // expected-note {{'is_same' evaluated to false}}
+}
+
+void err() {
+  int y, z;// expected-note 2{{declared here}}
+  auto implicit_tpl = [=]( // expected-note {{variable 'y' is captured here}}
+  decltype(
+  [&] { return 0; }) y) { //expected-error{{captur

[clang] 04000c2 - [clang] Implement Change scope of lambda trailing-return-type

2022-04-15 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2022-04-15T16:50:52+02:00
New Revision: 04000c2f928a7adc32138a664d167f01b642bef3

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

LOG: [clang] Implement Change scope of lambda trailing-return-type

Implement P2036R3.

Captured variables by copy (explicitely or not), are deduced
correctly at the point we know whether the lambda is mutable,
and ill-formed before that.

Up until now, the entire lambda declaration up to the start of the body would 
be parsed in the parent scope, such that capture would not be available to look 
up.

The scoping is changed to have an outer lambda scope, followed by the lambda 
prototype and body.

The lambda scope is necessary because there may be a template scope between the 
start of the lambda (to which we want to attach the captured variable) and the 
prototype scope.

We also need to introduce a declaration context to attach the captured variable 
to (and several parts of clang assume captures are handled from the call 
operator context), before we know the type of the call operator.

The order of operations is as follow:

* Parse the init capture in the lambda's parent scope

* Introduce a lambda scope

* Create the lambda class and call operator

* Add the init captures to the call operator context and the lambda scope. But 
the variables are not capured yet (because we don't know their type).
Instead, explicit  captures are stored in a temporary map that conserves the 
order of capture (for the purpose of having a stable order in the ast dumps).

* A flag is set on LambdaScopeInfo to indicate that we have not yet injected 
the captures.

* The parameters are parsed (in the parent context, as lambda mangling recurses 
in the parent context, we couldn't mangle a lambda that is attached to the 
context of a lambda whose type is not yet known).

* The lambda qualifiers are parsed, at this point We can switch (for the second 
time) inside the lambda context, unset the flag indicating that we have not 
parsed the lambda qualifiers,
record the lambda is mutable and capture the explicit variables.

* We can parse the rest of the lambda type, transform the lambda and call 
operator's types and also transform the call operator to a template function 
decl where necessary.

At this point, both captures and parameters can be injected in the body's 
scope. When trying to capture an implicit variable, if we are before the 
qualifiers of a lambda, we need to remember that the variables are still in the 
parent's context (rather than in the call operator's).

Reviewed By: aaron.ballman, #clang-language-wg, ChuanqiXu

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

Added: 
clang/test/SemaCXX/lambda-capture-type-deduction.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/DeclCXX.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Scope.h
clang/include/clang/Sema/ScopeInfo.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Sema/Scope.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaCXXScopeSpec.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/TreeTransform.h
clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2497280dfdd6d..c72028c718586 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -255,6 +255,9 @@ C++2b Feature Support
 - Implemented `P2128R6: Multidimensional subscript operator 
`_.
 - Implemented `P0849R8: auto(x): decay-copy in the language 
`_.
 - Implemented `P2242R3: Non-literal variables (and labels and gotos) in 
constexpr functions`_.
+- Implemented `P2036R3: Change scope of lambda trailing-return-type 
`_.
+  This proposal modifies how variables captured in lambdas can appear in 
trailing return type
+  expressions and how their types are deduced therein, in all C++ language 
versions.
 
 CUDA Language Changes in Clang
 --

diff  --git a/clang/include/clang/AST/DeclCXX.h 
b/clang/include/clang/AST/DeclCXX.h
index 04a9daa14e05e..c640f7f7ba63f 100644
--- a/clang/include/clang/AST/DeclCXX.h
+++ b/clang/include/clang/AST/DeclCXX.h
@@ -1799,6 +1799,20 @@ class CXXRecordDecl : public RecordDecl {
 return getLambdaData().MethodTyInfo;
   }
 
+  void setLambdaTypeInfo(TypeSourceInfo *TS) {
+auto *DD = DefinitionData;
+assert(DD && DD->IsLambda &&

[PATCH] D123858: [clang][dataflow] Ensure well-formed flow conditions.

2022-04-15 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added reviewers: xazax.hun, sgatev.
Herald added subscribers: tschuett, steakhal, rnkovacs.
Herald added a project: All.
ymandel requested review of this revision.
Herald added a project: clang.

Ensure that the expressions associated with terminators are associated with a
value. Otherwise, we can generate degenerate flow conditions, where both
branches share the same condition.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123858

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
@@ -2890,6 +2890,68 @@
   });
 }
 
+TEST_F(TransferTest, OpaqueFlowConditionMergesToOpaqueBool) {
+  std::string Code = R"(
+bool foo();
+
+void target() {
+  bool Bar = true;
+  if (foo())
+Bar = false;
+  (void)0;
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+auto &BarVal =
+*cast(Env.getValue(*BarDecl, SkipPast::Reference));
+
+EXPECT_FALSE(Env.flowConditionImplies(BarVal));
+  });
+}
+
+TEST_F(TransferTest, OpaqueFlowConditionInsideBranchMergesToOpaqueBool) {
+  std::string Code = R"(
+bool foo();
+
+void target(bool Cond) {
+  bool Bar = true;
+  if (Cond) {
+if (foo())
+  Bar = false;
+(void)0;
+/*[[p]]*/
+  }
+}
+  )";
+  runDataflow(
+  Code, [](llvm::ArrayRef<
+   std::pair>>
+   Results,
+   ASTContext &ASTCtx) {
+ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+const Environment &Env = Results[0].second.Env;
+
+const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+ASSERT_THAT(BarDecl, NotNull());
+
+auto &BarVal =
+*cast(Env.getValue(*BarDecl, SkipPast::Reference));
+
+EXPECT_FALSE(Env.flowConditionImplies(BarVal));
+  });
+}
+
 TEST_F(TransferTest, CorrelatedBranches) {
   std::string Code = R"(
 void target(bool B, bool C) {
Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -32,6 +32,7 @@
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/ErrorHandling.h"
 
 namespace clang {
 namespace dataflow {
@@ -108,8 +109,32 @@
 
 auto *Val =
 cast_or_null(Env.getValue(Cond, SkipPast::Reference));
-if (Val == nullptr)
-  return;
+// Value merging depends on flow conditions from different environments
+// being mutually exclusive. So, we need *some* value for the condition
+// expression, even if just an atom.
+if (Val == nullptr) {
+  Val = &Env.makeAtomicBoolValue();
+  QualType Type = Cond.getType();
+  assert(Type->isBooleanType() || Type->isReferenceType());
+  if (Type->isBooleanType()) {
+auto &Loc = Env.createStorageLocation(Cond);
+Env.setStorageLocation(Cond, Loc);
+Env.setValue(Loc, *Val);
+  } else if (auto *CondVal = cast_or_null(
+ Env.getValue(Cond, SkipPast::None))) {
+Env.setValue(CondVal->getPointeeLoc(), *Val);
+  } else {
+QualType PointeeType = Type->castAs()->getPointeeType();
+StorageLocation &PointeeLoc = Env.createStorageLocation(PointeeType);
+Env.setValue(PointeeLoc, *Val);
+auto *Loc = Env.getStorageLocation(Cond, SkipPast::None);
+// `Cond` must have been processed already (and so must have an
+// associated location) since it came from the predecessor block.
+assert(Loc != nullptr);
+Env.setValue(*Loc, Env.takeOwnership(
+   std::make_unique(PointeeLoc)));
+  }
+}
 
 // The condition must be inverted for the successor that encompasses the
 // "else" branch, if such exists.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 423116.
royjacobson marked an inline comment as not done.
royjacobson added a comment.

Update for look inside FunctionParamTypesAreEqual to be index based and simpler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp

Index: clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp
===
--- /dev/null
+++ clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+
+struct A;
+struct B;
+
+template  constexpr bool True = true;
+template  concept C = True;
+
+void f(C auto &, auto &) = delete;
+template  void f(Q &, C auto &);
+
+void g(struct A *ap, struct B *bp) {
+  f(*ap, *bp);
+}
+
+template  struct X {};
+
+template  bool operator==(X, V) = delete;
+templatebool operator==(T, X);
+
+bool h() {
+  return X{} == 0;
+}
+
+namespace PR53640 {
+
+template 
+concept C = true;
+
+template 
+void f(T t) {} // expected-note {{candidate function [with T = int]}}
+
+template 
+void f(const T &t) {} // expected-note {{candidate function [with T = int]}}
+
+int g() {
+  f(0); // expected-error {{call to 'f' is ambiguous}}
+}
+
+struct S {
+  template  explicit S(T) noexcept requires C {} // expected-note {{candidate constructor}}
+  template  explicit S(const T &) noexcept {}   // expected-note {{candidate constructor}}
+};
+
+int h() {
+  S s(4); // expected-error-re {{call to constructor of {{.*}} is ambiguous}}
+}
+
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5143,18 +5143,20 @@
 /// candidate with a reversed parameter order. In this case, the corresponding
 /// P/A pairs between FT1 and FT2 are reversed.
 ///
+/// \param AllowOrderingByConstraints If \c is false, don't check whether one
+/// of the templates is more constrained than the other. Default is true.
+///
 /// \returns the more specialized function template. If neither
 /// template is more specialized, returns NULL.
-FunctionTemplateDecl *
-Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
- FunctionTemplateDecl *FT2,
- SourceLocation Loc,
- TemplatePartialOrderingContext TPOC,
- unsigned NumCallArguments1,
- unsigned NumCallArguments2,
- bool Reversed) {
-
-  auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * {
+FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
+FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
+TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
+unsigned NumCallArguments2, bool Reversed,
+bool AllowOrderingByConstraints) {
+
+  auto JudgeByConstraints = [&]() -> FunctionTemplateDecl * {
+if (!AllowOrderingByConstraints)
+  return nullptr;
 llvm::SmallVector AC1, AC2;
 FT1->getAssociatedConstraints(AC1);
 FT2->getAssociatedConstraints(AC2);
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -2952,24 +2952,30 @@
 }
 
 /// FunctionParamTypesAreEqual - This routine checks two function proto types
-/// for equality of their argument types. Caller has already checked that
-/// they have same number of arguments.  If the parameters are different,
+/// for equality of their parameter types. Caller has already checked that
+/// they have same number of parameters.  If the parameters are different,
 /// ArgPos will have the parameter index of the first different parameter.
+/// If `Reversed` is true, the parameters of `NewType` will be compared in
+/// reverse order. That's useful if one of the functions is being used as a C++20
+/// synthesized operator overload with a reversed parameter order.
 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
   const FunctionProtoType *NewType,
-  unsigned *ArgPos) {
-  for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
-  N = NewType->param_type_begin(),
-  E = OldType->param_type_end();
-   O && (O != E); ++O, ++N) {
+  unsigned *ArgPos, bool Reversed) {
+  assert(OldType->get

[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:2967
+ "parameters!");
+  for (FunctionProtoType::param_type_iterator
+   O = OldType->param_type_begin(),

erichkeane wrote:
> Thanks for the clarification on 'Reversed'.  The comment makes it more clear.
> 
> This whole 'for' header is... really tough to mentally parse, even BEFORE 
> this, and now it is even worse with 'Reversed' involved.  I would prefer that 
> the iterators be initialized ahead of time.  Additionally, can we use 
> `reverse_iterator` for the 'NewType' instead of branching on `Reversed` here? 
>  
> 
> Any other suggestions you have to simplify this loop would also be 
> appreciated.  I might ALSO consider using 'zip' here?
I made it index based which IMO is easier to understand now.

I thought reverse_iterator would be annoying because I would need to make the 
code a template since it's a different type.

Also - ping about the comment in isBetterOverloadCandidate :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

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


[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:2967
+ "parameters!");
+  for (FunctionProtoType::param_type_iterator
+   O = OldType->param_type_begin(),

royjacobson wrote:
> erichkeane wrote:
> > Thanks for the clarification on 'Reversed'.  The comment makes it more 
> > clear.
> > 
> > This whole 'for' header is... really tough to mentally parse, even BEFORE 
> > this, and now it is even worse with 'Reversed' involved.  I would prefer 
> > that the iterators be initialized ahead of time.  Additionally, can we use 
> > `reverse_iterator` for the 'NewType' instead of branching on `Reversed` 
> > here?  
> > 
> > Any other suggestions you have to simplify this loop would also be 
> > appreciated.  I might ALSO consider using 'zip' here?
> I made it index based which IMO is easier to understand now.
> 
> I thought reverse_iterator would be annoying because I would need to make the 
> code a template since it's a different type.
> 
> Also - ping about the comment in isBetterOverloadCandidate :)
Ah, right, you'd have 1 reverse iterator on one side of the 'zip'.  Thats 
unfortunate.  I guess this reads well-enough though, iti s definitely an 
improvement.



Comment at: clang/lib/Sema/SemaOverload.cpp:9829
+  bool CanCompareConstraints = false;
+  if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
+  Cand2.Function->hasPrototype()) {

royjacobson wrote:
> erichkeane wrote:
> > Since the point of this is to just calculate the CanCompareConstraints, I 
> > think it should be a separate function called below where it is used.  
> Do you mean as in a separate `Sema` function? Or a local lambda?
Just a static function is fine, basically its a whole lot of work happening in 
this function for a single result, so I'm suggesting splitting off the 
calculation for `CanCompareConstraints` into its own function, so you get:

`bool CanCompareConstrants = new_function(...);`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

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


[clang] 52e6a27 - Clean up `OMPAtomicDirective::Create`

2022-04-15 Thread Shilei Tian via cfe-commits

Author: Shilei Tian
Date: 2022-04-15T11:41:26-04:00
New Revision: 52e6a27690ca8e5f07cc646716c3736475b7746b

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

LOG: Clean up `OMPAtomicDirective::Create`

Added: 


Modified: 
clang/include/clang/AST/StmtOpenMP.h
clang/lib/AST/StmtOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp

Removed: 




diff  --git a/clang/include/clang/AST/StmtOpenMP.h 
b/clang/include/clang/AST/StmtOpenMP.h
index 28b3567b36556..0aa318d84a93f 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -2889,6 +2889,27 @@ class OMPAtomicDirective : public OMPExecutableDirective 
{
   void setCond(Expr *C) { Data->getChildren()[DataPositionTy::POS_Cond] = C; }
 
 public:
+  struct Expressions {
+/// 'x' part of the associated expression/statement.
+Expr *X = nullptr;
+/// 'v' part of the associated expression/statement.
+Expr *V = nullptr;
+/// 'expr' part of the associated expression/statement.
+Expr *E = nullptr;
+/// UE Helper expression of the form:
+/// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
+/// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
+Expr *UE = nullptr;
+/// 'd' part of the associated expression/statement.
+Expr *D = nullptr;
+/// Conditional expression in `atomic compare` construct.
+Expr *Cond = nullptr;
+/// True if UE has the first form and false if the second.
+bool IsXLHSInRHSPart;
+/// True if original value of 'x' must be stored in 'v', not an updated 
one.
+bool IsPostfixUpdate;
+  };
+
   /// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr'
   /// parts of the atomic construct (see Section 2.12.6, atomic Construct, for
   /// detailed description of 'x', 'v' and 'expr').
@@ -2898,23 +2919,12 @@ class OMPAtomicDirective : public 
OMPExecutableDirective {
   /// \param EndLoc Ending Location of the directive.
   /// \param Clauses List of clauses.
   /// \param AssociatedStmt Statement, associated with the directive.
-  /// \param X 'x' part of the associated expression/statement.
-  /// \param V 'v' part of the associated expression/statement.
-  /// \param E 'expr' part of the associated expression/statement.
-  /// \param UE Helper expression of the form
-  /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
-  /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
-  /// \param D 'd' part of the associated expression/statement.
-  /// \param Cond Conditional expression in `atomic compare` construct.
-  /// \param IsXLHSInRHSPart true if \a UE has the first form and false if the
-  /// second.
-  /// \param IsPostfixUpdate true if original value of 'x' must be stored in
-  /// 'v', not an updated one.
-  static OMPAtomicDirective *
-  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
- ArrayRef Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V,
- Expr *E, Expr *UE, Expr *D, Expr *Cond, bool IsXLHSInRHSPart,
- bool IsPostfixUpdate);
+  /// \param Exprs Associated expressions or statements.
+  static OMPAtomicDirective *Create(const ASTContext &C,
+SourceLocation StartLoc,
+SourceLocation EndLoc,
+ArrayRef Clauses,
+Stmt *AssociatedStmt, Expressions Exprs);
 
   /// Creates an empty directive with the place for \a NumClauses
   /// clauses.

diff  --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp
index 84a4de00328a8..15e13da27dd84 100644
--- a/clang/lib/AST/StmtOpenMP.cpp
+++ b/clang/lib/AST/StmtOpenMP.cpp
@@ -866,19 +866,17 @@ OMPOrderedDirective 
*OMPOrderedDirective::CreateEmpty(const ASTContext &C,
 OMPAtomicDirective *
 OMPAtomicDirective::Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc, ArrayRef 
Clauses,
-   Stmt *AssociatedStmt, Expr *X, Expr *V, Expr *E,
-   Expr *UE, Expr *D, Expr *Cond, bool IsXLHSInRHSPart,
-   bool IsPostfixUpdate) {
+   Stmt *AssociatedStmt, Expressions Exprs) {
   auto *Dir = createDirective(
   C, Clauses, AssociatedStmt, /*NumChildren=*/6, StartLoc, EndLoc);
-  Dir->setX(X);
-  Dir->setV(V);
-  Dir->setExpr(E);
-  Dir->setUpdateExpr(UE);
-  Dir->setD(D);
-  Dir->setCond(Cond);
-  Dir->IsXLHSInRHSPart = IsXLHSInRHSPart;
-  Dir->IsPostfixUpdate = IsPostfixUpdate;
+  Dir->setX(Exprs.X);
+  Dir->setV(Exprs.V);
+  Dir->setExpr(Exprs.E);
+  Dir->setUpdateExpr(Exprs.UE);
+  Dir->setD(Exprs.D);
+  Dir->setCond(Exprs.Cond);
+  Dir->IsXLHSInRHSPart = Exprs.IsXLHSInRHSPart;
+  Dir->IsPostfixUpdate = Exprs.IsPostf

[clang] c7d4a05 - Properly identify builtins in a diagnostic note

2022-04-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-15T11:46:13-04:00
New Revision: c7d4a05228090cb6b1b7f6e5d300f197897ac756

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

LOG: Properly identify builtins in a diagnostic note

When emitting a "conflicting types" warning for a function declaration,
it's more clear to diagnose the previous declaration specifically as
being a builtin if it one.

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/prototype-redecls.c

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 0708e687c5752..76bf67397a6ee 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3256,6 +3256,10 @@ getNoteDiagForInvalidRedeclaration(const T *Old, const T 
*New) {
 PrevDiag = diag::note_previous_definition;
   else if (Old->isImplicit()) {
 PrevDiag = diag::note_previous_implicit_declaration;
+if (const auto *FD = dyn_cast(Old)) {
+  if (FD->getBuiltinID())
+PrevDiag = diag::note_previous_builtin_declaration;
+}
 if (OldLocation.isInvalid())
   OldLocation = New->getLocation();
   } else

diff  --git a/clang/test/Sema/prototype-redecls.c 
b/clang/test/Sema/prototype-redecls.c
index 9b85753cbbb5b..ca3355f79d69a 100644
--- a/clang/test/Sema/prototype-redecls.c
+++ b/clang/test/Sema/prototype-redecls.c
@@ -22,3 +22,10 @@ void derp(x) int x; {}
 void garp(int);
 void garp();
 void garp(x) int x; {}
+
+// Ensure redeclarations that conflict with a builtin use a note which makes it
+// clear that the previous declaration was a builtin.
+float rintf() { // expected-error {{conflicting types for 'rintf'}} \
+   expected-note {{'rintf' is a builtin with type 'float 
(float)'}}
+  return 1.0f;
+}



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


[PATCH] D123627: Correctly diagnose prototype redeclaration errors in C

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D123627#3452491 , @efriedma wrote:

>> The reason you get the weird behavior with the note pointing to the same 
>> line as the declaration is because rintf() is a predefined builtin: 
>> https://godbolt.org/z/j3W759M7a (note the same lovely diagnostic note 
>> behavior).
>
> It points at the same location, but at least it says "'rintf' is a builtin" 
> (diag::note_previous_builtin_declaration).  The new codepath specifically 
> skips the code which emits that note.

This situation should now be improved in 
c7d4a05228090cb6b1b7f6e5d300f197897ac756 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123627

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


[PATCH] D123826: Fix size of flexible array initializers, and re-enable assertions.

2022-04-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/AST/Decl.cpp:2735
+  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
+  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
+  if (!InitTy)

erichkeane wrote:
> Same here
You want something like this?

```
if (auto *List = dyn_cast(getInit()->IgnoreParens())) {
  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
  if (auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType())) {
return InitTy->getSize() != 0;
  }
}
return false;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123826

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


[PATCH] D123826: Fix size of flexible array initializers, and re-enable assertions.

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/Decl.cpp:2735
+  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
+  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
+  if (!InitTy)

efriedma wrote:
> erichkeane wrote:
> > Same here
> You want something like this?
> 
> ```
> if (auto *List = dyn_cast(getInit()->IgnoreParens())) {
>   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
>   if (auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType())) {
> return InitTy->getSize() != 0;
>   }
> }
> return false;
> ```
ah, shucks, i missed that this was an early exit (that is, I missed the '!').  
Disregard.  LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123826

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


[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 423120.
royjacobson added a comment.

Split the 'can compare constraints' code into a static function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp

Index: clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp
===
--- /dev/null
+++ clang/test/CXX/temp/temp.decls/temp.fct/temp.func.order/p6.cpp
@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+
+struct A;
+struct B;
+
+template  constexpr bool True = true;
+template  concept C = True;
+
+void f(C auto &, auto &) = delete;
+template  void f(Q &, C auto &);
+
+void g(struct A *ap, struct B *bp) {
+  f(*ap, *bp);
+}
+
+template  struct X {};
+
+template  bool operator==(X, V) = delete;
+templatebool operator==(T, X);
+
+bool h() {
+  return X{} == 0;
+}
+
+namespace PR53640 {
+
+template 
+concept C = true;
+
+template 
+void f(T t) {} // expected-note {{candidate function [with T = int]}}
+
+template 
+void f(const T &t) {} // expected-note {{candidate function [with T = int]}}
+
+int g() {
+  f(0); // expected-error {{call to 'f' is ambiguous}}
+}
+
+struct S {
+  template  explicit S(T) noexcept requires C {} // expected-note {{candidate constructor}}
+  template  explicit S(const T &) noexcept {}   // expected-note {{candidate constructor}}
+};
+
+int h() {
+  S s(4); // expected-error-re {{call to constructor of {{.*}} is ambiguous}}
+}
+
+}
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5143,18 +5143,20 @@
 /// candidate with a reversed parameter order. In this case, the corresponding
 /// P/A pairs between FT1 and FT2 are reversed.
 ///
+/// \param AllowOrderingByConstraints If \c is false, don't check whether one
+/// of the templates is more constrained than the other. Default is true.
+///
 /// \returns the more specialized function template. If neither
 /// template is more specialized, returns NULL.
-FunctionTemplateDecl *
-Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
- FunctionTemplateDecl *FT2,
- SourceLocation Loc,
- TemplatePartialOrderingContext TPOC,
- unsigned NumCallArguments1,
- unsigned NumCallArguments2,
- bool Reversed) {
-
-  auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * {
+FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
+FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
+TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
+unsigned NumCallArguments2, bool Reversed,
+bool AllowOrderingByConstraints) {
+
+  auto JudgeByConstraints = [&]() -> FunctionTemplateDecl * {
+if (!AllowOrderingByConstraints)
+  return nullptr;
 llvm::SmallVector AC1, AC2;
 FT1->getAssociatedConstraints(AC1);
 FT2->getAssociatedConstraints(AC2);
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -2952,24 +2952,30 @@
 }
 
 /// FunctionParamTypesAreEqual - This routine checks two function proto types
-/// for equality of their argument types. Caller has already checked that
-/// they have same number of arguments.  If the parameters are different,
+/// for equality of their parameter types. Caller has already checked that
+/// they have same number of parameters.  If the parameters are different,
 /// ArgPos will have the parameter index of the first different parameter.
+/// If `Reversed` is true, the parameters of `NewType` will be compared in
+/// reverse order. That's useful if one of the functions is being used as a C++20
+/// synthesized operator overload with a reversed parameter order.
 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
   const FunctionProtoType *NewType,
-  unsigned *ArgPos) {
-  for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
-  N = NewType->param_type_begin(),
-  E = OldType->param_type_end();
-   O && (O != E); ++O, ++N) {
+  unsigned *ArgPos, bool Reversed) {
+  assert(OldType->getNumParams() == NewType->getNumParams() &&
+ "Can't compare

[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson marked 2 inline comments as done.
royjacobson added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:9829
+  bool CanCompareConstraints = false;
+  if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
+  Cand2.Function->hasPrototype()) {

erichkeane wrote:
> royjacobson wrote:
> > erichkeane wrote:
> > > Since the point of this is to just calculate the CanCompareConstraints, I 
> > > think it should be a separate function called below where it is used.  
> > Do you mean as in a separate `Sema` function? Or a local lambda?
> Just a static function is fine, basically its a whole lot of work happening 
> in this function for a single result, so I'm suggesting splitting off the 
> calculation for `CanCompareConstraints` into its own function, so you get:
> 
> `bool CanCompareConstrants = new_function(...);`
Done


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

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


[PATCH] D123182: [Concepts] Fix overload resolution bug with constrained candidates

2022-04-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

I'm happy with this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123182

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


[PATCH] D123771: [clang][lex] NFCI: Use DirectoryEntryRef in HeaderSearch::load*()

2022-04-15 Thread Ben Barham via Phabricator via cfe-commits
bnbarham accepted this revision.
bnbarham added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Lex/HeaderSearch.cpp:1583
+::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath);
+assert(TopFrameworkDir && "Could not find the top-most framework dir");
 

jansvoboda11 wrote:
> bnbarham wrote:
> > Can we just return false in this case, or is it definitely always a logic 
> > error?
> I agree returning `false` here would be better, but I wanted to keep this 
> patch as NFC as possible. How about I make that change in a follow-up patch?
Sure. It would have been a segfault before, so I assume it must never happen 
anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123771

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


[PATCH] D121984: [RISCV] Moving RVV intrinsic type related util to clang/Support

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a reviewer: rsmith.
aaron.ballman added a subscriber: rsmith.
aaron.ballman added a comment.

In D121984#3453976 , @kito-cheng 
wrote:

>> Thank you for the explanation. I still don't think this is really "Support" 
>> material, but I'm also struggling to think of a better place to put it in an 
>> existing directory in Clang aside from Basic, but that would still be a bit 
>> of a layering violation it feels like. So I think I'm convinced that Support 
>> is a reasonable place to put it.
>
> Actually I tried to put that on clang/Basic before, and end up with the 
> clang/Basic is depended on clang-tblgen, and that made clang-tblgen depend on 
> clang/Basic...then CMake report error for circular dependency :P

Yup, that's exactly the issue I was thinking we'd hit. :-)

>> Should it live within a RISCV direction inside of the Support directory? Or 
>> should we use folders like that for host platform support files instead of 
>> target platform support files (as the LLVM Support directory appears to do)?
>
> I saw LLVM/Support are just target specific file on the folder instead of 
> many target folder, I guess there should not be too much target specific 
> files in clang/Support, and we could reorg the folder organization once it 
> getting complicated? What do you think?

Yeah, I think that's likely reasonable.

Giving my LGTM but adding @rsmith in case he has any code owner concerns over 
it. If you don't hear any concerns by Tue of next week, I think you're fine to 
land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121984

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


[PATCH] D123854: [clang][lex] NFCI: Use DirectoryEntryRef in FrameworkCacheEntry

2022-04-15 Thread Ben Barham via Phabricator via cfe-commits
bnbarham accepted this revision.
bnbarham added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Lex/HeaderSearch.cpp:584
   // If it is known and in some other directory, fail.
-  if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir())
+  if (CacheEntry.Directory && *CacheEntry.Directory != getFrameworkDir())
 return None;





Comment at: clang/lib/Lex/HeaderSearch.cpp:607
 // If the framework dir doesn't exist, we fail.
 auto Dir = FileMgr.getDirectory(FrameworkName);
 if (!Dir)

Is the plan to do these ones in later commits? Ie. this just does what's needed 
for `FrameworkCacheEntry`?



Comment at: clang/lib/Lex/HeaderSearch.cpp:1192
 // framework.
 CacheLookup.second.Directory = *Dir;
   }

Don't need the `*`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123854

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


[PATCH] D123856: [clang][lex] NFCI: Use FileEntryRef in ModuleMap::diagnoseHeaderInclusion()

2022-04-15 Thread Ben Barham via Phabricator via cfe-commits
bnbarham accepted this revision.
bnbarham added a comment.
This revision is now accepted and ready to land.

Shadowing of `FE` almost tripped me up there 😅


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123856

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


[PATCH] D123300: [Clang] Enable opaque pointers by default

2022-04-15 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

  $ cat /tmp/a.ll 
  target triple = "thumbv8-unknown-linux-gnueabihf"
  
  define void @zot() {
  bb:
br label %bb1
  
  bb1:  ; preds = %bb1, %bb
%tmp = phi ptr [ null, %bb ], [ %tmp2, %bb1 ]
store ptr %tmp, ptr %tmp, align 4
%tmp2 = getelementptr inbounds ptr, ptr %tmp, i32 1
%tmp3 = icmp eq ptr %tmp2, null
br i1 %tmp3, label %bb4, label %bb1
  
  bb4:  ; preds = %bb1
ret void
  }
  $ opt -passes=loop-vectorize /tmp/a.ll -disable-output
  # crash


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123300

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


[PATCH] D123642: [clang codegen] Assume arguments of __atomic_* are aligned.

2022-04-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

> Have we verified that this is the rule that GCC uses? Is it true even if e.g. 
> the pointer expression is the address of a variable with a known alignment, 
> or if the pointer has an explicitly-aligned type (e.g. with an aligned 
> typedef)?

As far as I can tell, if the type's size is a power of two, and there's an 
inline atomic sequence available, gcc will use an inline sequence that assumes 
the address is naturally aligned.  Otherwise, it makes the libcall.  I've tried 
a variety of ways of writing the operation; alignment doesn't matter at all, no 
matter what the alignment actually is.

Oddly, `__atomic_is_lock_free`/`__atomic_always_lock_free` do care about the 
alignment, though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123642

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


[PATCH] D123862: [Clang][OpenMP] Use bitfields for flags in `OMPAtomicDirective`

2022-04-15 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 created this revision.
tianshilei1992 added reviewers: ABataev, jdoerfert.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
tianshilei1992 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123862

Files:
  clang/include/clang/AST/StmtOpenMP.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp


Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2449,8 +2449,8 @@
 void ASTStmtReader::VisitOMPAtomicDirective(OMPAtomicDirective *D) {
   VisitStmt(D);
   VisitOMPExecutableDirective(D);
-  D->IsXLHSInRHSPart = Record.readBool();
-  D->IsPostfixUpdate = Record.readBool();
+  D->Flags.IsXLHSInRHSPart = Record.readBool() ? 1 : 0;
+  D->Flags.IsPostfixUpdate = Record.readBool() ? 1 : 0;
 }
 
 void ASTStmtReader::VisitOMPTargetDirective(OMPTargetDirective *D) {
Index: clang/lib/AST/StmtOpenMP.cpp
===
--- clang/lib/AST/StmtOpenMP.cpp
+++ clang/lib/AST/StmtOpenMP.cpp
@@ -875,8 +875,8 @@
   Dir->setUpdateExpr(Exprs.UE);
   Dir->setD(Exprs.D);
   Dir->setCond(Exprs.Cond);
-  Dir->IsXLHSInRHSPart = Exprs.IsXLHSInRHSPart;
-  Dir->IsPostfixUpdate = Exprs.IsPostfixUpdate;
+  Dir->Flags.IsXLHSInRHSPart = Exprs.IsXLHSInRHSPart ? 1 : 0;
+  Dir->Flags.IsPostfixUpdate = Exprs.IsPostfixUpdate ? 1 : 0;
   return Dir;
 }
 
Index: clang/include/clang/AST/StmtOpenMP.h
===
--- clang/include/clang/AST/StmtOpenMP.h
+++ clang/include/clang/AST/StmtOpenMP.h
@@ -2827,25 +2827,28 @@
 class OMPAtomicDirective : public OMPExecutableDirective {
   friend class ASTStmtReader;
   friend class OMPExecutableDirective;
-  /// Used for 'atomic update' or 'atomic capture' constructs. They may
-  /// have atomic expressions of forms
-  /// \code
-  /// x = x binop expr;
-  /// x = expr binop x;
-  /// \endcode
-  /// This field is true for the first form of the expression and false for the
-  /// second. Required for correct codegen of non-associative operations (like
-  /// << or >>).
-  bool IsXLHSInRHSPart = false;
-  /// Used for 'atomic update' or 'atomic capture' constructs. They may
-  /// have atomic expressions of forms
-  /// \code
-  /// v = x; ;
-  /// ; v = x;
-  /// \endcode
-  /// This field is true for the first(postfix) form of the expression and 
false
-  /// otherwise.
-  bool IsPostfixUpdate = false;
+
+  struct FlagTy {
+/// Used for 'atomic update' or 'atomic capture' constructs. They may
+/// have atomic expressions of forms:
+/// \code
+/// x = x binop expr;
+/// x = expr binop x;
+/// \endcode
+/// This field is 1 for the first form of the expression and 0 for the
+/// second. Required for correct codegen of non-associative operations 
(like
+/// << or >>).
+uint8_t IsXLHSInRHSPart : 1;
+/// Used for 'atomic update' or 'atomic capture' constructs. They may
+/// have atomic expressions of forms:
+/// \code
+/// v = x; ;
+/// ; v = x;
+/// \endcode
+/// This field is 1 for the first(postfix) form of the expression and 0
+/// otherwise.
+uint8_t IsPostfixUpdate : 1;
+  } Flags;
 
   /// Build directive with the given start and end location.
   ///
@@ -2956,10 +2959,10 @@
   /// Return true if helper update expression has form
   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form
   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
-  bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
+  bool isXLHSInRHSPart() const { return Flags.IsXLHSInRHSPart; }
   /// Return true if 'v' expression must be updated to original value of
   /// 'x', false if 'v' must be updated to the new value of 'x'.
-  bool isPostfixUpdate() const { return IsPostfixUpdate; }
+  bool isPostfixUpdate() const { return Flags.IsPostfixUpdate; }
   /// Get 'v' part of the associated expression/statement.
   Expr *getV() {
 return cast_or_null(Data->getChildren()[DataPositionTy::POS_V]);


Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2449,8 +2449,8 @@
 void ASTStmtReader::VisitOMPAtomicDirective(OMPAtomicDirective *D) {
   VisitStmt(D);
   VisitOMPExecutableDirective(D);
-  D->IsXLHSInRHSPart = Record.readBool();
-  D->IsPostfixUpdate = Record.readBool();
+  D->Flags.IsXLHSInRHSPart = Record.readBool() ? 1 : 0;
+  D->Flags.IsPostfixUpdate = Record.readBool() ? 1 : 0;
 }
 
 void ASTStmtReader::VisitOMPTargetDirective(OMPTargetDirective *D) {
Index: clang/lib/AST/StmtOpenMP.cpp
=

[PATCH] D123649: Allow flexible array initialization in C++.

2022-04-15 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

For posterity, posting the link to the failure this caused in Linaro's TCWG's 
CI of kernel builds w/ clang: 
https://lore.kernel.org/llvm/906914372.14298.1650022522881@jenkins.jenkins/.

I'm guessing D123826  fixes this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123649

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


[PATCH] D120290: [Clang][OpenMP] Add the codegen support for `atomic compare capture`

2022-04-15 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 423132.
tianshilei1992 added a comment.
Herald added a project: All.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120290

Files:
  clang/include/clang/AST/StmtOpenMP.h
  clang/lib/AST/StmtOpenMP.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/OpenMP/atomic_compare_codegen.cpp

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


[PATCH] D120290: [Clang][OpenMP] Add the codegen support for `atomic compare capture`

2022-04-15 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 marked 3 inline comments as done.
tianshilei1992 added inline comments.



Comment at: clang/include/clang/AST/StmtOpenMP.h:2835-2847
   bool IsXLHSInRHSPart = false;
   /// Used for 'atomic update' or 'atomic capture' constructs. They may
   /// have atomic expressions of forms
   /// \code
   /// v = x; ;
   /// ; v = x;
   /// \endcode

tianshilei1992 wrote:
> ABataev wrote:
> > Transform these booleans to bitfields?
> Will do in another patch.
In D123862.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:6216
-  KindsEncountered.contains(OMPC_capture)) {
-IsCompareCapture = true;
 Kind = OMPC_compare;

ABataev wrote:
> tianshilei1992 wrote:
> > ABataev wrote:
> > > Can this be fixed in a separate patch?
> > Well, I think it's part of this patch because we can't tell if it's compare 
> > or compare capture before, but now we can. If we really want to do that, we 
> > can have another patch including all changes in this patch related to 
> > `OMPAtomicDirective`.
> Kind of NFC? Would be good
I think we don't need an extra NFC patch for this part because it's not gonna 
be very neat w/o some other code in this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120290

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


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Sema/init-randomized-struct.c:30
+} __attribute__((randomize_layout));
+
+struct other_test t5 = { .a = foo, .b[0] = foo }; // Okay

MaskRay wrote:
> Perhaps test an empty struct with randomize_layout and a struct with one 
> field with randomize_layout?
Good point -- there's really no reason to reject something like:
```
struct degenerate {
  func_ptr a;
};

struct degenerate d= { foo };
```
even though it's not doing a zero initialization.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[PATCH] D123534: [dwarf] Emit a DIGlobalVariable for constant strings.

2022-04-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

This seems like it would significantly introduce debug info size for at least 
some kinds of code - have you done any size measurements of this change?

What does the resulting DWARF look like?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123534

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


[PATCH] D123862: [Clang][OpenMP] Use bitfields for flags in `OMPAtomicDirective`

2022-04-15 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

What about ASTStmtWriter?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123862

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


[clang] 8fd3b5d - Fix an edge case in determining is a function has a prototype

2022-04-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-15T14:04:07-04:00
New Revision: 8fd3b5de3f96300189a2841278e6c7b6654bffc5

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

LOG: Fix an edge case in determining is a function has a prototype

Given the declaration:

  typedef void func_t(unsigned);
  __attribute__((noreturn)) func_t func;

we would incorrectly determine that `func` had no prototype because the
`noreturn` attribute would convert the underlying type directly into a
FunctionProtoType, but the declarator for `func` itself was not one for
a function with a prototype. This adds an additional check for when the
declarator is a type representation for a function with a prototype.

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/warn-strict-prototypes.c

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 76bf67397a6ee..499c70e087898 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8803,15 +8803,21 @@ static FunctionDecl *CreateNewFunctionDecl(Sema 
&SemaRef, Declarator &D,
   bool isInline = D.getDeclSpec().isInlineSpecified();
 
   if (!SemaRef.getLangOpts().CPlusPlus) {
-// Determine whether the function was written with a
-// prototype. This true when:
+// Determine whether the function was written with a prototype. This is
+// true when:
 //   - there is a prototype in the declarator, or
 //   - the type R of the function is some kind of typedef or other non-
 // attributed reference to a type name (which eventually refers to a
-// function type).
+// function type). Note, we can't always look at the adjusted type to
+// check this case because attributes may cause a non-function
+// declarator to still have a function type. e.g.,
+//   typedef void func(int a);
+//   __attribute__((noreturn)) func other_func; // This has a prototype
 bool HasPrototype =
-  (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
-  (!R->getAsAdjusted() && R->isFunctionProtoType());
+(D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
+(D.getDeclSpec().isTypeRep() &&
+ D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
+(!R->getAsAdjusted() && R->isFunctionProtoType());
 
 NewFD = FunctionDecl::Create(
 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,

diff  --git a/clang/test/Sema/warn-strict-prototypes.c 
b/clang/test/Sema/warn-strict-prototypes.c
index 4dc7913cd33e7..e2cd4dcddc4c0 100644
--- a/clang/test/Sema/warn-strict-prototypes.c
+++ b/clang/test/Sema/warn-strict-prototypes.c
@@ -80,3 +80,13 @@ void foo13(...) __attribute__((overloadable)) {}
 void foo14(void) {
   foo14_call(); // no-warning
 }
+
+// Ensure that redeclarations involving a typedef type work properly, even if
+// there are function attributes involved in the declaration.
+typedef void foo_t(unsigned val);
+__attribute__((noreturn)) foo_t foo15;
+foo_t foo15; // OK
+void foo15(unsigned val); // OK
+
+foo_t foo16;
+void foo16(unsigned val); // OK



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


[PATCH] D123862: [Clang][OpenMP] Use bitfields for flags in `OMPAtomicDirective`

2022-04-15 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 added a comment.

In D123862#3454380 , @ABataev wrote:

> What about ASTStmtWriter?

It's using accessor function `isXLHSInRHSPart()` and so on.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123862

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122983#3452994 , @rsmith wrote:

> I think we should just make this an error by default in C99 onwards;

Out of curiosity -- do you think we should remove the `DefaultIgnore` in C89 
mode so that we warn by default there (perhaps as a follow up)? Also, I presume 
you expect `diag::ext_implicit_lib_function_decl` to behave the same way (warn 
in C89, warn-as-err in C99 and up) as part of this patch?


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

https://reviews.llvm.org/D122983

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


[PATCH] D123862: [Clang][OpenMP] Use bitfields for flags in `OMPAtomicDirective`

2022-04-15 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123862

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


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 423139.
void added a comment.

Add tests for empty and single element structs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/Sema/init-randomized-struct.c

Index: clang/test/Sema/init-randomized-struct.c
===
--- /dev/null
+++ clang/test/Sema/init-randomized-struct.c
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -frandomize-layout-seed=1234567890abcdef
+
+typedef void (*func_ptr)();
+
+void foo(void);
+void bar(void);
+void baz(void);
+void gaz(void);
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((randomize_layout));
+
+struct test t1 = {}; // This should be fine per WG14 N2900 (in C23) + our extension handling of it in earlier modes
+struct test t2 = {0}; // This should also be fine per C99 6.7.8p19
+struct test t3 = { .f = baz, .b = bar, .g = gaz, .a = foo }; // Okay
+struct test t4 = { .a = foo, bar, baz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+
+struct other_test {
+  func_ptr a;
+  func_ptr b[3];
+  func_ptr c;
+} __attribute__((randomize_layout));
+
+struct other_test t5 = { .a = foo, .b[0] = foo }; // Okay
+struct other_test t6 = { .a = foo, .b[0] = foo, bar, baz }; // Okay
+struct other_test t7 = { .a = foo, .b = { foo, bar, baz } }; // Okay
+struct other_test t8 = { baz, bar, gaz, foo }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+struct other_test t9 = { .a = foo, .b[0] = foo, bar, baz, gaz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+
+struct empty_test {
+} __attribute__((randomize_layout));
+
+struct empty_test t10 = {}; // Okay
+
+struct degen_test {
+  func_ptr a;
+} __attribute__((randomize_layout));
+
+struct degen_test t11 = { foo }; // Okay
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -2123,6 +2123,7 @@
   // worthwhile to skip over the rest of the initializer, though.
   RecordDecl *RD = DeclType->castAs()->getDecl();
   RecordDecl::field_iterator FieldEnd = RD->field_end();
+  size_t NumRecordFields = std::distance(RD->field_begin(), RD->field_end());
   bool CheckForMissingFields =
 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
@@ -2172,6 +2173,35 @@
   break;
 }
 
+// Check if this is an initializer of forms:
+//
+//   struct foo f = {};
+//   struct foo g = {0};
+//
+// These are okay for randomized structures. [C99 6.7.8p19]
+//
+// Also, if there is only one element in the structure, we allow something
+// like this, because it's really not randomized in the tranditional sense.
+//
+//   struct foo h = {bar};
+auto IsZeroInitializer = [&](const Expr *I) {
+  if (IList->getNumInits() == 1) {
+if (NumRecordFields == 1)
+  return true;
+if (const auto *IL = dyn_cast(I))
+  return IL->getValue().isZero();
+  }
+  return false;
+};
+
+// Don't allow non-designated initializers on randomized structures.
+if (RD->isRandomized() && !IsZeroInitializer(Init)) {
+  if (!VerifyOnly)
+SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
+  hadError = true;
+  break;
+}
+
 // We've already initialized a member of a union. We're done.
 if (InitializedSomething && DeclType->isUnionType())
   break;
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11602,7 +11602,9 @@
 def err_hlsl_operator_unsupported : Error<
   "the '%select{&|*|->}0' operator is unsupported in HLSL">;
 
-// Layout randomization warning.
+// Layout randomization diagnostics.
+def err_non_designated_init_used : Error<
+  "a randomized struct can only be initialized with a designated initializer">;
 def err_cast_from_randomized_struct : Error<
   "casting from randomized structure pointer type %0 to %1">;
 } // end of sema component.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM, thank you for adding some guard rails for this new feature!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[PATCH] D123642: [clang codegen] Assume arguments of __atomic_* are aligned.

2022-04-15 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

In D123642#3450110 , @efriedma wrote:

>> I disagree with this on principle -- IMO, it is basically a historical bug 
>> in GCC that it ignores the type alignment, and we should NOT try to match 
>> that -- it's dangerous.
>
> gcc has always behaved this way, and I don't see any indication they intend 
> to change it.  I mean, you can call it a bug, but at the end of the day the 
> bug reports will land in our bugtracker, not gcc's.

Have we had many other such bug reports?

On the other hand, I have seen many cases where people wrote code using the 
`__atomic_*` APIs, and pass arguments which are underaligned on some platforms 
(though not the one the code was developed on). Having it be silently 
non-atomic (which is what typically happens with misaligned atomic 
instructions) is just...really nasty.

>> Ask GCC to modify libstdc++ so that `__builtin_addressof` is called 
>> directly, instead of going through `std::__addressof`.
>
> Even if gcc did this today, it would take years to reach people on Linux.

True, but the behavior in the meantime is correct. And given the apparent lack 
of widespread issues, I'm not sure it much matters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123642

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


[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.

LGTM, too.

It may be worthwhile adding a file-level comment at the header.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

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


[PATCH] D123649: Allow flexible array initialization in C++.

2022-04-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

6cf0b1b3  
was a temporary fix to stop the crash. D123826 
 is the full fix to make the assertion 
actually work correctly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123649

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-15 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

In D122983#3454406 , @aaron.ballman 
wrote:

> In D122983#3452994 , @rsmith wrote:
>
>> I think we should just make this an error by default in C99 onwards;
>
> Out of curiosity -- do you think we should remove the `DefaultIgnore` in C89 
> mode so that we warn by default there (perhaps as a follow up)? Also, I 
> presume you expect `diag::ext_implicit_lib_function_decl` to behave the same 
> way (warn in C89, warn-as-err in C99 and up) as part of this patch?

I'm not sure what purpose it'd serve to change -std=c89 to be more strict at 
this point. It's not the default compilation mode, and the code is actually 
valid under that standard. IMO, adding such a on-by-default warning there would 
only serve to annoy folks explicitly trying to build super-old code with a 
super-old standards version.


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

https://reviews.llvm.org/D122983

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


[clang] 4802edd - Fix size of flexible array initializers, and re-enable assertions.

2022-04-15 Thread Eli Friedman via cfe-commits

Author: Eli Friedman
Date: 2022-04-15T12:09:57-07:00
New Revision: 4802edd1ac7a5aea8c8488b5baec221d722cbdde

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

LOG: Fix size of flexible array initializers, and re-enable assertions.

In D123649, I got the formula for getFlexibleArrayInitChars slightly
wrong: the flexible array elements can be contained in the tail padding
of the struct.  Fix the formula to account for that.

With the fixed formula, we run into another issue: in some cases, we
were emitting extra padding for flexible arrray initializers. Fix
CGExprConstant so it uses a packed struct when necessary, to avoid this
extra padding.

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

Added: 


Modified: 
clang/include/clang/AST/Decl.h
clang/lib/AST/Decl.cpp
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGExprConstant.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/flexible-array-init.c
clang/test/CodeGenCXX/flexible-array-init.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 5816a91bd0c2d..f93008cdd322d 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -1591,12 +1591,18 @@ class VarDecl : public DeclaratorDecl, public 
Redeclarable {
   /// kind?
   QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
 
-  /// If this variable declares a struct with a flexible array member, and
-  /// the flexible array member is initialized with one or more elements,
-  /// compute the number of bytes necessary to store those elements.
+  /// Whether this variable has a flexible array member initialized with one
+  /// or more elements. This can only be called for declarations where
+  /// hasInit() is true.
   ///
   /// (The standard doesn't allow initializing flexible array members; this is
   /// a gcc/msvc extension.)
+  bool hasFlexibleArrayInit(const ASTContext &Ctx) const;
+
+  /// If hasFlexibleArrayInit is true, compute the number of additional bytes
+  /// necessary to store those elements. Otherwise, returns zero.
+  ///
+  /// This can only be called for declarations where hasInit() is true.
   CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const;
 
   // Implement isa/cast/dyncast/etc.

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 915d8db10aca4..050c3ad2dafc6 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -31,6 +31,7 @@
 #include "clang/AST/PrettyDeclStackTrace.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/Randstruct.h"
+#include "clang/AST/RecordLayout.h"
 #include "clang/AST/Redeclarable.h"
 #include "clang/AST/Stmt.h"
 #include "clang/AST/TemplateBase.h"
@@ -2722,6 +2723,21 @@ VarDecl::needsDestruction(const ASTContext &Ctx) const {
   return getType().isDestructedType();
 }
 
+bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
+  assert(hasInit() && "Expect initializer to check for flexible array init");
+  auto *Ty = getType()->getAs();
+  if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
+return false;
+  auto *List = dyn_cast(getInit()->IgnoreParens());
+  if (!List)
+return false;
+  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
+  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
+  if (!InitTy)
+return false;
+  return InitTy->getSize() != 0;
+}
+
 CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
   assert(hasInit() && "Expect initializer to check for flexible array init");
   auto *Ty = getType()->getAs();
@@ -2730,11 +2746,17 @@ CharUnits VarDecl::getFlexibleArrayInitChars(const 
ASTContext &Ctx) const {
   auto *List = dyn_cast(getInit()->IgnoreParens());
   if (!List)
 return CharUnits::Zero();
-  auto FlexibleInit = List->getInit(List->getNumInits() - 1);
+  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
   if (!InitTy)
 return CharUnits::Zero();
-  return Ctx.getTypeSizeInChars(InitTy);
+  CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
+  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
+  CharUnits FlexibleArrayOffset =
+  Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));
+  if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
+return CharUnits::Zero();
+  return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
 }
 
 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {

diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index 322602606ebe9..e47450f2ba8fe 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -3

[PATCH] D123826: Fix size of flexible array initializers, and re-enable assertions.

2022-04-15 Thread Eli Friedman 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 rG4802edd1ac7a: Fix size of flexible array initializers, and 
re-enable assertions. (authored by efriedma).

Changed prior to commit:
  https://reviews.llvm.org/D123826?vs=422979&id=423146#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123826

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/flexible-array-init.c
  clang/test/CodeGenCXX/flexible-array-init.cpp

Index: clang/test/CodeGenCXX/flexible-array-init.cpp
===
--- clang/test/CodeGenCXX/flexible-array-init.cpp
+++ clang/test/CodeGenCXX/flexible-array-init.cpp
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -o - %s | FileCheck %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm-only -verify -DFAIL1 %s
 // RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm-only -verify -DFAIL2 %s
+// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm-only -verify -DFAIL3 %s
 
 struct A { int x; int y[]; };
 A a = { 1, 7, 11 };
@@ -9,7 +10,7 @@
 A b = { 1, { 13, 15 } };
 // CHECK: @b ={{.*}} global { i32, [2 x i32] } { i32 1, [2 x i32] [i32 13, i32 15] }
 
-int f();
+char f();
 #ifdef FAIL1
 A c = { f(), { f(), f() } }; // expected-error {{cannot compile this flexible array initializer yet}}
 #endif
@@ -18,3 +19,7 @@
   static A d = { f(), { f(), f() } }; // expected-error {{cannot compile this flexible array initializer yet}}
 }
 #endif
+#ifdef FAIL3
+struct B { int x; char y; char z[]; };
+B e = {f(), f(), f(), f()}; // expected-error {{cannot compile this flexible array initializer yet}}
+#endif
Index: clang/test/CodeGen/flexible-array-init.c
===
--- clang/test/CodeGen/flexible-array-init.c
+++ clang/test/CodeGen/flexible-array-init.c
@@ -18,7 +18,5 @@
 struct __attribute((packed, aligned(4))) { char a; int x; char z[]; } e = { 1, 2, { 13, 15, 17, 19 } };
 // CHECK: @e ={{.*}} <{ i8, i32, [4 x i8] }> <{ i8 1, i32 2, [4 x i8] c"\0D\0F\11\13" }>
 
-// FIXME: This global should be 6 bytes, not 8.  Not likely to matter in most
-// cases, but still a bug.
 struct { int x; char y[]; } f = { 1, { 13, 15 } };
-// CHECK: @f ={{.*}} global { i32, [2 x i8] } { i32 1, [2 x i8] c"\0D\0F" }
+// CHECK: @f ={{.*}} global <{ i32, [2 x i8] }> <{ i32 1, [2 x i8] c"\0D\0F" }>
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -4615,7 +4615,7 @@
 T = D->getType();
 
   if (getLangOpts().CPlusPlus) {
-if (!InitDecl->getFlexibleArrayInitChars(getContext()).isZero())
+if (InitDecl->hasFlexibleArrayInit(getContext()))
   ErrorUnsupported(D, "flexible array initializer");
 Init = EmitNullConstant(T);
 NeedsGlobalCtor = true;
@@ -4631,17 +4631,12 @@
   if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
 DelayedCXXInitPosition.erase(D);
 
-#if 0
-  // FIXME: The following check doesn't handle flexible array members
-  // inside tail padding (which don't actually increase the size of
-  // the struct).
 #ifndef NDEBUG
   CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) +
   InitDecl->getFlexibleArrayInitChars(getContext());
   CharUnits CstSize = CharUnits::fromQuantity(
   getDataLayout().getTypeAllocSize(Init->getType()));
   assert(VarSize == CstSize && "Emitted constant has unexpected size");
-#endif
 #endif
 }
   }
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -439,22 +439,33 @@
 // Can't emit as an array, carry on to emit as a struct.
   }
 
+  // The size of the constant we plan to generate.  This is usually just
+  // the size of the initialized type, but in AllowOversized mode (i.e.
+  // flexible array init), it can be larger.
   CharUnits DesiredSize = Utils.getSize(DesiredTy);
+  if (Size > DesiredSize) {
+assert(AllowOversized && "Elems are oversized");
+DesiredSize = Size;
+  }
+
+  // The natural alignment of an unpacked LLVM struct with the given elements.
   CharUnits Align = CharUnits::One();
   for (llvm::Constant *C : Elems)
 Align = std::max(Align, Utils.getAlignment(C));
+
+  // The natural size of an unpacked LLVM struct with the given elements.
   CharUnits AlignedSize = Size.alignTo(Align);
 
   bool Packed = false;
   ArrayRef UnpackedElems = Elems;
   llvm::SmallVector UnpackedElemStorag

[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D122983#3454494 , @jyknight wrote:

> In D122983#3454406 , @aaron.ballman 
> wrote:
>
>> In D122983#3452994 , @rsmith wrote:
>>
>>> I think we should just make this an error by default in C99 onwards;
>>
>> Out of curiosity -- do you think we should remove the `DefaultIgnore` in C89 
>> mode so that we warn by default there (perhaps as a follow up)? Also, I 
>> presume you expect `diag::ext_implicit_lib_function_decl` to behave the same 
>> way (warn in C89, warn-as-err in C99 and up) as part of this patch?
>
> I'm not sure what purpose it'd serve to change -std=c89 to be more strict at 
> this point. It's not the default compilation mode, and the code is actually 
> valid under that standard. IMO, adding such a on-by-default warning there 
> would only serve to annoy folks explicitly trying to build super-old code 
> with a super-old standards version.

Yeah, I was waffling on that one -- my thinking was that it would at least warn 
users that they're using something dangerous and we're going to break them if 
they attempt to upgrade (aka, we treat it as almost-deprecated in C89). But I'm 
fine leaving that one as `DefaultIgnore` too; as you say, if someone is in that 
mode explicitly, this IS a "feature" of that language.

I feel a bit more strongly that implicit builtins should be handled the same as 
other implicit functions (in terms of `DefaultError` behavior), unless there's 
some scenarios I'm not thinking of.


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

https://reviews.llvm.org/D122983

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


[clang] 721651b - [HLSL][clang][Driver] Support target profile command line option.

2022-04-15 Thread Chris Bieneman via cfe-commits

Author: Xiang Li
Date: 2022-04-15T14:18:18-05:00
New Revision: 721651be246e26efd767c3ec55c8f06c7b5a9a3d

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

LOG: [HLSL][clang][Driver] Support target profile command line option.

The target profile option(/T) decide the shader model when compile hlsl.
The format is shaderKind_major_minor like ps_6_1.
The shader model is saved as llvm::Triple is clang/llvm like
dxil-unknown-shadermodel6.1-hull.
The main job to support the option is translating ps_6_1 into
shadermodel6.1-pixel.
That is done inside tryParseProfile  at HLSL.cpp.

To integrate the option into clang Driver, a new DriverMode DxcMode is
created. When DxcMode is enabled, OSType for TargetTriple will be
forced into Triple::ShaderModel. And new ToolChain HLSLToolChain will
be created when OSType is Triple::ShaderModel.

In HLSLToolChain, ComputeEffectiveClangTriple is overridden to call
tryParseProfile when targetProfile option is set.

To make test work, Fo option is added and .hlsl is added for active
-xhlsl.

Reviewed By: beanz

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

Patch by: Xiang Li 

Added: 
clang/lib/Driver/ToolChains/HLSL.cpp
clang/lib/Driver/ToolChains/HLSL.h

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Driver.h
clang/include/clang/Driver/Options.h
clang/include/clang/Driver/Options.td
clang/lib/Driver/CMakeLists.txt
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChain.cpp
clang/lib/Driver/Types.cpp
clang/test/lit.cfg.py
clang/unittests/Driver/ToolChainTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 64af4c84672fe..cb53804d9e4f8 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -657,4 +657,7 @@ def warn_drv_fjmc_for_elf_only : Warning<
 def err_drv_target_variant_invalid : Error<
   "unsupported '%0' value '%1'; use 'ios-macabi' instead">;
 
+def err_drv_invalid_directx_shader_module : Error<
+  "invalid profile : %0">;
+
 }

diff  --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 6f24f649ea544..b33b64cd9e6a2 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -68,7 +68,8 @@ class Driver {
 GXXMode,
 CPPMode,
 CLMode,
-FlangMode
+FlangMode,
+DXCMode
   } Mode;
 
   enum SaveTempsMode {
@@ -195,6 +196,9 @@ class Driver {
   /// Other modes fall back to calling gcc which in turn calls gfortran.
   bool IsFlangMode() const { return Mode == FlangMode; }
 
+  /// Whether the driver should follow dxc.exe like behavior.
+  bool IsDXCMode() const { return Mode == DXCMode; }
+
   /// Only print tool bindings, don't build any jobs.
   unsigned CCCPrintBindings : 1;
 

diff  --git a/clang/include/clang/Driver/Options.h 
b/clang/include/clang/Driver/Options.h
index 056660192ac5f..f9b9632ee7cbe 100644
--- a/clang/include/clang/Driver/Options.h
+++ b/clang/include/clang/Driver/Options.h
@@ -35,7 +35,8 @@ enum ClangFlags {
   FlangOption = (1 << 14),
   FC1Option = (1 << 15),
   FlangOnlyOption = (1 << 16),
-  Ignored = (1 << 17),
+  DXCOption = (1 << 17),
+  Ignored = (1 << 18),
 };
 
 enum ID {

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 104c8ea8483d1..f454bd038ecf8 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -49,6 +49,10 @@ def CC1Option : OptionFlag;
 // CC1AsOption - This option should be accepted by clang -cc1as.
 def CC1AsOption : OptionFlag;
 
+// DXCOption - This is a dxc.exe compatibility option. Options with this flag
+// are made available when the driver is running in DXC compatibility mode.
+def DXCOption : OptionFlag;
+
 // NoDriverOption - This option should not be accepted by the driver.
 def NoDriverOption : OptionFlag;
 
@@ -6686,3 +6690,33 @@ def _SLASH_Ze : CLFlag<"Ze">;
 def _SLASH_Zg : CLFlag<"Zg">;
 def _SLASH_ZI : CLFlag<"ZI">;
 def _SLASH_ZW : CLJoined<"ZW">;
+
+//===--===//
+// clang-dxc Options
+//===--===//
+
+def dxc_Group : OptionGroup<"">, Flags<[DXCOption]>,
+  HelpText<"dxc compatibility options">;
+
+class DXCJoinedOrSeparate : Option<["/", "-"], name,
+  KIND_JOINED_OR_SEPARATE>, Group, Flags<[DXCOption, 
NoXarchOption]>;
+
+def dxc_help : Option<["/", "-", "--"], "help", KIND_JOINED>,
+  Group, Flags<[DXCOption, NoXarchOption]>, Alias,
+  HelpText<"Display available options">;
+
+
+def Fo : DXCJoinedOrSeparate<"Fo">, Alias,
+ 

[PATCH] D122865: [HLSL][clang][Driver] Support target profile command line option.

2022-04-15 Thread Chris Bieneman 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 rG721651be246e: [HLSL][clang][Driver] Support target profile 
command line option. (authored by python3kgae, committed by beanz).

Changed prior to commit:
  https://reviews.llvm.org/D122865?vs=422677&id=423149#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122865

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/HLSL.cpp
  clang/lib/Driver/ToolChains/HLSL.h
  clang/lib/Driver/Types.cpp
  clang/test/lit.cfg.py
  clang/unittests/Driver/ToolChainTest.cpp

Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -300,6 +300,12 @@
   EXPECT_TRUE(Res.ModeSuffix == "clang-cl");
   EXPECT_STREQ(Res.DriverMode, "--driver-mode=cl");
   EXPECT_FALSE(Res.TargetIsValid);
+
+  Res = ToolChain::getTargetAndModeFromProgramName("clang-dxc");
+  EXPECT_TRUE(Res.TargetPrefix.empty());
+  EXPECT_TRUE(Res.ModeSuffix == "clang-dxc");
+  EXPECT_STREQ(Res.DriverMode, "--driver-mode=dxc");
+  EXPECT_FALSE(Res.TargetIsValid);
 }
 
 TEST(ToolChainTest, CommandOutput) {
@@ -361,4 +367,141 @@
   EXPECT_EQ(getDriverMode(Args[0], llvm::makeArrayRef(Args).slice(1)), "bar");
 }
 
+TEST(DxcModeTest, TargetProfileValidation) {
+  IntrusiveRefCntPtr DiagID(new DiagnosticIDs());
+  struct SimpleDiagnosticConsumer : public DiagnosticConsumer {
+void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
+  const Diagnostic &Info) override {
+  if (DiagLevel == DiagnosticsEngine::Level::Error) {
+Errors.emplace_back();
+Info.FormatDiagnostic(Errors.back());
+  } else {
+Msgs.emplace_back();
+Info.FormatDiagnostic(Msgs.back());
+  }
+}
+void clear() override {
+  Msgs.clear();
+  Errors.clear();
+  DiagnosticConsumer::clear();
+}
+std::vector> Msgs;
+std::vector> Errors;
+  };
+
+  IntrusiveRefCntPtr InMemoryFileSystem(
+  new llvm::vfs::InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile("foo.hlsl", 0,
+  llvm::MemoryBuffer::getMemBuffer("\n"));
+
+  auto *DiagConsumer = new SimpleDiagnosticConsumer;
+  IntrusiveRefCntPtr DiagOpts = new DiagnosticOptions();
+  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagConsumer);
+  Driver TheDriver("/bin/clang", "", Diags, "", InMemoryFileSystem);
+  std::unique_ptr C(
+  TheDriver.BuildCompilation({"clang", "--driver-mode=dxc", "foo.hlsl"}));
+  EXPECT_TRUE(C);
+  EXPECT_TRUE(!C->containsError());
+
+  auto &TC = C->getDefaultToolChain();
+  bool ContainsError = false;
+  auto Args = TheDriver.ParseArgStrings({"-Tvs_6_0"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  auto Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.0-vertex");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Ths_6_1"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.1-hull");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tds_6_2"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.2-domain");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tds_6_2"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.2-domain");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tgs_6_3"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.3-geometry");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tps_6_4"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.4-pixel");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tcs_6_5"}, false, ContainsError);
+  EXPECT_FALSE(ContainsError);
+  Triple = TC.ComputeEffectiveClangTriple(Args);
+  EXPECT_STREQ(Triple.c_str(), "dxil--shadermodel6.5-compute");
+  EXPECT_EQ(Diags.getNumErrors(), 0u);
+
+  Args = TheDriver.ParseArgStrings({"-Tms_6_6"}, false, Contains

[clang] aed923b - [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Bill Wendling via cfe-commits

Author: Bill Wendling
Date: 2022-04-15T12:29:32-07:00
New Revision: aed923b1246ac38335b222b89594516fcf0d6385

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

LOG: [randstruct] Enforce using a designated init for a randomized struct

A randomized structure needs to use a designated or default initializer.
Using a non-designated initializer will result in values being assigned
to the wrong fields.

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

Added: 
clang/test/Sema/init-randomized-struct.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaInit.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a14194d271a71..e79a40d62381f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11602,7 +11602,9 @@ def err_hlsl_pointers_unsupported : Error<
 def err_hlsl_operator_unsupported : Error<
   "the '%select{&|*|->}0' operator is unsupported in HLSL">;
 
-// Layout randomization warning.
+// Layout randomization diagnostics.
+def err_non_designated_init_used : Error<
+  "a randomized struct can only be initialized with a designated initializer">;
 def err_cast_from_randomized_struct : Error<
   "casting from randomized structure pointer type %0 to %1">;
 } // end of sema component.

diff  --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index c3bbefbaaed1b..233be547bf118 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -2123,6 +2123,7 @@ void InitListChecker::CheckStructUnionTypes(
   // worthwhile to skip over the rest of the initializer, though.
   RecordDecl *RD = DeclType->castAs()->getDecl();
   RecordDecl::field_iterator FieldEnd = RD->field_end();
+  size_t NumRecordFields = std::distance(RD->field_begin(), RD->field_end());
   bool CheckForMissingFields =
 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
@@ -2172,6 +2173,35 @@ void InitListChecker::CheckStructUnionTypes(
   break;
 }
 
+// Check if this is an initializer of forms:
+//
+//   struct foo f = {};
+//   struct foo g = {0};
+//
+// These are okay for randomized structures. [C99 6.7.8p19]
+//
+// Also, if there is only one element in the structure, we allow something
+// like this, because it's really not randomized in the tranditional sense.
+//
+//   struct foo h = {bar};
+auto IsZeroInitializer = [&](const Expr *I) {
+  if (IList->getNumInits() == 1) {
+if (NumRecordFields == 1)
+  return true;
+if (const auto *IL = dyn_cast(I))
+  return IL->getValue().isZero();
+  }
+  return false;
+};
+
+// Don't allow non-designated initializers on randomized structures.
+if (RD->isRandomized() && !IsZeroInitializer(Init)) {
+  if (!VerifyOnly)
+SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
+  hadError = true;
+  break;
+}
+
 // We've already initialized a member of a union. We're done.
 if (InitializedSomething && DeclType->isUnionType())
   break;

diff  --git a/clang/test/Sema/init-randomized-struct.c 
b/clang/test/Sema/init-randomized-struct.c
new file mode 100644
index 0..87842e1f19e80
--- /dev/null
+++ b/clang/test/Sema/init-randomized-struct.c
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only 
-frandomize-layout-seed=1234567890abcdef
+
+// Initializing a randomized structure requires a designated initializer,
+// otherwise the element ordering will be off. The only exceptions to this rule
+// are:
+//
+//- A structure with only one element, and
+//- A structure initialized with "{0}".
+//
+// These are well-defined situations where the field ordering doesn't affect
+// the result.
+
+typedef void (*func_ptr)();
+
+void foo(void);
+void bar(void);
+void baz(void);
+void gaz(void);
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((randomize_layout));
+
+struct test t1 = {}; // This should be fine per WG14 N2900 (in C23) + our 
extension handling of it in earlier modes
+struct test t2 = { 0 }; // This should also be fine per C99 6.7.8p19
+struct test t3 = { .f = baz, .b = bar, .g = gaz, .a = foo }; // Okay
+struct test t4 = { .a = foo, bar, baz }; // expected-error {{a randomized 
struct can only be initialized with a designated initializer}}
+
+struct other_test {
+  func_ptr a;
+  func_ptr b[3];
+  func_ptr c;
+} __attribute__((randomize_layout));
+
+struct other_test t5 = { .a = foo, .b[0] = foo }; // Okay
+struct other_test t6 = { .a = foo, .b[0] = foo, 

[PATCH] D123763: [randstruct] Enforce using a designated init for a randomized struct

2022-04-15 Thread Bill Wendling 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 rGaed923b1246a: [randstruct] Enforce using a designated init 
for a randomized struct (authored by void).

Changed prior to commit:
  https://reviews.llvm.org/D123763?vs=423139&id=423151#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123763

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/Sema/init-randomized-struct.c

Index: clang/test/Sema/init-randomized-struct.c
===
--- /dev/null
+++ clang/test/Sema/init-randomized-struct.c
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 %s -verify -fsyntax-only -frandomize-layout-seed=1234567890abcdef
+
+// Initializing a randomized structure requires a designated initializer,
+// otherwise the element ordering will be off. The only exceptions to this rule
+// are:
+//
+//- A structure with only one element, and
+//- A structure initialized with "{0}".
+//
+// These are well-defined situations where the field ordering doesn't affect
+// the result.
+
+typedef void (*func_ptr)();
+
+void foo(void);
+void bar(void);
+void baz(void);
+void gaz(void);
+
+struct test {
+  func_ptr a;
+  func_ptr b;
+  func_ptr c;
+  func_ptr d;
+  func_ptr e;
+  func_ptr f;
+  func_ptr g;
+} __attribute__((randomize_layout));
+
+struct test t1 = {}; // This should be fine per WG14 N2900 (in C23) + our extension handling of it in earlier modes
+struct test t2 = { 0 }; // This should also be fine per C99 6.7.8p19
+struct test t3 = { .f = baz, .b = bar, .g = gaz, .a = foo }; // Okay
+struct test t4 = { .a = foo, bar, baz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+
+struct other_test {
+  func_ptr a;
+  func_ptr b[3];
+  func_ptr c;
+} __attribute__((randomize_layout));
+
+struct other_test t5 = { .a = foo, .b[0] = foo }; // Okay
+struct other_test t6 = { .a = foo, .b[0] = foo, bar, baz }; // Okay
+struct other_test t7 = { .a = foo, .b = { foo, bar, baz } }; // Okay
+struct other_test t8 = { baz, bar, gaz, foo }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+struct other_test t9 = { .a = foo, .b[0] = foo, bar, baz, gaz }; // expected-error {{a randomized struct can only be initialized with a designated initializer}}
+
+struct empty_test {
+} __attribute__((randomize_layout));
+
+struct empty_test t10 = {}; // Okay
+
+struct degen_test {
+  func_ptr a;
+} __attribute__((randomize_layout));
+
+struct degen_test t11 = { foo }; // Okay
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -2123,6 +2123,7 @@
   // worthwhile to skip over the rest of the initializer, though.
   RecordDecl *RD = DeclType->castAs()->getDecl();
   RecordDecl::field_iterator FieldEnd = RD->field_end();
+  size_t NumRecordFields = std::distance(RD->field_begin(), RD->field_end());
   bool CheckForMissingFields =
 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
@@ -2172,6 +2173,35 @@
   break;
 }
 
+// Check if this is an initializer of forms:
+//
+//   struct foo f = {};
+//   struct foo g = {0};
+//
+// These are okay for randomized structures. [C99 6.7.8p19]
+//
+// Also, if there is only one element in the structure, we allow something
+// like this, because it's really not randomized in the tranditional sense.
+//
+//   struct foo h = {bar};
+auto IsZeroInitializer = [&](const Expr *I) {
+  if (IList->getNumInits() == 1) {
+if (NumRecordFields == 1)
+  return true;
+if (const auto *IL = dyn_cast(I))
+  return IL->getValue().isZero();
+  }
+  return false;
+};
+
+// Don't allow non-designated initializers on randomized structures.
+if (RD->isRandomized() && !IsZeroInitializer(Init)) {
+  if (!VerifyOnly)
+SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
+  hadError = true;
+  break;
+}
+
 // We've already initialized a member of a union. We're done.
 if (InitializedSomething && DeclType->isUnionType())
   break;
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11602,7 +11602,9 @@
 def err_hlsl_operator_unsupported : Error<
   "the '%select{&|*|->}0' operator is unsupported in HLSL">;
 
-// Layout randomization warning.
+// Layout randomization diagnostics.
+def err_non_designated_init_used : Error<
+  "a randomized struct can only be initialized with a designated initi

[PATCH] D121959: [clang] Add missing diagnostics for invalid overloads of multiversion functions in C.

2022-04-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

This might've caused a regression? 
(https://github.com/llvm/llvm-project/issues/54892)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121959

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


[PATCH] D123345: Treat `std::move`, `forward`, and `move_if_noexcept` as builtins.

2022-04-15 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D123345#3453037 , @rnk wrote:

> Generally speaking, this sounds like a good idea to me. One time in 2019 I 
> used -ftime-trace+ClangBuildAnalyzer and it told me that std::unique_ptr was 
> the most expensive template 
>  because it is 
> instantiated so much. Those results don't even capture the -O0 object file 
> size impact.
>
> In D123345#3452933 , @rsmith wrote:
>
>> In D123345#3452496 , 
>> @aaron.ballman wrote:
>>
>>> Do you have ideas on how we can improve the debugging checkpoint behavior 
>>> (if at all)?
>>
>> I think we just live with it, like we do for other builtin functions. (There 
>> might be things we can do by emitting inlining info into the debug info. If 
>> we do that, we should presumably do it for all builtin lib functions.)
>
> Honestly, I don't think it's worth the debug info bytes to describe these 
> inlined call sites. Debug info isn't free.

+1 there - and also these operations/intrinsics produce no instructions, so far 
as I understand/know - so for now, LLVM's got to way to represent that anyway 
(there's some talk in DWARF about how to have multiple "states" for a single 
instruction location (so, eg, you could step in/out of an inlined function even 
though you stay at exactly the same instruction))


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123345

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


[PATCH] D121959: [clang] Add missing diagnostics for invalid overloads of multiversion functions in C.

2022-04-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

> This might've caused a regression? 
> (https://github.com/llvm/llvm-project/issues/54892)

@dblaikie, it most definitely did. Note that I'm the author of the patch that 
introduced the regression, the reporter of the regression, and the assignee for 
fixing the regression ;)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121959

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


  1   2   >