[PATCH] D131755: [CMake] Explicit bootstrap options override any passthrough ones.

2022-08-17 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

In D131755#3723366 , @beanz wrote:

> Looks good to me.

Thanks for the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131755

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-17 Thread Michele Scandale via Phabricator via cfe-commits
michele.scandale added a comment.

I can see failures related to this change in a downstream version of clang 
where the default `ClangABICompat` value is not `Latest` (after the followup 
https://reviews.llvm.org/rGda6187f566b7881cb8350621aea9bd582de569b9).
My understanding is that with `-fclang-abi-compat=14` we should get the 
behavior prior to this change. If my understanding is correct, then I'd think 
that such failure shouldn't occur.

These are the tests that I see failing with new diagnostic messages `class 
template partial specialization is not more specialized than the primary 
template` being raised:

  Clang :: CXX/temp/temp.decls/temp.class.spec/p8-0x.cpp
  Clang :: CXX/temp/temp.decls/temp.variadic/example-bind.cpp
  Clang :: CXX/temp/temp.decls/temp.variadic/example-tuple.cpp
  Clang :: CXX/temp/temp.decls/temp.variadic/injected-class-name.cpp
  Clang :: CXX/temp/temp.decls/temp.variadic/metafunctions.cpp
  Clang :: CXX/temp/temp.fct.spec/temp.arg.explicit/p3-0x.cpp
  Clang :: CXX/temp/temp.fct.spec/temp.arg.explicit/p9-0x.cpp
  Clang :: CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.call/p1-0x.cpp
  Clang :: CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.type/p21.cpp
  Clang :: CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.type/p9-0x.cpp
  Clang :: CXX/temp/temp.param/p11-0x.cpp
  Clang :: SemaCXX/coreturn-exp-namespace.cpp
  Clang :: SemaCXX/coreturn.cpp
  Clang :: SemaCXX/coroutine-unhandled_exception-warning-exp-namespace.cpp
  Clang :: SemaCXX/coroutine-unhandled_exception-warning.cpp
  Clang :: SemaCXX/coroutines-exp-namespace.cpp
  Clang :: SemaCXX/coroutines.cpp
  Clang :: SemaCXX/crash-lambda-12645424.cpp
  Clang :: SemaCXX/discrim-union.cpp
  Clang :: SemaTemplate/attributes.cpp
  Clang :: SemaTemplate/class-template-spec.cpp
  Clang :: SemaTemplate/deduction.cpp
  Clang :: SemaTemplate/pack-deduction.cpp
  Clang :: SemaTemplate/temp_arg_nontype_cxx1z.cpp
  Clang :: SemaTemplate/temp_arg_template_cxx1z.cpp

I've reproduced this locally with the following patch to inject 
`-fclang-abi-compat=14` on the command line executed for those tests:

  diff --git a/clang/test/CXX/temp/lit.local.cfg 
b/clang/test/CXX/temp/lit.local.cfg
  new file mode 100644
  index ..23d23bb6c46e
  --- /dev/null
  +++ b/clang/test/CXX/temp/lit.local.cfg
  @@ -0,0 +1,3 @@
  +config.substitutions.insert(0,
  +  ('%clang_cc1',
  +   '%clang_cc1 -fclang-abi-compat=14.0'))
  diff --git a/clang/test/SemaCXX/lit.local.cfg 
b/clang/test/SemaCXX/lit.local.cfg
  new file mode 100644
  index ..23d23bb6c46e
  --- /dev/null
  +++ b/clang/test/SemaCXX/lit.local.cfg
  @@ -0,0 +1,3 @@
  +config.substitutions.insert(0,
  +  ('%clang_cc1',
  +   '%clang_cc1 -fclang-abi-compat=14.0'))
  diff --git a/clang/test/SemaTemplate/lit.local.cfg 
b/clang/test/SemaTemplate/lit.local.cfg
  new file mode 100644
  index ..23d23bb6c46e
  --- /dev/null
  +++ b/clang/test/SemaTemplate/lit.local.cfg
  @@ -0,0 +1,3 @@
  +config.substitutions.insert(0,
  +  ('%clang_cc1',
  +   '%clang_cc1 -fclang-abi-compat=14.0'))

(Note that by adding the `lit.local.cfg` file abovementioned there will also be 
the failure of `SemaCXX/class-layout.cpp`, but that can be ignored as for some 
command lines the expected behavior is equivalent to pass 
`-fclang-abi-compat=latest`)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[clang] 177cbb1 - [CMake] Explicit bootstrap options override any passthrough ones.

2022-08-17 Thread Carlos Alberto Enciso via cfe-commits

Author: Carlos Alberto Enciso
Date: 2022-08-17T08:16:10+01:00
New Revision: 177cbb1c9b661b15a7db35e4ec9255adf502a6cb

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

LOG: [CMake] Explicit bootstrap options override any passthrough ones.

The https://reviews.llvm.org/D53014 added CMAKE_BUILD_TYPE to
the list of BOOTSTRAP_DEFAULT_PASSTHROUGH variables.

The downside is that both stage-1 and stage-2 configurations
are the same. So it is not possible to build different stage
configurations.

This patch allow explicit bootstrap options to override any
passthrough ones.

For instance, the following settings would build:
  stage-1 (Release) and stage-2(Debug)

-DCMAKE_BUILD_TYPE=Release -DBOOTSTRAP_CMAKE_BUILD_TYPE=Debug

Reviewed By: @beanz

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

Added: 


Modified: 
clang/CMakeLists.txt

Removed: 




diff  --git a/clang/CMakeLists.txt b/clang/CMakeLists.txt
index f6e860159435..60f6c162a2d5 100644
--- a/clang/CMakeLists.txt
+++ b/clang/CMakeLists.txt
@@ -758,6 +758,19 @@ if (CLANG_ENABLE_BOOTSTRAP)
 set(LTO_RANLIB)
   endif()
 
+  # Populate the passthrough variables
+  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} 
${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
+if(DEFINED ${variableName})
+  if("${${variableName}}" STREQUAL "")
+set(value "")
+  else()
+string(REPLACE ";" "|" value "${${variableName}}")
+  endif()
+  list(APPEND PASSTHROUGH_VARIABLES
+-D${variableName}=${value})
+endif()
+  endforeach()
+
   # Find all variables that start with BOOTSTRAP_ and populate a variable with
   # them.
   get_cmake_property(variableNames VARIABLES)
@@ -774,19 +787,6 @@ if (CLANG_ENABLE_BOOTSTRAP)
 endif()
   endforeach()
 
-  # Populate the passthrough variables
-  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} 
${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
-if(DEFINED ${variableName})
-  if("${${variableName}}" STREQUAL "")
-set(value "")
-  else()
-string(REPLACE ";" "|" value "${${variableName}}")
-  endif()
-  list(APPEND PASSTHROUGH_VARIABLES
--D${variableName}=${value})
-endif()
-  endforeach()
-
   ExternalProject_Add(${NEXT_CLANG_STAGE}
 DEPENDS clang-bootstrap-deps
 PREFIX ${NEXT_CLANG_STAGE}



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


[PATCH] D131755: [CMake] Explicit bootstrap options override any passthrough ones.

2022-08-17 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG177cbb1c9b66: [CMake] Explicit bootstrap options override 
any passthrough ones. (authored by CarlosAlbertoEnciso).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131755

Files:
  clang/CMakeLists.txt


Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -758,6 +758,19 @@
 set(LTO_RANLIB)
   endif()
 
+  # Populate the passthrough variables
+  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} 
${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
+if(DEFINED ${variableName})
+  if("${${variableName}}" STREQUAL "")
+set(value "")
+  else()
+string(REPLACE ";" "|" value "${${variableName}}")
+  endif()
+  list(APPEND PASSTHROUGH_VARIABLES
+-D${variableName}=${value})
+endif()
+  endforeach()
+
   # Find all variables that start with BOOTSTRAP_ and populate a variable with
   # them.
   get_cmake_property(variableNames VARIABLES)
@@ -774,19 +787,6 @@
 endif()
   endforeach()
 
-  # Populate the passthrough variables
-  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} 
${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
-if(DEFINED ${variableName})
-  if("${${variableName}}" STREQUAL "")
-set(value "")
-  else()
-string(REPLACE ";" "|" value "${${variableName}}")
-  endif()
-  list(APPEND PASSTHROUGH_VARIABLES
--D${variableName}=${value})
-endif()
-  endforeach()
-
   ExternalProject_Add(${NEXT_CLANG_STAGE}
 DEPENDS clang-bootstrap-deps
 PREFIX ${NEXT_CLANG_STAGE}


Index: clang/CMakeLists.txt
===
--- clang/CMakeLists.txt
+++ clang/CMakeLists.txt
@@ -758,6 +758,19 @@
 set(LTO_RANLIB)
   endif()
 
+  # Populate the passthrough variables
+  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} ${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
+if(DEFINED ${variableName})
+  if("${${variableName}}" STREQUAL "")
+set(value "")
+  else()
+string(REPLACE ";" "|" value "${${variableName}}")
+  endif()
+  list(APPEND PASSTHROUGH_VARIABLES
+-D${variableName}=${value})
+endif()
+  endforeach()
+
   # Find all variables that start with BOOTSTRAP_ and populate a variable with
   # them.
   get_cmake_property(variableNames VARIABLES)
@@ -774,19 +787,6 @@
 endif()
   endforeach()
 
-  # Populate the passthrough variables
-  foreach(variableName ${CLANG_BOOTSTRAP_PASSTHROUGH} ${_BOOTSTRAP_DEFAULT_PASSTHROUGH})
-if(DEFINED ${variableName})
-  if("${${variableName}}" STREQUAL "")
-set(value "")
-  else()
-string(REPLACE ";" "|" value "${${variableName}}")
-  endif()
-  list(APPEND PASSTHROUGH_VARIABLES
--D${variableName}=${value})
-endif()
-  endforeach()
-
   ExternalProject_Add(${NEXT_CLANG_STAGE}
 DEPENDS clang-bootstrap-deps
 PREFIX ${NEXT_CLANG_STAGE}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131385: [clangd] Support for standard type hierarchy

2022-08-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet marked 2 inline comments as done.
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1713
+  fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
+  Item.data.parents->emplace_back(ParentSym->data);
+  Item.parents->emplace_back(std::move(*ParentSym));

usaxena95 wrote:
> nit: std::move.
the copy here is actually intentional. as we need to preserve `data` both in 
current element and also in its `parent`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131385

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


[PATCH] D131385: [clangd] Support for standard type hierarchy

2022-08-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rG83411bf06f34: [clangd] Support for standard type hierarchy 
(authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131385

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h
  clang-tools-extra/clangd/test/initialize-params.test
  clang-tools-extra/clangd/test/type-hierarchy-ext.test
  clang-tools-extra/clangd/test/type-hierarchy.test
  clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Index: clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
===
--- clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
+++ clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
@@ -5,6 +5,7 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
+#include "AST.h"
 #include "Annotations.h"
 #include "Matchers.h"
 #include "ParsedAST.h"
@@ -16,6 +17,7 @@
 #include "llvm/Support/Path.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -26,6 +28,7 @@
 using ::testing::Field;
 using ::testing::IsEmpty;
 using ::testing::Matcher;
+using ::testing::SizeIs;
 using ::testing::UnorderedElementsAre;
 
 // GMock helpers for matching TypeHierarchyItem.
@@ -45,6 +48,10 @@
 // Note: "not resolved" is different from "resolved but empty"!
 MATCHER(parentsNotResolved, "") { return !arg.parents; }
 MATCHER(childrenNotResolved, "") { return !arg.children; }
+MATCHER_P(withResolveID, SID, "") { return arg.symbolID.str() == SID; }
+MATCHER_P(withResolveParents, M, "") {
+  return testing::ExplainMatchResult(M, arg.data.parents, result_listener);
+}
 
 TEST(FindRecordTypeAt, TypeOrVariable) {
   Annotations Source(R"cpp(
@@ -64,8 +71,10 @@
   auto AST = TU.build();
 
   for (Position Pt : Source.points()) {
-const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
-EXPECT_EQ(&findDecl(AST, "Child2"), static_cast(RD));
+auto Records = findRecordTypeAt(AST, Pt);
+ASSERT_THAT(Records, SizeIs(1));
+EXPECT_EQ(&findDecl(AST, "Child2"),
+  static_cast(Records.front()));
   }
 }
 
@@ -86,8 +95,10 @@
   auto AST = TU.build();
 
   for (Position Pt : Source.points()) {
-const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
-EXPECT_EQ(&findDecl(AST, "Child2"), static_cast(RD));
+auto Records = findRecordTypeAt(AST, Pt);
+ASSERT_THAT(Records, SizeIs(1));
+EXPECT_EQ(&findDecl(AST, "Child2"),
+  static_cast(Records.front()));
   }
 }
 
@@ -107,11 +118,10 @@
   auto AST = TU.build();
 
   for (Position Pt : Source.points()) {
-const CXXRecordDecl *RD = findRecordTypeAt(AST, Pt);
 // A field does not unambiguously specify a record type
 // (possible associated reocrd types could be the field's type,
 // or the type of the record that the field is a member of).
-EXPECT_EQ(nullptr, RD);
+EXPECT_THAT(findRecordTypeAt(AST, Pt), SizeIs(0));
   }
 }
 
@@ -359,11 +369,11 @@
   for (Position Pt : Source.points()) {
 // Set ResolveLevels to 0 because it's only used for Children;
 // for Parents, getTypeHierarchy() always returns all levels.
-llvm::Optional Result = getTypeHierarchy(
-AST, Pt, /*ResolveLevels=*/0, TypeHierarchyDirection::Parents);
-ASSERT_TRUE(bool(Result));
+auto Result = getTypeHierarchy(AST, Pt, /*ResolveLevels=*/0,
+   TypeHierarchyDirection::Parents);
+ASSERT_THAT(Result, SizeIs(1));
 EXPECT_THAT(
-*Result,
+Result.front(),
 AllOf(
 withName("Child"), withKind(SymbolKind::Struct),
 parents(AllOf(withName("Parent1"), withKind(SymbolKind::Struct),
@@ -398,11 +408,11 @@
   // The parent is reported as "S" because "S<0>" is an invalid instantiation.
   // We then iterate once more and find "S" again before detecting the
   // recursion.
-  llvm::Optional Result = getTypeHierarchy(
-  AST, Source.points()[0], 0, TypeHierarchyDirection::Parents);
-  ASSERT_TRUE(bool(Result));
+  auto Result = getTypeHierarchy(AST, Source.points()[0], 0,
+ TypeHierarchyDirection::Parents);
+  ASSERT_THAT(Result, SizeIs(1));
   EXPECT_THAT(
-  *Result,
+  Result.front(),
   AllOf(withName("S<0>"), withKind(SymbolKind::Struct),
 parents(
 AllOf(withName("S"), withKind(SymbolKind::Struct),
@@ -432,11 +442,

[clang-tools-extra] 83411bf - [clangd] Support for standard type hierarchy

2022-08-17 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-08-17T09:29:15+02:00
New Revision: 83411bf06f34ae06731008eeabfc53553c1a1f86

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

LOG: [clangd] Support for standard type hierarchy

This is mostly a mechanical change to adapt standard type hierarchy
support proposed in LSP 3.17 on top of clangd's existing extension support.

This does mainly two things:
- Incorporate symbolids for all the parents inside resolution parameters, so
  that they can be retrieved from index later on. This is a new code path, as
  extension always resolved them eagerly.
- Propogate parent information when resolving children, so that at least one
  branch of parents is always preserved. This is to address a shortcoming in the
  extension.

This doesn't drop support for the extension, but it's deprecated from now on and
will be deleted in upcoming releases. Currently we use the same struct
internally but don't serialize extra fields.

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

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

Added: 
clang-tools-extra/clangd/test/type-hierarchy-ext.test

Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/ClangdLSPServer.h
clang-tools-extra/clangd/ClangdServer.cpp
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/Protocol.cpp
clang-tools-extra/clangd/Protocol.h
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/XRefs.h
clang-tools-extra/clangd/test/initialize-params.test
clang-tools-extra/clangd/test/type-hierarchy.test
clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 0cc3792a0fdd2..66bda05d00f71 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -26,6 +26,8 @@
 #include "support/Trace.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/FunctionExtras.h"
+#include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringRef.h"
@@ -571,8 +573,12 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
&Params,
   {"referencesProvider", true},
   {"astProvider", true}, // clangd extension
   {"typeHierarchyProvider", true},
-  {"memoryUsageProvider", true}, // clangd extension
-  {"compilationDatabase",// clangd extension
+  // Unfortunately our extension made use of the same capability name as 
the
+  // standard. Advertise this capability to tell clients that implement our
+  // extension we really have support for the standardized one as well.
+  {"standardTypeHierarchyProvider", true}, // clangd extension
+  {"memoryUsageProvider", true},   // clangd extension
+  {"compilationDatabase",  // clangd extension
llvm::json::Object{{"automaticReload", true}}},
   {"callHierarchyProvider", true},
   {"clangdInlayHintsProvider", true},
@@ -1183,18 +1189,94 @@ void ClangdLSPServer::onHover(const 
TextDocumentPositionParams &Params,
 });
 }
 
-void ClangdLSPServer::onTypeHierarchy(
-const TypeHierarchyParams &Params,
-Callback> Reply) {
+// Our extension has a 
diff erent representation on the wire than the standard.
+// https://clangd.llvm.org/extensions#type-hierarchy
+llvm::json::Value serializeTHIForExtension(TypeHierarchyItem THI) {
+  llvm::json::Object Result{{
+  {"name", std::move(THI.name)},
+  {"kind", static_cast(THI.kind)},
+  {"uri", std::move(THI.uri)},
+  {"range", THI.range},
+  {"selectionRange", THI.selectionRange},
+  {"data", std::move(THI.data)},
+  }};
+  if (THI.deprecated)
+Result["deprecated"] = THI.deprecated;
+  if (THI.detail)
+Result["detail"] = std::move(*THI.detail);
+
+  if (THI.parents) {
+llvm::json::Array Parents;
+for (auto &Parent : *THI.parents)
+  Parents.emplace_back(serializeTHIForExtension(std::move(Parent)));
+Result["parents"] = std::move(Parents);
+  }
+
+  if (THI.children) {
+llvm::json::Array Children;
+for (auto &child : *THI.children)
+  Children.emplace_back(serializeTHIForExtension(std::move(child)));
+Result["children"] = std::move(Children);
+  }
+  return Result;
+}
+
+void ClangdLSPServer::onTypeHierarchy(const TypeHierarchyPrepareParams &Params,
+  Callback Reply) {
+  auto Serialize =
+  [Reply = std::move(Reply)](
+  llvm::Expected> Resp) mutable {
+if (!Resp) {
+  Reply(Resp.takeError());
+  return;
+}
+if (Resp->empt

[clang] 4dd71b3 - [clang] Give priority to Class context while parsing declarations

2022-08-17 Thread Kadir Cetinkaya via cfe-commits

Author: Furkan Usta
Date: 2022-08-17T10:06:39+02:00
New Revision: 4dd71b3cb9473e960d06f5c4c60f0817bd5b9cf6

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

LOG: [clang] Give priority to Class context while parsing declarations

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

Reviewed By: kadircet

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

Added: 


Modified: 
clang/lib/Parse/ParseDecl.cpp
clang/test/CodeCompletion/overrides.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 39ba93ee33859..769809c9c9c4f 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -3266,13 +3266,14 @@ void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
 return;
   }
 
-  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
-CCC = Sema::PCC_LocalDeclarationSpecifiers;
-  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
+  // Class context can appear inside a function/block, so prioritise that.
+  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
 CCC = DSContext == DeclSpecContext::DSC_class ? 
Sema::PCC_MemberTemplate
   : Sema::PCC_Template;
   else if (DSContext == DeclSpecContext::DSC_class)
 CCC = Sema::PCC_Class;
+  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
+CCC = Sema::PCC_LocalDeclarationSpecifiers;
   else if (CurParsedObjCImpl)
 CCC = Sema::PCC_ObjCImplementation;
 

diff  --git a/clang/test/CodeCompletion/overrides.cpp 
b/clang/test/CodeCompletion/overrides.cpp
index 6645569d82a77..543c67fac7db4 100644
--- a/clang/test/CodeCompletion/overrides.cpp
+++ b/clang/test/CodeCompletion/overrides.cpp
@@ -11,7 +11,7 @@ void vfunc(bool param, int p) override;
 class C : public B {
  public:
   void vfunc(bool param) override;
-  vf
+  vf;
 };
 
 // Runs completion at ^vf
@@ -31,3 +31,13 @@ class C : public B {
 // CHECK-CC3-NOT: COMPLETION: Pattern : int ttt(bool param, int x = 3) const 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param, int p) 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param) override{{$}}
+
+void func() {
+  class D : public A {
+
+  };
+}
+
+// Runs completion at empty line on line 37.
+// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:37:1 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}



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


[PATCH] D130363: [clang] Give priority to Class context while parsing declarations

2022-08-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4dd71b3cb947: [clang] Give priority to Class context while 
parsing declarations (authored by furkanusta, committed by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D130363?vs=451604&id=453224#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130363

Files:
  clang/lib/Parse/ParseDecl.cpp
  clang/test/CodeCompletion/overrides.cpp


Index: clang/test/CodeCompletion/overrides.cpp
===
--- clang/test/CodeCompletion/overrides.cpp
+++ clang/test/CodeCompletion/overrides.cpp
@@ -11,7 +11,7 @@
 class C : public B {
  public:
   void vfunc(bool param) override;
-  vf
+  vf;
 };
 
 // Runs completion at ^vf
@@ -31,3 +31,13 @@
 // CHECK-CC3-NOT: COMPLETION: Pattern : int ttt(bool param, int x = 3) const 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param, int p) 
override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param) override{{$}}
+
+void func() {
+  class D : public A {
+
+  };
+}
+
+// Runs completion at empty line on line 37.
+// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:37:1 %s -o - | 
FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -3266,13 +3266,14 @@
 return;
   }
 
-  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
-CCC = Sema::PCC_LocalDeclarationSpecifiers;
-  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
+  // Class context can appear inside a function/block, so prioritise that.
+  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
 CCC = DSContext == DeclSpecContext::DSC_class ? 
Sema::PCC_MemberTemplate
   : Sema::PCC_Template;
   else if (DSContext == DeclSpecContext::DSC_class)
 CCC = Sema::PCC_Class;
+  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
+CCC = Sema::PCC_LocalDeclarationSpecifiers;
   else if (CurParsedObjCImpl)
 CCC = Sema::PCC_ObjCImplementation;
 


Index: clang/test/CodeCompletion/overrides.cpp
===
--- clang/test/CodeCompletion/overrides.cpp
+++ clang/test/CodeCompletion/overrides.cpp
@@ -11,7 +11,7 @@
 class C : public B {
  public:
   void vfunc(bool param) override;
-  vf
+  vf;
 };
 
 // Runs completion at ^vf
@@ -31,3 +31,13 @@
 // CHECK-CC3-NOT: COMPLETION: Pattern : int ttt(bool param, int x = 3) const override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
 // CHECK-CC3-NOT: COMPLETION: Pattern : void vfunc(bool param) override{{$}}
+
+void func() {
+  class D : public A {
+
+  };
+}
+
+// Runs completion at empty line on line 37.
+// RUN: not %clang_cc1 -fsyntax-only -code-completion-at=%s:37:1 %s -o - | FileCheck -check-prefix=CHECK-CC4 %s
+// CHECK-CC4: COMPLETION: Pattern : void vfunc(bool param, int p) override{{$}}
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -3266,13 +3266,14 @@
 return;
   }
 
-  if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
-CCC = Sema::PCC_LocalDeclarationSpecifiers;
-  else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
+  // Class context can appear inside a function/block, so prioritise that.
+  if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
 CCC = DSContext == DeclSpecContext::DSC_class ? Sema::PCC_MemberTemplate
   : Sema::PCC_Template;
   else if (DSContext == DeclSpecContext::DSC_class)
 CCC = Sema::PCC_Class;
+  else if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
+CCC = Sema::PCC_LocalDeclarationSpecifiers;
   else if (CurParsedObjCImpl)
 CCC = Sema::PCC_ObjCImplementation;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

2022-08-17 Thread Fred Tingaud via Phabricator via cfe-commits
frederic-tingaud-sonarsource added a comment.

Hi @NoQ . Would you have time to look if the changes I did to this PR solve 
your concerns?


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

https://reviews.llvm.org/D126534

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


[clang] 8837ef4 - [clang] Apply FixIts to members declared via `using` in derived classes

2022-08-17 Thread Kadir Cetinkaya via cfe-commits

Author: Denis Fatkulin
Date: 2022-08-17T10:09:48+02:00
New Revision: 8837ef4d373be3f9b4ea297596ee917a1a91377e

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

LOG: [clang] Apply FixIts to members declared via `using` in derived classes

FixIt don't switch to arrow in derrived members with `using`

Example code:
```
struct Bar {
  void foo();
};
struct Baz {
  using Bar::foo;
};
void test(Baz* ptr) {
  ptr.^
}

Reviewed By: kadircet

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

Added: 


Modified: 
clang/lib/Sema/SemaCodeComplete.cpp
clang/test/CodeCompletion/member-access.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index f4303f6ec6bf..6d5769a39627 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -1098,7 +1098,8 @@ void ResultBuilder::MaybeAddResult(Result R, DeclContext 
*CurContext) {
 getBasePriority(Using->getTargetDecl()),
 R.Qualifier, false,
 (R.Availability == CXAvailability_Available ||
- R.Availability == CXAvailability_Deprecated));
+ R.Availability == CXAvailability_Deprecated),
+std::move(R.FixIts));
 Result.ShadowDecl = Using;
 MaybeAddResult(Result, CurContext);
 return;
@@ -1273,7 +1274,8 @@ void ResultBuilder::AddResult(Result R, DeclContext 
*CurContext,
 getBasePriority(Using->getTargetDecl()),
 R.Qualifier, false,
 (R.Availability == CXAvailability_Available ||
- R.Availability == CXAvailability_Deprecated));
+ R.Availability == CXAvailability_Deprecated),
+std::move(R.FixIts));
 Result.ShadowDecl = Using;
 AddResult(Result, CurContext, Hiding);
 return;

diff  --git a/clang/test/CodeCompletion/member-access.cpp 
b/clang/test/CodeCompletion/member-access.cpp
index 2c611b471580..4a5d1c66a25a 100644
--- a/clang/test/CodeCompletion/member-access.cpp
+++ b/clang/test/CodeCompletion/member-access.cpp
@@ -311,3 +311,25 @@ void testMembersFromBasesInDependentContext() {
   // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:310:19 %s -o - | 
FileCheck -check-prefix=CHECK-MEMBERS-FROM-BASE-DEPENDENT %s
   // CHECK-MEMBERS-FROM-BASE-DEPENDENT: [#Base4#]base4
 }
+
+namespace members_using_fixits {
+  struct Bar {
+void method();
+int field;
+  };
+  struct Baz: Bar {
+using Bar::method;
+using Bar::field;
+  };
+  void testMethod(Baz* ptr) {
+ptr.m
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:325:10 %s -o - | FileCheck 
-check-prefix=CHECK-METHOD-DECLARED-VIA-USING %s
+  // CHECK-METHOD-DECLARED-VIA-USING: [#void#]method() (requires fix-it: 
{325:8-325:9} to "->")
+
+  void testField(Baz* ptr) {
+ptr.f
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:331:10 %s -o - | FileCheck 
-check-prefix=CHECK-FIELD-DECLARED-VIA-USING %s
+  // CHECK-FIELD-DECLARED-VIA-USING: [#int#]field (requires fix-it: 
{331:8-331:9} to "->")
+}



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


[PATCH] D131088: [clang] Apply FixIts to members declared via `using` in derived classes

2022-08-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8837ef4d373b: [clang] Apply FixIts to members declared via 
`using` in derived classes (authored by denis-fatkulin, committed by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D131088?vs=452408&id=453227#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131088

Files:
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/member-access.cpp


Index: clang/test/CodeCompletion/member-access.cpp
===
--- clang/test/CodeCompletion/member-access.cpp
+++ clang/test/CodeCompletion/member-access.cpp
@@ -311,3 +311,25 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:310:19 %s -o - | 
FileCheck -check-prefix=CHECK-MEMBERS-FROM-BASE-DEPENDENT %s
   // CHECK-MEMBERS-FROM-BASE-DEPENDENT: [#Base4#]base4
 }
+
+namespace members_using_fixits {
+  struct Bar {
+void method();
+int field;
+  };
+  struct Baz: Bar {
+using Bar::method;
+using Bar::field;
+  };
+  void testMethod(Baz* ptr) {
+ptr.m
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:325:10 %s -o - | FileCheck 
-check-prefix=CHECK-METHOD-DECLARED-VIA-USING %s
+  // CHECK-METHOD-DECLARED-VIA-USING: [#void#]method() (requires fix-it: 
{325:8-325:9} to "->")
+
+  void testField(Baz* ptr) {
+ptr.f
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits 
-code-completion-at=%s:331:10 %s -o - | FileCheck 
-check-prefix=CHECK-FIELD-DECLARED-VIA-USING %s
+  // CHECK-FIELD-DECLARED-VIA-USING: [#int#]field (requires fix-it: 
{331:8-331:9} to "->")
+}
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -1098,7 +1098,8 @@
 getBasePriority(Using->getTargetDecl()),
 R.Qualifier, false,
 (R.Availability == CXAvailability_Available ||
- R.Availability == CXAvailability_Deprecated));
+ R.Availability == CXAvailability_Deprecated),
+std::move(R.FixIts));
 Result.ShadowDecl = Using;
 MaybeAddResult(Result, CurContext);
 return;
@@ -1273,7 +1274,8 @@
 getBasePriority(Using->getTargetDecl()),
 R.Qualifier, false,
 (R.Availability == CXAvailability_Available ||
- R.Availability == CXAvailability_Deprecated));
+ R.Availability == CXAvailability_Deprecated),
+std::move(R.FixIts));
 Result.ShadowDecl = Using;
 AddResult(Result, CurContext, Hiding);
 return;


Index: clang/test/CodeCompletion/member-access.cpp
===
--- clang/test/CodeCompletion/member-access.cpp
+++ clang/test/CodeCompletion/member-access.cpp
@@ -311,3 +311,25 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:310:19 %s -o - | FileCheck -check-prefix=CHECK-MEMBERS-FROM-BASE-DEPENDENT %s
   // CHECK-MEMBERS-FROM-BASE-DEPENDENT: [#Base4#]base4
 }
+
+namespace members_using_fixits {
+  struct Bar {
+void method();
+int field;
+  };
+  struct Baz: Bar {
+using Bar::method;
+using Bar::field;
+  };
+  void testMethod(Baz* ptr) {
+ptr.m
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:325:10 %s -o - | FileCheck -check-prefix=CHECK-METHOD-DECLARED-VIA-USING %s
+  // CHECK-METHOD-DECLARED-VIA-USING: [#void#]method() (requires fix-it: {325:8-325:9} to "->")
+
+  void testField(Baz* ptr) {
+ptr.f
+  }
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-with-fixits -code-completion-at=%s:331:10 %s -o - | FileCheck -check-prefix=CHECK-FIELD-DECLARED-VIA-USING %s
+  // CHECK-FIELD-DECLARED-VIA-USING: [#int#]field (requires fix-it: {331:8-331:9} to "->")
+}
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -1098,7 +1098,8 @@
 getBasePriority(Using->getTargetDecl()),
 R.Qualifier, false,
 (R.Availability == CXAvailability_Available ||
- R.Availability == CXAvailability_Deprecated));
+ R.Availability == CXAvailability_Deprecated),
+std::move(R.FixIts));
 Result.ShadowDecl = Using;
 MaybeAddResult(Result, CurContext);
 return;
@@ -1273,7 +1274,8 @@
  

[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-17 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

Stopping by - I assume this targets Clang 16 now, so the abi compat level 
should be adjusted to 15.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[clang] b296aed - [clang] fix a typo in da6187f566b7881cb835

2022-08-17 Thread Yuanfang Chen via cfe-commits

Author: Yuanfang Chen
Date: 2022-08-17T01:27:12-07:00
New Revision: b296aed8ae239c20ebdd7969e978f8d2a3b9c178

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

LOG: [clang] fix a typo in da6187f566b7881cb835

Added: 


Modified: 
clang/lib/Sema/SemaTemplateDeduction.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index ac0b3fe8e04a..99119bcb2e4e 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -2488,7 +2488,8 @@ static bool isSameTemplateArg(ASTContext &Context,
  XPEnd = X.pack_end(),
  YP = Y.pack_begin();
  XP != XPEnd; ++XP, ++YP)
-  if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
+  if (!isSameTemplateArg(Context, *XP, *YP, PartialOrdering,
+ PackExpansionMatchesPack))
 return false;
   } else {
 unsigned PackIterationSize = X.pack_size();



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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-17 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128745#3728087 , 
@michele.scandale wrote:

> I can see failures related to this change in a downstream version of clang 
> where the default `ClangABICompat` value is not `Latest` (after the followup 
> https://reviews.llvm.org/rGda6187f566b7881cb8350621aea9bd582de569b9).

Fixed in b296aed8ae239c20e 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-08-17 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added a comment.

In D128745#3728196 , @royjacobson 
wrote:

> Stopping by - I assume this targets Clang 16 now, so the abi compat level 
> should be adjusted to 15.

Sure, I'll make a new patch for that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D131879: [clang][analyzer] Errno modeling code refactor (NFC).

2022-08-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 453231.
balazske marked 4 inline comments as done.
balazske added a comment.

Small improvements.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131879

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp

Index: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -57,19 +57,6 @@
 using namespace clang;
 using namespace clang::ento;
 
-/// Produce a textual description of the state of \c errno (this describes the
-/// way how it is allowed to be used).
-/// The returned string is insertable into a longer warning message (in the form
-/// "the value 'errno' <...>").
-/// Currently only the \c errno_modeling::MustNotBeChecked state is supported.
-/// But later other kind of errno state may be needed if functions with special
-/// handling of \c errno are added.
-static const char *describeErrnoCheckState(errno_modeling::ErrnoCheckState CS) {
-  assert(CS == errno_modeling::MustNotBeChecked &&
- "Errno description not applicable.");
-  return "may be undefined after the call and should not be used";
-}
-
 namespace {
 class StdLibraryFunctionsChecker
 : public Checker {
@@ -392,45 +379,42 @@
   using ConstraintSet = std::vector;
 
   /// Define how a function affects the system variable 'errno'.
-  /// This works together with the ErrnoModeling and ErrnoChecker classes.
+  /// This works together with the \c ErrnoModeling and \c ErrnoChecker classes.
+  /// Currently 3 use cases exist: success, failure, irrelevant.
+  /// In the future the failure case can be customized to set \c errno to a
+  /// more specific constraint (for example > 0), or new case can be added
+  /// for functions which require check of \c errno in both success and failure
+  /// case.
   class ErrnoConstraintBase {
   public:
 /// Apply specific state changes related to the errno variable.
 virtual ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
   const Summary &Summary,
   CheckerContext &C) const = 0;
-/// Get a description about what is applied to 'errno' and how is it allowed
-/// to be used. If ErrnoChecker generates a bug then this message is
-/// displayed as a note at the function call.
-/// It may return empty string if no note tag is to be added.
-virtual std::string describe(StringRef FunctionName) const { return ""; }
+/// Get a NoteTag about the changes made to 'errno' and the possible bug.
+/// It may return \c nullptr (if no bug report from \c ErrnoChecker is
+/// expected).
+virtual const NoteTag *describe(CheckerContext &C,
+StringRef FunctionName) const {
+  return nullptr;
+}
 
 virtual ~ErrnoConstraintBase() {}
 
   protected:
-/// Many of the descendant classes use this value.
-const errno_modeling::ErrnoCheckState CheckState;
-
-ErrnoConstraintBase(errno_modeling::ErrnoCheckState CS) : CheckState(CS) {}
+ErrnoConstraintBase() = default;
 
 /// This is used for conjure symbol for errno to differentiate from the
 /// original call expression (same expression is used for the errno symbol).
 static int Tag;
   };
 
-  /// Set value of 'errno' to be related to 0 in a specified way, with a
-  /// specified "errno check state". For example with \c BO_GT 'errno' is
-  /// constrained to be greater than 0. Use this for failure cases of functions.
-  class ZeroRelatedErrnoConstraint : public ErrnoConstraintBase {
-BinaryOperatorKind Op;
-
+  /// Set errno constraint at failure cases of standard functions.
+  /// Failure case: 'errno' becomes not equal to 0 and may or may not be checked
+  /// by the program. \c ErrnoChecker does not emit a bug report after such a
+  /// function call.
+  class FailureErrnoConstraint : public ErrnoConstraintBase {
   public:
-ZeroRelatedErrnoConstraint(clang::BinaryOperatorKind OpK,
-   errno_modeling::ErrnoCheckState CS)
-: ErrnoConstraintBase(CS), Op(OpK) {
-  assert(BinaryOperator::isComparisonOp(OpK));
-}
-
 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
   const Summary &Summary,
   CheckerContext &C) const override {
@@ -440,62 +424,36 @@
C.getLocationContext(), C.getASTContext().IntTy,
C.blockCount())
   .castAs();
-  NonLoc ZeroVal =
-  SVB.makeZeroVal(C.getASTContext().IntTy).castAs();
-  De

[PATCH] D131555: [Clang] Propagate const context info when emitting compound literal

2022-08-17 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added inline comments.



Comment at: clang/test/CodeGen/const-init.c:2
+// setting strict FP behaviour in the run line below tests that the compiler
+// does the right thing for global compound literals (compoundliteral test)
+// RUN: %clang_cc1 -no-opaque-pointers -triple i386-pc-linux-gnu 
-ffreestanding -Wno-pointer-to-int-cast -Wno-int-conversion 
-ffp-exception-behavior=strict -emit-llvm -o - %s | FileCheck %s

Drive by comment, what is "the right thing" here? Without me having to git 
blame this file if I'm looking at this months from now.

You could add a comment down next to the test like "clang should evaluate this 
in a constant context, so floating point mode should have no effect". Which is 
still a bit vague but better than "clang should not crash if we do this".

Also are there any other floating point modes that have/had this same problem? 
They should be tested too if so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131555

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


[PATCH] D132017: [clang][analyzer] Add errno modeling to StreamChecker

2022-08-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, gamesh411, 
dkrupp, donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, 
baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a reviewer: NoQ.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Update the existing modeling of stream functions in StreamChecker
with 'errno' modeling. The not (yet) evaluated stream functions
are not updated.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132017

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-errno.c

Index: clang/test/Analysis/stream-errno.c
===
--- /dev/null
+++ clang/test/Analysis/stream-errno.c
@@ -0,0 +1,196 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,debug.ExprInspection -analyzer-output text -verify %s
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_func.h"
+
+extern void clang_analyzer_eval(int);
+extern void clang_analyzer_dump(int);
+
+void check_fopen(void) {
+  FILE *F = fopen("xxx", "r");
+  // expected-note@-1{{Assuming that function 'fopen' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_tmpfile(void) {
+  FILE *F = tmpfile();
+  // expected-note@-1{{Assuming that function 'tmpfile' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_freopen(void) {
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  F = freopen("xxx", "w", F);
+  // expected-note@-1{{Assuming that function 'freopen' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_fclose(void) {
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  int Ret = fclose(F);
+  // expected-note@-1{{Assuming that function 'fclose' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+2{{Taking true branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (Ret == EOF) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_fread(void) {
+  char Buf[10];
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  fread(Buf, 0, 1, F);
+  // expected-note@+2{{Taking false branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (errno) {} // no-warning
+  fread(Buf, 1, 0, F);
+  // expected-note@+2{{Taking false branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (errno) {} // no-warning
+
+

[PATCH] D131677: [clang][RISCV] Fix incorrect ABI lowering for inherited structs under hard-float ABIs

2022-08-17 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng accepted this revision.
kito-cheng added a comment.
This revision is now accepted and ready to land.

LGTM, result has compared with GCC for `rv32gc/ilp32d` and `rv64gc/lp64d`.


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

https://reviews.llvm.org/D131677

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


[PATCH] D132017: [clang][analyzer] Add errno modeling to StreamChecker

2022-08-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:283-284
 
+  mutable bool EofInitialized = false;
+  mutable int EofVal = -1;
+

Have you considered using `llvm::Optional` for this?



Comment at: clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp:537
+  errno_modeling::getNoteTagForStdSuccess(
+  C, cast(Call.getDecl())->getNameAsString()));
   C.addTransition(StateNull);

I believe, `getDecl()` might return null, e.g. for calling a function pointer.



Comment at: clang/test/Analysis/stream-errno.c:12-13
+  // expected-note@-1{{Assuming that function 'fopen' is successful, in this 
case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}

So these two lines correspond to the following `clang_analyzer_eval()`.
It took me a while to make sense of the two independent note streams at once.
Please consider splitting this and similar cases to have a single stream of 
notes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132017

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


[PATCH] D131678: hicpp-signed-bitwise - Return location of the operand (and not of the operator beginning)

2022-08-17 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.

Would you like me to commit it on your behalf again?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131678

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


[PATCH] D131780: [clang-tidy] Do not trigger cppcoreguidelines-avoid-const-or-ref-data-members on lambda captures

2022-08-17 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp:191
+  auto r5 = [&x5]{};
+}

Can you add some cases with implicit capture (using [=] and [&])


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

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


[PATCH] D131678: hicpp-signed-bitwise - Return location of the operand (and not of the operator beginning)

2022-08-17 Thread Vladimir Plyashkun via Phabricator via cfe-commits
vladimir.plyashkun marked an inline comment as done.
vladimir.plyashkun added a comment.

In D131678#3728412 , @njames93 wrote:

> Would you like me to commit it on your behalf again?

Yes, the email is the same - vladimir.plyash...@jetbrains.com


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131678

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


[PATCH] D128861: [clang-tidy] add cppcoreguidelines-symmetric-binary-operator

2022-08-17 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:24-34
+using transformer::applyFirst;
+using transformer::cat;
+using transformer::changeTo;
+using transformer::insertBefore;
+using transformer::makeRule;
+using transformer::name;
+using transformer::node;

Just bring the whole namespace into scope.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:56
+bool isComparisonOperator(OverloadedOperatorKind Kind) {
+  return llvm::is_contained(
+  std::initializer_list{

Could these not be represented as a bitset?



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:84
+
+static Expected getNode(const BoundNodes &Nodes, StringRef ID) {
+  auto &NodesMap = Nodes.getMap();

Should there ever be a case where this returns an error. If not can this assert 
instead and just return a DynTypedNode?



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:117-122
+  for (; OptToken.hasValue() && !IsConstToken(OptToken.getValue()) &&
+ !OptToken.getValue().isOneOf(tok::TokenKind::l_brace,
+  tok::TokenKind::kw_default,
+  tok::TokenKind::semi);
+   OptToken = GetNextToken(OptToken.getValue().getLocation())) {
+  }

Looks like this is begging to be a while loop.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:129-133
+  // This error is unreachable within this check. constSpec is only called
+  // on defaulted symmetric binary operators, which are required to be 
const
+  // specified.
+  return invalidArgumentError(
+  "constSpec invalid argument: member function is not const 
qualified");

If its unreachable, use unreachable to indicate that.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:134
+  "constSpec invalid argument: member function is not const 
qualified");
+};
+return invalidArgumentError(

This semi-colon looks suspicious



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/SymmetricBinaryOperatorCheck.cpp:135-136
+};
+return invalidArgumentError(
+"constSpec invalid argument: not a CXXMethodDecl");
+  };

Is this error reachable? Again if not use unreachable.
If it is reachable, is it possible to show a test case where this error is 
expected and detected in the test?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128861

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


[PATCH] D128981: [C++20][Modules] Implement include translation.

2022-08-17 Thread Iain Sandoe via Phabricator via cfe-commits
iains added a comment.

In D128981#3728070 , @jansvoboda11 
wrote:

> Hi @iains, upstream Clang crashes on the attached test case due to an 
> assertion failure. Git bisect pointed me to this commit. Can you please take 
> a look? Previously, the test would result in a warning of incomplete umbrella 
> header.

yes, I can repeat this - will take a look.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128981

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


[PATCH] D130747: [pseudo] wip/prototype: eliminate identifier ambiguities in the grammar.

2022-08-17 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 453259.
hokein marked 2 inline comments as done.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130747

Files:
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/glr.cpp


Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -12,10 +12,7 @@
 // CHECK-NEXT: │ └─; := tok[8]
 // CHECK-NEXT: └─statement~simple-declaration := decl-specifier-seq 
init-declarator-list ;
 // CHECK-NEXT:   ├─decl-specifier-seq~simple-type-specifier := 
-// CHECK-NEXT:   │ ├─simple-type-specifier~type-name := 
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ └─type-name~IDENTIFIER := tok[5]
+// CHECK-NEXT:   │ ├─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   │ └─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   ├─init-declarator-list~ptr-declarator := ptr-operator 
ptr-declarator
 // CHECK-NEXT:   │ ├─ptr-operator~* := tok[6]
@@ -23,12 +20,11 @@
 // CHECK-NEXT:   └─; := tok[8]
 }
 
-// CHECK:  3 Ambiguous nodes:
+// CHECK:  2 Ambiguous nodes:
 // CHECK-NEXT: 1 simple-type-specifier
 // CHECK-NEXT: 1 statement
-// CHECK-NEXT: 1 type-name
 // CHECK-EMPTY:
 // CHECK-NEXT: 0 Opaque nodes:
 // CHECK-EMPTY:
-// CHECK-NEXT: Ambiguity: 0.40 misparses/token
+// CHECK-NEXT: Ambiguity: 0.20 misparses/token
 // CHECK-NEXT: Unparsed: 0.00%
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -34,14 +34,9 @@
 _ := declaration-seq
 
 # gram.key
-typedef-name := IDENTIFIER
-typedef-name := simple-template-id
+#! we don't distinguish between namespaces and namespace aliases, as it's hard
+#! and uninteresting.
 namespace-name := IDENTIFIER
-namespace-name := namespace-alias
-namespace-alias := IDENTIFIER
-class-name := IDENTIFIER
-class-name := simple-template-id
-enum-name := IDENTIFIER
 template-name := IDENTIFIER
 
 # gram.basic
@@ -391,9 +386,12 @@
 builtin-type := FLOAT
 builtin-type := DOUBLE
 builtin-type := VOID
-type-name := class-name
-type-name := enum-name
-type-name := typedef-name
+#! Unlike C++ standard grammar, we don't distinguish the underlying type 
(class,
+#! enum, typedef) of the IDENTIFIER, as these ambiguities are "local" and don't
+#! affect the final parse tree. Eliminating them gives a significant 
performance
+#! boost to the parser.
+type-name := IDENTIFIER
+type-name := simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier_opt IDENTIFIER
 elaborated-type-specifier := class-key simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier TEMPLATE_opt 
simple-template-id
@@ -551,7 +549,7 @@
 class-specifier := class-head { member-specification_opt [recover=Brackets] }
 class-head := class-key class-head-name class-virt-specifier_opt 
base-clause_opt
 class-head := class-key base-clause_opt
-class-head-name := nested-name-specifier_opt class-name
+class-head-name := nested-name-specifier_opt type-name
 class-virt-specifier := contextual-final
 class-key := CLASS
 class-key := STRUCT


Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -12,10 +12,7 @@
 // CHECK-NEXT: │ └─; := tok[8]
 // CHECK-NEXT: └─statement~simple-declaration := decl-specifier-seq init-declarator-list ;
 // CHECK-NEXT:   ├─decl-specifier-seq~simple-type-specifier := 
-// CHECK-NEXT:   │ ├─simple-type-specifier~type-name := 
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ └─type-name~IDENTIFIER := tok[5]
+// CHECK-NEXT:   │ ├─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   │ └─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator
 // CHECK-NEXT:   │ ├─ptr-operator~* := tok[6]
@@ -23,12 +20,11 @@
 // CHECK-NEXT:   └─; := tok[8]
 }
 
-// CHECK:  3 Ambiguous nodes:
+// CHECK:  2 Ambiguous nodes:
 // CHECK-NEXT: 1 simple-type-specifier
 // CHECK-NEXT: 1 statement
-// CHECK-NEXT: 1 type-name
 // CHECK-EMPTY:
 // CHECK-NEXT: 0 Opaque nodes:
 // CHECK-EMPTY:
-// CHECK-NEXT: Ambiguity: 0.40 misparses/token
+// CHECK-NEXT: Ambiguity: 0.20 misparses/token
 // CHECK-NEXT: Unparsed: 0.00%
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo

[PATCH] D130747: [pseudo] wip/prototype: eliminate identifier ambiguities in the grammar.

2022-08-17 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D130747#3727386 , @sammccall wrote:

> LG, though i think we should eliminate class-name altogether.
>
> This gives most of the perf, which is nice!
>
> The reduction in ambiguous nodes is less impressive than before :-( As 
> discussed offline, i think the remaining ambiguous nodes serve a purpose as 
> they will assist in correlated disambiguation & keep the representation of 
> important concepts uniform. I may be wrong about that, in which case we can 
> still drop them later.

Yeah, this is because we still keep two critical ambiguous nodes:

- simple-type-specifier (type-name vs template-name), e.g. for the CTAD case;
- nested-name-specifier (type-name vs namespace-name), e.g. for `a::b::c` case;

These two ambiguous nodes are the top1 and top2 now.

> The forest size reduction is nice to have, but least critical imo.






Comment at: clang-tools-extra/pseudo/lib/cxx/cxx.bnf:39
 namespace-name := IDENTIFIER
-namespace-name := namespace-alias
-namespace-alias := IDENTIFIER
 class-name := IDENTIFIER
 class-name := simple-template-id

sammccall wrote:
> hokein wrote:
> > this can be removed as well, but the `class-head-name` rule uses it. 
> Can't we use `class-head-name := nested-name-specifier_opt type-name` as 
> `class-name` and `type-name` now match?
> 
> (Oops, not sure how i lost this comment)
ah, this is clever, I missed that the fact that class-name and type-name are 
identical now. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130747

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


[clang] 956f8c0 - [Driver] Override default location of config files

2022-08-17 Thread Serge Pavlov via cfe-commits

Author: Serge Pavlov
Date: 2022-08-17T18:52:53+07:00
New Revision: 956f8c0e1028edd65f68c4b386224d4ccb58c5b6

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

LOG: [Driver] Override default location of config files

If directory for config files was specified in project configuration
using parameters CLANG_CONFIG_FILE_SYSTEM_DIR or CLANG_CONFIG_FILE_USER_DIR,
it was not overriden by command-line option `--config-system-dir=` or
`--config-user-dir=` that specified empty path.

This change corrects the behavior. It fixes the issue
https://github.com/llvm/llvm-project/issues/56836 ([clang] [test]
test/Driver/config-file-errs.c fails if CLANG_CONFIG_FILE_SYSTEM_DIR is
specified).

Added: 


Modified: 
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 5b43a86d20581..59ddc89269d95 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -970,23 +970,19 @@ bool Driver::loadConfigFile() {
   SmallString<128> CfgDir;
   CfgDir.append(
   CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
-  if (!CfgDir.empty()) {
-if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
-  SystemConfigDir.clear();
-else
-  SystemConfigDir = static_cast(CfgDir);
-  }
+  if (CfgDir.empty() || llvm::sys::fs::make_absolute(CfgDir))
+SystemConfigDir.clear();
+  else
+SystemConfigDir = static_cast(CfgDir);
 }
 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
   SmallString<128> CfgDir;
   CfgDir.append(
   CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
-  if (!CfgDir.empty()) {
-if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
-  UserConfigDir.clear();
-else
-  UserConfigDir = static_cast(CfgDir);
-  }
+  if (CfgDir.empty() || llvm::sys::fs::make_absolute(CfgDir))
+UserConfigDir.clear();
+  else
+UserConfigDir = static_cast(CfgDir);
 }
   }
 



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


[clang] d7e06d5 - Update the status of some more C99 features

2022-08-17 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-08-17T08:11:56-04:00
New Revision: d7e06d5675b62b5d3d89e6d6210c34b74a1a8356

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

LOG: Update the status of some more C99 features

This also adds some test coverage to demonstrate we implement what was
standardized.

Added: 
clang/test/C/C99/n617.c
clang/test/C/C99/n629.c
clang/test/C/C99/n636.c
clang/test/C/C99/n736.c

Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/test/C/C99/n617.c b/clang/test/C/C99/n617.c
new file mode 100644
index 0..be263cc05f3e8
--- /dev/null
+++ b/clang/test/C/C99/n617.c
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -verify %s
+
+// expected-no-diagnostics
+
+/* WG14 N617: yes
+ * reliable integer division
+ */
+void test(void) {
+  _Static_assert(59 / 4 == 14, "we didn't truncate properly");
+  _Static_assert(59 / -4 == -14, "we didn't truncate properly");
+  _Static_assert(-59 / 4 == -14, "we didn't truncate properly");
+  _Static_assert(-59 / -4 == 14, "we didn't truncate properly");
+
+  // Might as well test % for the quotient.
+  _Static_assert(59 % 4 == 3, "we didn't truncate properly");
+  _Static_assert(59 % -4 == 3, "we didn't truncate properly");
+  _Static_assert(-59 % 4 == -3, "we didn't truncate properly");
+  _Static_assert(-59 % -4 == -3, "we didn't truncate properly");
+
+  // Test the idiom for rounding up.
+  _Static_assert((59 + (4 - 1)) / 4 == 15, "failed to 'round up' with the 
usual idiom");
+  _Static_assert((59 + (4 - 1)) % 4 == 2, "failed to 'round up' with the usual 
idiom");
+}
+

diff  --git a/clang/test/C/C99/n629.c b/clang/test/C/C99/n629.c
new file mode 100644
index 0..01e32fb084fb6
--- /dev/null
+++ b/clang/test/C/C99/n629.c
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux -verify %s
+// RUN: %clang_cc1 -triple i686-unknown-linux -verify %s
+// RUN: %clang_cc1 -triple x86_64-unknown-win32 -verify %s
+// RUN: %clang_cc1 -triple i686-unknown-win32 -verify %s
+
+/* WG14 N629: yes
+ * integer constant type rules
+ */
+
+// expected-no-diagnostics
+
+void test_decimal_constants(void) {
+  // Easy cases where the value fits into the type you'd expect.
+  (void)_Generic(2,int : 1);
+  (void)_Generic(2u,   unsigned int : 1);
+  (void)_Generic(2l,   long : 1);
+  (void)_Generic(2ul,  unsigned long : 1);
+  (void)_Generic(2ll,  long long : 1);
+  (void)_Generic(2ull, unsigned long long : 1);
+
+#if __INT_WIDTH__ == 16
+  #if __LONG_WIDTH__ > 16
+(void)_Generic(65536, long : 1);
+(void)_Generic(65536U, unsigned long : 1);
+  #else
+(void)_Generic(65536, long long : 1);
+(void)_Generic(65536U, unsigned long : 1);
+  #endif // __LONG_WIDTH__ > 16
+#elif __INT_WIDTH__ == 32
+  #if __LONG_WIDTH__ > 32
+(void)_Generic(4294967296, long : 1);
+(void)_Generic(4294967296U, unsigned long : 1);
+  #else
+(void)_Generic(4294967296, long long : 1);
+(void)_Generic(4294967296U, unsigned long long : 1);
+  #endif // __LONG_WIDTH__ > 32
+#endif
+
+#if __LONG_WIDTH__ > 32
+  (void)_Generic(4294967296L, long : 1);
+  (void)_Generic(4294967296U, unsigned long : 1);
+#else
+  (void)_Generic(4294967296L, long long : 1);
+  (void)_Generic(4294967296U, unsigned long long : 1);
+#endif
+}
+
+void test_octal_constants(void) {
+  (void)_Generic(02,int : 1);
+  (void)_Generic(02u,   unsigned int : 1);
+  (void)_Generic(02l,   long : 1);
+  (void)_Generic(02ul,  unsigned long : 1);
+  (void)_Generic(02ll,  long long : 1);
+  (void)_Generic(02ull, unsigned long long : 1);
+
+#if __INT_WIDTH__ == 16
+  #if __LONG_WIDTH__ > 16
+(void)_Generic(020, long : 1);
+(void)_Generic(020U, unsigned long : 1);
+  #else
+(void)_Generic(020, long long : 1);
+(void)_Generic(020U, unsigned long : 1);
+  #endif // __LONG_WIDTH__ > 16
+#elif __INT_WIDTH__ == 32
+  #if __LONG_WIDTH__ > 32
+(void)_Generic(0400, long : 1);
+(void)_Generic(0400U, unsigned long : 1);
+  #else
+(void)_Generic(0400, long long : 1);
+(void)_Generic(0400U, unsigned long long : 1);
+  #endif // __LONG_WIDTH__ > 32
+#endif
+
+#if __LONG_WIDTH__ > 32
+  (void)_Generic(0400L, long : 1);
+  (void)_Generic(0400U, unsigned long : 1);
+#else
+  (void)_Generic(0400L, long long : 1);
+  (void)_Generic(0400U, unsigned long long : 1);
+#endif
+}
+
+void test_hexadecimal_constants(void) {
+  (void)_Generic(0x2,int : 1);
+  (void)_Generic(0x2u,   unsigned int : 1);
+  (void)_Generic(0x2l,   long : 1);
+  (void)_Generic(0x2ul,  unsigned long : 1);
+  (void)_Generic(0x2ll,  long long : 1);
+  (void)_Generic(0x2ull, unsigned long long : 1);
+
+#if __INT_WIDTH__ == 16
+  #if __LONG_WIDTH__ > 16
+(void)_Generic(0x1, lo

[clang-tools-extra] 6a9f79e - [pseudo] Eliminate the type-name identifier ambiguities in the grammar.

2022-08-17 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-08-17T14:30:53+02:00
New Revision: 6a9f79e1020db9f581d00791f1f644b64facfebe

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

LOG: [pseudo] Eliminate the type-name identifier ambiguities in the grammar.

See https://reviews.llvm.org/D130626 for motivation.

Identifier in the grammar has different categories (type-name, template-name,
namespace-name), they requires semantic information to resolve. This patch is
to eliminate the "local" ambiguities in type-name, and namespace-name, which
gives us a performance boost of the parser:

  - eliminate all different type rules (class-name, enum-name, typedef-name), 
and
fold them into a unified type-name, this removes the #1 type-name 
ambiguity, and
gives us a big performance boost;
  - remove the namespace-alis rules, as they're hard and uninteresting;

Note that we could eliminate more and gain more performance (like fold 
template-name,
type-name, namespace together), but at current stage, we'd like keep all 
existing
categories of the identifier (as they might assist in correlated disambiguation 
&
keep the representation of important concepts uniform).

| file   |ambiguous nodes |  forest size | glrParse performance 
|
|SemaCodeComplete.cpp|  11k -> 5.7K   | 10.4MB -> 7.9MB  | 7.1MB/s -> 9.98MB/s  
|
|   AST.cpp  |  1.3k -> 0.73K | 0.99MB -> 0.77MB | 6.7MB/s -> 8.4MB/s   
|

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

Added: 


Modified: 
clang-tools-extra/pseudo/lib/cxx/cxx.bnf
clang-tools-extra/pseudo/test/glr.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf 
b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
index bc6599c4e3c44..7221a5086acf5 100644
--- a/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ b/clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -34,14 +34,9 @@ _ := statement-seq
 _ := declaration-seq
 
 # gram.key
-typedef-name := IDENTIFIER
-typedef-name := simple-template-id
+#! we don't distinguish between namespaces and namespace aliases, as it's hard
+#! and uninteresting.
 namespace-name := IDENTIFIER
-namespace-name := namespace-alias
-namespace-alias := IDENTIFIER
-class-name := IDENTIFIER
-class-name := simple-template-id
-enum-name := IDENTIFIER
 template-name := IDENTIFIER
 
 # gram.basic
@@ -391,9 +386,12 @@ builtin-type := INT
 builtin-type := FLOAT
 builtin-type := DOUBLE
 builtin-type := VOID
-type-name := class-name
-type-name := enum-name
-type-name := typedef-name
+#! Unlike C++ standard grammar, we don't distinguish the underlying type 
(class,
+#! enum, typedef) of the IDENTIFIER, as these ambiguities are "local" and don't
+#! affect the final parse tree. Eliminating them gives a significant 
performance
+#! boost to the parser.
+type-name := IDENTIFIER
+type-name := simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier_opt IDENTIFIER
 elaborated-type-specifier := class-key simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier TEMPLATE_opt 
simple-template-id
@@ -551,7 +549,7 @@ private-module-fragment := module-keyword : PRIVATE ; 
declaration-seq_opt
 class-specifier := class-head { member-specification_opt [recover=Brackets] }
 class-head := class-key class-head-name class-virt-specifier_opt 
base-clause_opt
 class-head := class-key base-clause_opt
-class-head-name := nested-name-specifier_opt class-name
+class-head-name := nested-name-specifier_opt type-name
 class-virt-specifier := contextual-final
 class-key := CLASS
 class-key := STRUCT

diff  --git a/clang-tools-extra/pseudo/test/glr.cpp 
b/clang-tools-extra/pseudo/test/glr.cpp
index 221725c6f089f..f805e42ffa6dd 100644
--- a/clang-tools-extra/pseudo/test/glr.cpp
+++ b/clang-tools-extra/pseudo/test/glr.cpp
@@ -12,10 +12,7 @@ void foo() {
 // CHECK-NEXT: │ └─; := tok[8]
 // CHECK-NEXT: └─statement~simple-declaration := decl-specifier-seq 
init-declarator-list ;
 // CHECK-NEXT:   ├─decl-specifier-seq~simple-type-specifier := 
-// CHECK-NEXT:   │ ├─simple-type-specifier~type-name := 
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ └─type-name~IDENTIFIER := tok[5]
+// CHECK-NEXT:   │ ├─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   │ └─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   ├─init-declarator-list~ptr-declarator := ptr-operator 
ptr-declarator
 // CHECK-NEXT:   │ ├─ptr-operator~* := tok[6]
@@ -23,12 +20,11 @@ void foo() {
 // CHECK-NEXT:   └─; := tok[8]
 }
 
-// CHECK:  3 Ambiguous nodes:
+// CHECK:  2 Ambiguous nodes:
 // CHECK-NEXT: 1 simple-type-specifier
 // CHECK-NEXT: 1 statement
-// CHECK-NEXT: 1 type-name
 // CHECK-EMPTY:
 // CHECK-NEXT: 0 Opaque nodes:
 // CHECK-EMPTY:
-// C

[PATCH] D130747: [pseudo] Eliminate the type-name identifier ambiguities in the grammar.

2022-08-17 Thread Haojian Wu 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 rG6a9f79e1020d: [pseudo] Eliminate the type-name identifier 
ambiguities in the grammar. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130747

Files:
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/glr.cpp


Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -12,10 +12,7 @@
 // CHECK-NEXT: │ └─; := tok[8]
 // CHECK-NEXT: └─statement~simple-declaration := decl-specifier-seq 
init-declarator-list ;
 // CHECK-NEXT:   ├─decl-specifier-seq~simple-type-specifier := 
-// CHECK-NEXT:   │ ├─simple-type-specifier~type-name := 
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ └─type-name~IDENTIFIER := tok[5]
+// CHECK-NEXT:   │ ├─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   │ └─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   ├─init-declarator-list~ptr-declarator := ptr-operator 
ptr-declarator
 // CHECK-NEXT:   │ ├─ptr-operator~* := tok[6]
@@ -23,12 +20,11 @@
 // CHECK-NEXT:   └─; := tok[8]
 }
 
-// CHECK:  3 Ambiguous nodes:
+// CHECK:  2 Ambiguous nodes:
 // CHECK-NEXT: 1 simple-type-specifier
 // CHECK-NEXT: 1 statement
-// CHECK-NEXT: 1 type-name
 // CHECK-EMPTY:
 // CHECK-NEXT: 0 Opaque nodes:
 // CHECK-EMPTY:
-// CHECK-NEXT: Ambiguity: 0.40 misparses/token
+// CHECK-NEXT: Ambiguity: 0.20 misparses/token
 // CHECK-NEXT: Unparsed: 0.00%
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -34,14 +34,9 @@
 _ := declaration-seq
 
 # gram.key
-typedef-name := IDENTIFIER
-typedef-name := simple-template-id
+#! we don't distinguish between namespaces and namespace aliases, as it's hard
+#! and uninteresting.
 namespace-name := IDENTIFIER
-namespace-name := namespace-alias
-namespace-alias := IDENTIFIER
-class-name := IDENTIFIER
-class-name := simple-template-id
-enum-name := IDENTIFIER
 template-name := IDENTIFIER
 
 # gram.basic
@@ -391,9 +386,12 @@
 builtin-type := FLOAT
 builtin-type := DOUBLE
 builtin-type := VOID
-type-name := class-name
-type-name := enum-name
-type-name := typedef-name
+#! Unlike C++ standard grammar, we don't distinguish the underlying type 
(class,
+#! enum, typedef) of the IDENTIFIER, as these ambiguities are "local" and don't
+#! affect the final parse tree. Eliminating them gives a significant 
performance
+#! boost to the parser.
+type-name := IDENTIFIER
+type-name := simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier_opt IDENTIFIER
 elaborated-type-specifier := class-key simple-template-id
 elaborated-type-specifier := class-key nested-name-specifier TEMPLATE_opt 
simple-template-id
@@ -551,7 +549,7 @@
 class-specifier := class-head { member-specification_opt [recover=Brackets] }
 class-head := class-key class-head-name class-virt-specifier_opt 
base-clause_opt
 class-head := class-key base-clause_opt
-class-head-name := nested-name-specifier_opt class-name
+class-head-name := nested-name-specifier_opt type-name
 class-virt-specifier := contextual-final
 class-key := CLASS
 class-key := STRUCT


Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -12,10 +12,7 @@
 // CHECK-NEXT: │ └─; := tok[8]
 // CHECK-NEXT: └─statement~simple-declaration := decl-specifier-seq init-declarator-list ;
 // CHECK-NEXT:   ├─decl-specifier-seq~simple-type-specifier := 
-// CHECK-NEXT:   │ ├─simple-type-specifier~type-name := 
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ ├─type-name~IDENTIFIER := tok[5]
-// CHECK-NEXT:   │ │ └─type-name~IDENTIFIER := tok[5]
+// CHECK-NEXT:   │ ├─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   │ └─simple-type-specifier~IDENTIFIER := tok[5]
 // CHECK-NEXT:   ├─init-declarator-list~ptr-declarator := ptr-operator ptr-declarator
 // CHECK-NEXT:   │ ├─ptr-operator~* := tok[6]
@@ -23,12 +20,11 @@
 // CHECK-NEXT:   └─; := tok[8]
 }
 
-// CHECK:  3 Ambiguous nodes:
+// CHECK:  2 Ambiguous nodes:
 // CHECK-NEXT: 1 simple-type-specifier
 // CHECK-NEXT: 1 statement
-// CHECK-NEXT: 1 type-name
 // CHECK-EMPTY:
 // CHECK-NEXT: 0 Opaque nodes:
 // CHECK-EMPTY:
-// CHECK-NEXT: Ambiguity: 0.40 misparses/token
+// CHECK-NEXT: Ambiguity: 0.20 misparses/token
 // CHECK-NEXT: Unparsed: 0.00%
Index: clang-too

[PATCH] D131874: [Clang] Tighten restrictions on enum out of range diagnostic to avoid constant initialization

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI failures are unrelated to this patch.




Comment at: clang/lib/AST/ExprConstant.cpp:13547-13550
+  if (const auto *VD = 
dyn_cast_or_null(Info.EvaluatingDecl.dyn_cast())) {
+if (VD && !VD->isConstexpr())
+  ConstexprVar = false;
+  }

You already know that `VD` is nonnull, so no need for that check, and we can 
remove the predicate entirely because you're setting `ConstexprVar` based on 
`isConstexpr()` anyway.


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

https://reviews.llvm.org/D131874

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


[PATCH] D128083: [C++20] Correctly handle constexpr/consteval explicitly defaulted special member instantiation behavior

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman abandoned this revision.
aaron.ballman added a comment.

This was partially covered by https://reviews.llvm.org/D131479 and the rest 
should be handled in a different patch, so abandoning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128083

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


[PATCH] D131708: [RISCV] Change how mtune aliases are implemented.

2022-08-17 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

This seems like a sensible direction to me - let's discuss in the sync-up call 
this Thursday to check everyone is on-board and doesn't have concerns.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131708

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


[PATCH] D131990: [DRAFT][WebAssembly] Do not support `[[clang::musttail]]` by default

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

> Marked draft for further discussion because I'm not sure getting this:
>
>   test.cpp:10:7: warning: unknown attribute 'musttail' ignored 
> [-Wunknown-attributes]
>   [[clang::musttail]] return bar(x * 10);
>
> is actually better developer experience than getting a fatal error with a 
> description of the WebAssembly-specific problem.

FWIW, I think it's vastly better. A fatal error on the backend is a bug in the 
compiler. Telling the user "this attribute won't do anything for you" is a 
feature. If we think the "unknown attribute ignored" warning is too generic and 
we'd rather see something like "attribute 'foo' not supported on this target", 
that's an improvement but one we should make across all target-specific 
attributes. (FWIW, I'd be happy to review such a patch if you or anyone else 
felt like working on it. But I don't think it's a requirement for what you're 
doing here.)

I think all that's missing from this patch are test cases and a release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131990

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


[PATCH] D131942: [clang][Inter[ Implement bool and nullptr literal expressions

2022-08-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/Interp/Disasm.cpp:26
 inline std::enable_if_t::value, T> ReadArg(Program &P,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();

Are you sure this isn't intentional that this is passed by value?  With a name 
like CodePtr, it certainly SOUNDS like it means to be passed by value.



Comment at: clang/lib/AST/Interp/Function.h:69
   /// Returns a pointer to the start of the code.
-  CodePtr getCodeBegin() const;
+  CodePtr getCodeBegin() const { return Code.data(); }
   /// Returns a pointer to the end of the code.

is this an unrelated NFC change?  In the future, please keep this out of 
patches that do stuff.



Comment at: clang/lib/AST/Interp/Source.h:64
   /// Pointer into the code owned by a function.
   const char *Ptr;
 };

Ah, this DOES just wrap a pointer, passing by value is likely the right idea 
here.



Comment at: clang/test/AST/Interp/literals.cpp:14
+constexpr bool getTrue() { return true; }
+constexpr bool getFalse() { return false; }

can you also do a 'getNullptr'?  Also, a static-assert for all 3 of the 
functions as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131942

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


[clang] d483730 - Re-apply "Deferred Concept Instantiation Implementation""

2022-08-17 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-08-17T06:24:40-07:00
New Revision: d483730d8c3fa2e0d4192b2f3c61c761b124e6ad

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

LOG: Re-apply "Deferred Concept Instantiation Implementation""

This reverts commit 258c3aee54e11bc5c5d8ac137eb15e8d5bbcc7e4.

This should fix the libc++ issue that caused the revert, by re-designing
slightly how we determined when we should evaluate the constraints.
Additionally, many of the other components to the original patch (the
NFC parts) were committed separately to shrink the size of this patch
for review.

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

Added: 
clang/test/SemaTemplate/concepts-friends.cpp
clang/test/SemaTemplate/deferred-concept-inst.cpp
clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/Template.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/lib/Sema/TreeTransform.h

clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp

clang/test/CXX/temp/temp.constr/temp.constr.order/class-template-partial-specializations.cpp

clang/test/CXX/temp/temp.constr/temp.constr.order/var-template-partial-specializations.cpp
clang/test/SemaTemplate/concepts.cpp
clang/test/SemaTemplate/instantiate-requires-clause.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1da6015ad1610..4a6c9deb0c9c2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -144,6 +144,10 @@ C++ Language Changes in Clang
 
 C++20 Feature Support
 ^
+- Clang now correctly delays the instantiation of function constraints until
+  the time of checking, which should now allow the libstdc++ ranges 
implementation
+  to work for at least trivial examples.  This fixes
+  `Issue 44178 `_.
 
 - Support capturing structured bindings in lambdas
   (`P1091R3 `_ and `P1381R1 
`).

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6908eaf8ff954..85641f595d417 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3637,6 +3637,16 @@ class Sema final {
   bool ConsiderCudaAttrs = true,
   bool ConsiderRequiresClauses = true);
 
+  // Calculates whether the expression Constraint depends on an enclosing
+  // template, for the purposes of [temp.friend] p9.
+  // TemplateDepth is the 'depth' of the friend function, which is used to
+  // compare whether a declaration reference is referring to a containing
+  // template, or just the current friend function. A 'lower' TemplateDepth in
+  // the AST refers to a 'containing' template. As the constraint is
+  // uninstantiated, this is relative to the 'top' of the TU.
+  bool ConstraintExpressionDependsOnEnclosingTemplate(unsigned TemplateDepth,
+  const Expr *Constraint);
+
   enum class AllowedExplicit {
 /// Allow no explicit functions to be used.
 None,
@@ -7109,6 +7119,21 @@ class Sema final {
   LocalInstantiationScope &Scope,
   const MultiLevelTemplateArgumentList &TemplateArgs);
 
+  /// used by SetupConstraintCheckingTemplateArgumentsAndScope to 
recursively(in
+  /// the case of lambdas) set up the LocalInstantiationScope of the current
+  /// function.
+  bool SetupConstraintScope(
+  FunctionDecl *FD, llvm::Optional> 
TemplateArgs,
+  MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope);
+
+  /// Used during constraint checking, sets up the constraint template arguemnt
+  /// lists, and calls SetupConstraintScope to set up the
+  /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
+  llvm::Optional
+  SetupConstraintCheckingTemplateArgumentsAndScope(
+  FunctionDecl *FD, llvm::Optional> 
TemplateArgs,
+  LocalInstantiationScope &Scope);
+
 public:
   const NormalizedConstraint *
   getNormalizedAssociatedConstraints(
@@ -7151,6 +7176,39 @@ class Sema final {
   bool CheckConstraintSatisfaction(
   const NamedDecl *Template, ArrayRef ConstraintExprs,
   const MultiLevelTemplateArgumentList &TemplateArgLists,
+  SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) {
+llvm::SmallVector Converted;
+return CheckConstraintSatisfaction(Template, Constraint

[PATCH] D126907: Deferred Concept Instantiation Implementation Take 2

2022-08-17 Thread Erich Keane 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 rGd483730d8c3f: Re-apply "Deferred Concept Instantiation 
Implementation"" (authored by erichkeane).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126907

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  
clang/test/CXX/temp/temp.constr/temp.constr.order/class-template-partial-specializations.cpp
  
clang/test/CXX/temp/temp.constr/temp.constr.order/var-template-partial-specializations.cpp
  clang/test/SemaTemplate/concepts-friends.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+  requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};// #FOO
+
+template 
+void TrailingReturn(T)   // #TRAILING
+  requires(sizeof(T) > 2) || // #TRAILING_REQ
+  T::value   // #TRAILING_REQ_VAL
+{};
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -Wno-unused-value -verify
 
 template  requires ((sizeof(Args) == 1), ...)
 // expected-note@-1 {{because '(sizeof(int) == 1) , (sizeof(char) == 1) , (sizeof(int) == 1)' evaluated to false}}
@@ -40,6 +40,20 @@
 
 static_assert(S::f(1));
 
+// Similar to the 'S' test, but tries to use 'U' in the requires clause.
+template 
+struct S1 {
+  // expected-note@+3 {{candidate template i

[PATCH] D129016: [PowerPC] implemented @llvm.ppc.kill.canary to corrupt stack guard

2022-08-17 Thread Paul Scoropan via Phabricator via cfe-commits
pscoro updated this revision to Diff 453272.
pscoro added a comment.

Reverted chain revision again, final


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129016

Files:
  clang/include/clang/Basic/BuiltinsPPC.def
  clang/lib/Basic/Targets/PPC.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-stackprotect.c
  llvm/include/llvm/IR/IntrinsicsPowerPC.td
  llvm/lib/Target/PowerPC/PPCISelLowering.cpp
  llvm/test/CodeGen/PowerPC/kill-canary-intrinsic.ll

Index: llvm/test/CodeGen/PowerPC/kill-canary-intrinsic.ll
===
--- /dev/null
+++ llvm/test/CodeGen/PowerPC/kill-canary-intrinsic.ll
@@ -0,0 +1,206 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-aix -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-AIX
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-AIX64
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-LINUX-LE
+
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-aix -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr8 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-AIX
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-linux-gnu -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr8 --ppc-asm-full-reg-names < %s | FileCheck %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr8 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-AIX64
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr8 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-LINUX-LE
+
+; RUN: llc -verify-machineinstrs -O0 -mtriple=powerpc-unknown-aix -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-AIX-FAST
+; RUN: llc -verify-machineinstrs -O0 -mtriple=powerpc64-unknown-linux-gnu -ppc-vsr-nums-as-vr \
+; RUN:   -mcpu=pwr7 --ppc-asm-full-reg-names < %s | FileCheck %s -check-prefix=CHECK-FAST
+
+attributes #1 = { nounwind }
+declare void @llvm.ppc.kill.canary()
+define dso_local void @test_kill_canary() #1 {
+; CHECK-AIX-LABEL: test_kill_canary:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:blr
+;
+; CHECK-LABEL: test_kill_canary:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:blr
+;
+; CHECK-AIX64-LABEL: test_kill_canary:
+; CHECK-AIX64:   # %bb.0: # %entry
+; CHECK-AIX64-NEXT:blr
+;
+; CHECK-LINUX-LE-LABEL: test_kill_canary:
+; CHECK-LINUX-LE:   # %bb.0: # %entry
+; CHECK-LINUX-LE-NEXT:blr
+;
+; CHECK-AIX-FAST-LABEL: test_kill_canary:
+; CHECK-AIX-FAST:   # %bb.0: # %entry
+; CHECK-AIX-FAST-NEXT:blr
+;
+; CHECK-FAST-LABEL: test_kill_canary:
+; CHECK-FAST:   # %bb.0: # %entry
+; CHECK-FAST-NEXT:blr
+entry:
+  call void @llvm.ppc.kill.canary()
+  ret void
+}
+
+attributes #0 = { sspreq }
+; Function Attrs: sspreq
+define dso_local void @test_kill_canary_ssp() #0 #1 {
+; CHECK-AIX-LABEL: test_kill_canary_ssp:
+; CHECK-AIX:   # %bb.0: # %entry
+; CHECK-AIX-NEXT:mflr r0
+; CHECK-AIX-NEXT:stw r0, 8(r1)
+; CHECK-AIX-NEXT:stwu r1, -64(r1)
+; CHECK-AIX-NEXT:lwz r3, L..C0(r2) # @__ssp_canary_word
+; CHECK-AIX-NEXT:lwz r4, 0(r3)
+; CHECK-AIX-NEXT:stw r4, 60(r1)
+; CHECK-AIX-NEXT:lwz r4, 0(r3)
+; CHECK-AIX-NEXT:not r4, r4
+; CHECK-AIX-NEXT:stw r4, 60(r1)
+; CHECK-AIX-NEXT:lwz r3, 0(r3)
+; CHECK-AIX-NEXT:lwz r4, 60(r1)
+; CHECK-AIX-NEXT:cmplw r3, r4
+; CHECK-AIX-NEXT:bne cr0, L..BB1_2
+; CHECK-AIX-NEXT:  # %bb.1: # %entry
+; CHECK-AIX-NEXT:addi r1, r1, 64
+; CHECK-AIX-NEXT:lwz r0, 8(r1)
+; CHECK-AIX-NEXT:mtlr r0
+; CHECK-AIX-NEXT:blr
+; CHECK-AIX-NEXT:  L..BB1_2: # %entry
+; CHECK-AIX-NEXT:bl .__stack_chk_fail[PR]
+; CHECK-AIX-NEXT:nop
+;
+; CHECK-LABEL: test_kill_canary_ssp:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:mflr r0
+; CHECK-NEXT:std r0, 16(r1)
+; CHECK-NEXT:stdu r1, -128(r1)
+; CHECK-NEXT:ld r3, -28688(r13)
+; CHECK-NEXT:std r3, 120(r1)
+; CHECK-NEXT:ld r3, -28688(r13)
+; CHECK-NEXT:not r3, r3
+; CHECK-NEXT:std r3, 120(r1)
+; CHECK-NEXT:ld r3, 120(r1)
+; CHECK-NEXT:ld r4, -28688(r13)
+; CHECK-NEXT:cmpld r4, r3
+; CHECK-NEXT:bne cr0, .LBB1_2
+; CHECK-NEXT:  # %bb.1: # %entry
+; CHECK-NEXT:addi r1, r1, 128
+; CHECK-NEXT:ld r0, 16(r1)
+; CHECK-NEXT:  

[PATCH] D131683: Diagnosing the Future Keywords

2022-08-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

I didn't have time to dig into the correctness of the TokenKinds or test 
changes (hopefully @aaron.ballman can take some time on that), but 
implementation overall looks correct, just with some style/formatting issues.




Comment at: clang/include/clang/Basic/TokenKinds.def:82
 #endif
+#ifndef C99_KEYWORD
+#define C99_KEYWORD(X,Y) KEYWORD(X,KEYC99|(Y))

NiT: Would be nice to put these next to the OTHER language standards 



Comment at: clang/lib/Basic/IdentifierTable.cpp:852
+
+//===--===//
+// IdentifierTable Implementation

This comment block shouldn't be here at all.



Comment at: clang/lib/Basic/IdentifierTable.cpp:863
+
+  // Getting the flag value. i.e bool keyword passing it name to the function
+  // and will return the flag value that which keys are used then will use for

This comment doesn't really make any sense here.  I dont understand what you're 
trying to say.



Comment at: clang/lib/Basic/IdentifierTable.cpp:874
+
+  // If C++.
+  if (LangOpts.CPlusPlus) {

This comment isn't helpful.



Comment at: clang/lib/Basic/IdentifierTable.cpp:884
+  // If C.
+  if (!LangOpts.CPlusPlus) {
+if ((Flags & KEYC99) == KEYC99)

just make this an 'else'.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131683

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


[PATCH] D122215: [WebAssembly] Initial support for reference type externref in clang

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

Adding new types to the type system is quite invasive; was there an RFC for 
this you can point me to along with a design document? I have no idea how to 
review this because I don't know what the semantics of this type are supposed 
to be.




Comment at: clang/include/clang/AST/ASTContext.h:1496
 
+  /// Return a WebAssembly externref type
+  QualType getExternrefType() const;





Comment at: clang/include/clang/AST/Type.h:1972-1973
+  /// Check if this is a WebAssembly Reference Type.
+  bool isWebAssemblyReferenceType() const;
+  bool isWebAssemblyExternrefType() const;
   /// Determines if this is a sizeless type supported by the

It's unfortunate to name this with `ReferenceType` given that we already have a 
considerable number of APIs that assume "reference type" to mean `&` or `&&`. 
We run into similar problems with "pointer type" and objective-c pointers.

Basically, I worry we're setting ourselves up for another 
`isObjCObjectPointerType()`/`isPointerType()` situation.



Comment at: clang/include/clang/Basic/AddressSpaces.h:59-60
 
+  wasm_var,
+  wasm_externref,
   // This denotes the count of language-specific address spaces and also

tlively wrote:
> What is `wasm_var`? It would be good to have a short comment here (and 
> newline afterward).
Agreed; I'm not certain why `wasm_var` is part of this changeset.



Comment at: clang/include/clang/Basic/Attr.td:3937-3944
+def WebAssemblyFuncref : TypeAttr, TargetSpecificAttr {
+  let Spellings = [Clang<"funcref">];
+  let Args = [];
+  let Documentation = [Undocumented];
+  // Represented as part of the enclosing function pointer type.
+  let ASTNode = 0;
+}

No new undocumented attributes, please. No need for the `Args` field, and 
please add the newline back to the end of the file.



Comment at: clang/include/clang/Basic/Builtins.def:50
 //  p -> pid_t
+//  e -> wasm externref
 //  . -> "...".  This may only occur at the end of the function list.

tlively wrote:
> 
How often do you expect to use this marking? If it's only going to be used once 
or twice, it might make sense to not steal a letter but instead use custom 
checking for the signature.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:11683-11686
+def err_wasm_reference_pointer : Error<
+  "pointers to WebAssembly reference types are illegal">;
+def err_wasm_reference_reference : Error<
+  "references to WebAssembly reference types are illegal">;

These can be combined with a `%select`



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:11687-11690
+def err_wasm_capture_reference : Error<
+  "cannot capture WebAssembly reference">;
+def err_wasm_addrof_reference : Error<
+  "cannot take address of WebAssembly reference">;

These can also be combined with a `%select`



Comment at: clang/include/clang/Basic/WebAssemblyReferenceTypes.def:16
+//
+//  - Name is the name of the builtin type.  MangledName is the mangled name.
+//

What kind of mangling is this name? Itanium? Microsoft? Something else?



Comment at: clang/lib/AST/ASTContext.cpp:952-953
+12, // ptr64
+1,  // wasm_var
+10, // wasm_externref,
 };

How did you arrive at these values?



Comment at: clang/lib/AST/ItaniumMangle.cpp:3147
+type_name = MangledName;   
\
+Out << (type_name == InternalName ? "u" : "") << type_name.size()  
\
+<< type_name;  
\

tlively wrote:
> Our `MangledName` is not the same as our `InternalName`, so it looks like 
> this condition will never be true. Should be follow the simpler pattern from 
> the previous two targets instead?
I'm not an Itanium mangling expert, but doesn't this *have* to use the `u` 
marking per 
https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.builtin-type because 
this is definitely a vendor extension type.



Comment at: clang/lib/AST/MicrosoftMangle.cpp:2480-2481
 #include "clang/Basic/RISCVVTypes.def"
+#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
+#include "clang/Basic/WebAssemblyReferenceTypes.def"
   case BuiltinType::ShortAccum:

Is it reasonable that this simply cannot mangle in Microsoft ABI mode?



Comment at: clang/lib/AST/Type.cpp:2330-2333
+  const BuiltinType *BT = getAs();
+  if (BT && BT->getKind() == BuiltinType::WasmExternRef)
+return true;
+  return false;





Comment at: clang/lib/Sema/SemaType.cpp:2179-2184
+  if (getASTCont

[PATCH] D131780: [clang-tidy] Do not trigger cppcoreguidelines-avoid-const-or-ref-data-members on lambda captures

2022-08-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp updated this revision to Diff 453277.
carlosgalvezp added a comment.

Added unit test for implicit capture (ref and value)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

Files:
  
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
@@ -167,3 +167,28 @@
 TemplatedConstRef t3{123};
 TemplatedRefRef t4{123};
 TemplatedRef t5{t1.t};
+
+// Lambdas capturing const or ref members should not trigger warnings
+void lambdas()
+{
+  int x1{123};
+  const int x2{123};
+  const int& x3{123};
+  int&& x4{123};
+  int& x5{x1};
+
+  auto v1 = [x1]{};
+  auto v2 = [x2]{};
+  auto v3 = [x3]{};
+  auto v4 = [x4]{};
+  auto v5 = [x5]{};
+
+  auto r1 = [&x1]{};
+  auto r2 = [&x2]{};
+  auto r3 = [&x3]{};
+  auto r4 = [&x4]{};
+  auto r5 = [&x5]{};
+
+  auto iv = [=]{};
+  auto ir = [&]{};
+}
Index: 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
===
--- 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
+++ 
clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
@@ -15,12 +15,23 @@
 namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
+namespace {
+
+AST_MATCHER(FieldDecl, isMemberOfLambda) {
+  return Node.getParent()->isLambda();
+}
+
+} // namespace
 
 void AvoidConstOrRefDataMembersCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  fieldDecl(hasType(hasCanonicalType(referenceType(.bind("ref"), this);
-  Finder->addMatcher(
-  fieldDecl(hasType(qualType(isConstQualified(.bind("const"), this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(hasCanonicalType(referenceType(
+ .bind("ref"),
+ this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(qualType(isConstQualified(
+ .bind("const"),
+ this);
 }
 
 void AvoidConstOrRefDataMembersCheck::check(


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
@@ -167,3 +167,28 @@
 TemplatedConstRef t3{123};
 TemplatedRefRef t4{123};
 TemplatedRef t5{t1.t};
+
+// Lambdas capturing const or ref members should not trigger warnings
+void lambdas()
+{
+  int x1{123};
+  const int x2{123};
+  const int& x3{123};
+  int&& x4{123};
+  int& x5{x1};
+
+  auto v1 = [x1]{};
+  auto v2 = [x2]{};
+  auto v3 = [x3]{};
+  auto v4 = [x4]{};
+  auto v5 = [x5]{};
+
+  auto r1 = [&x1]{};
+  auto r2 = [&x2]{};
+  auto r3 = [&x3]{};
+  auto r4 = [&x4]{};
+  auto r5 = [&x5]{};
+
+  auto iv = [=]{};
+  auto ir = [&]{};
+}
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
@@ -15,12 +15,23 @@
 namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
+namespace {
+
+AST_MATCHER(FieldDecl, isMemberOfLambda) {
+  return Node.getParent()->isLambda();
+}
+
+} // namespace
 
 void AvoidConstOrRefDataMembersCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  fieldDecl(hasType(hasCanonicalType(referenceType(.bind("ref"), this);
-  Finder->addMatcher(
-  fieldDecl(hasType(qualType(isConstQualified(.bind("const"), this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(hasCanonicalType(referenceType(
+ .bind("ref"),
+ this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(qualType(isConstQualified(
+ .bind("const"),
+ this);
 }
 
 void AvoidConstOrRefDataMembersCheck::check(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
h

[PATCH] D128440: [WebAssembly] Initial support for reference type funcref in clang

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

Same question here about an RFC for adding this new type to the type system and 
a design document for how the type behaves as in 
https://reviews.llvm.org/D122215.




Comment at: clang/include/clang/Basic/Attr.td:4053
+  let Spellings = [Keyword<"__funcref">];
+  let Documentation = [Undocumented];
+}

tlively wrote:
> It would be good to document this!
It's a requirement that this be documented. Also, this should probably have a 
`Subjects` line that expects a function of some sort? (It doesn't impact the 
semantics of anything, but it self-documents the expectations for people 
reading Attr.td.)



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7332
+def err_attribute_webassembly_funcref : Error<
+  "'__clang_webassembly_funcref' attribute can only be applied to function 
pointer types">;
 

1) What is `__clang_webassembly_funcref`? Did you mean `__funcref`?
2) There's no test coverage for this diagnostic.



Comment at: clang/include/clang/Basic/TokenKinds.def:666
+// WebAssembly Type Extension
+KEYWORD(__funcref , KEYALL)
+

Why is this a keyword in all language modes?



Comment at: clang/include/clang/Parse/Parser.h:2843
   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
+  void ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs);
   void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();





Comment at: clang/include/clang/Sema/Sema.h:13103-13104
  CallExpr *TheCall);
+  bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned 
BuiltinID,
+ CallExpr *TheCall);
 

Formatting is off here.



Comment at: clang/include/clang/Sema/Sema.h:13169
+  // WebAssembly builtin handling
+  bool SemaBuiltinWasmRefNullFunc(CallExpr *TheCall);
+

I think there's a verb missing from this function identifier -- also, I don't 
think we need to continue the terrible trend of prepending `Sema` onto the 
function name which lives in the `Sema` object.



Comment at: clang/lib/AST/ASTContext.cpp:954
 10, // wasm_externref,
+20, // wasm_funcref
 };

Where did this value come from?



Comment at: clang/lib/Parse/ParseDecl.cpp:845-846
 
+void Parser::ParseWebAssemblyFuncrefTypeAttribute(ParsedAttributes &attrs) {
+  if (Tok.getKind() == tok::kw___funcref) {
+IdentifierInfo *AttrName = Tok.getIdentifierInfo();





Comment at: clang/lib/Parse/ParseDecl.cpp:851-854
+  } else {
+return;
+  }
+}





Comment at: clang/lib/Parse/ParseDecl.cpp:5780
+case tok::kw___funcref:
+  if (AttrReqs & AR_DeclspecAttributesParsed) {
+ParseWebAssemblyFuncrefTypeAttribute(DS.getAttributes());

Why that specific ordering as opposed to `AR_VendorAttributesParsed`?



Comment at: clang/lib/Sema/SemaChecking.cpp:6557-6561
+  // Therefore we need to change the types of the DeclRefExpr (stored in FDecl)
+  // and regenerate a straight up CallExpr on the modified FDecl.
+  // returning
+  // CallExpr
+  // `- FunctionDecl

Why would we need to do this?? And what do we do when there is no 
`FunctionDecl` to get back to (because it's a call expression through a 
function pointer, for example)?



Comment at: clang/lib/Sema/SemaChecking.cpp:6564
+  // Prepare FDecl type
+  QualType Pointee = Context.getFunctionType(Context.VoidTy, {}, {});
+  QualType Type = Context.getPointerType(Pointee);

Why are you guaranteed this function returns void?



Comment at: clang/lib/Sema/SemaType.cpp:7256
+  QualType Desugared = Type;
+  const AttributedType *AT = dyn_cast(Type);
+  while (AT) {





Comment at: clang/lib/Sema/SemaType.cpp:7269
+  }
+  Attrs[NewAttrKind] = true;
+

This seems like it's not used.



Comment at: clang/lib/Sema/SemaType.cpp:7289-7290
+  QualType Pointee = Type->getPointeeType();
+  Pointee = S.Context.getAddrSpaceQualType(
+  S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
+  Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));

What happens when the user's function already has an explicitly specified 
address space?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128440

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


[PATCH] D130510: Missing tautological compare warnings due to unary operators

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D130510#3727096 , @rtrieu wrote:

> This patch has been moving back and forth between 
> `IsIntegerLiteralConstantExpr` and `getIntegerLiteralSubexpressionValue`.  
> The first function is preexisting and the second one is a new function.  The 
> final patch seems to settle on using just 
> `getIntegerLiteralSubexpressionValue`.  Can you explain why the existing 
> function does not meet your needs?  It wasn't clear from the update messages 
> why you went that way.

The existing function returns whether the expression is an ICE (sort of), the 
replacement function calculates the actual value and returns an optional APInt 
so you can perform operations on it directly. That said, a future refactoring 
could probably remove `IsIntegerLiteralConstantExpr()` and replace it with 
`getIntegerLiteralSubexpressionValue()`, but the only caller of 
`IsIntegerLiteralConstantExpr()` doesn't actually need the value at that point.

> Besides that, there is added support for multiple unary operators, but only 
> minus is tested.  Each one should have at least a positive and a negative 
> test to show it is supported.

Good catch! I agree those tests should be added.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

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


[PATCH] D130510: Missing tautological compare warnings due to unary operators

2022-08-17 Thread Muhammad Usman Shahid via Phabricator via cfe-commits
Codesbyusman added a comment.

working on the test. Will update the patch soon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

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


[PATCH] D131935: [clang][llvm][NFC] Change misexpect's tolerance option to be 32-bit

2022-08-17 Thread Joe Loser via Phabricator via cfe-commits
jloser accepted this revision.
jloser added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks for the follow-up cleanup. I'll rebase once this lands to avoid 
the cast in https://reviews.llvm.org/D131869 if that works for you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131935

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


[clang] 656c5d6 - [clang][llvm][NFC] Change misexpect's tolerance option to be 32-bit

2022-08-17 Thread Paul Kirth via cfe-commits

Author: Paul Kirth
Date: 2022-08-17T14:38:53Z
New Revision: 656c5d652ce10257e90c7693b34336b6ce0ecfa3

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

LOG: [clang][llvm][NFC] Change misexpect's tolerance option to be 32-bit

In D131869 we noticed that we jump through some hoops because we parse the
tolerance option used in MisExpect.cpp into a 64-bit integer. This is
unnecessary, since the value can only be in the range [0, 100).

This patch changes the underlying type to be 32-bit from where it is
parsed in Clang through to it's use in LLVM.

Reviewed By: jloser

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.h
clang/lib/Frontend/CompilerInvocation.cpp
llvm/include/llvm/IR/LLVMContext.h
llvm/lib/IR/LLVMContext.cpp
llvm/lib/IR/LLVMContextImpl.h
llvm/lib/Transforms/Utils/MisExpect.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index cd204e5d7c15..7fffb3833888 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -424,7 +424,7 @@ class CodeGenOptions : public CodeGenOptionsBase {
 
   /// The maximum percentage profiling weights can deviate from the expected
   /// values in order to be included in misexpect diagnostics.
-  Optional DiagnosticsMisExpectTolerance = 0;
+  Optional DiagnosticsMisExpectTolerance = 0;
 
 public:
   // Define accessors/mutators for code generation options of enumeration type.

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 7073828f8f6d..9731d4006d1e 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -113,8 +113,8 @@ using namespace llvm::opt;
 
 // Parse misexpect tolerance argument value.
 // Valid option values are integers in the range [0, 100)
-inline Expected> parseToleranceOption(StringRef Arg) {
-  int64_t Val;
+inline Expected> parseToleranceOption(StringRef Arg) {
+  uint32_t Val;
   if (Arg.getAsInteger(10, Val))
 return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Not an integer: %s", Arg.data());

diff  --git a/llvm/include/llvm/IR/LLVMContext.h 
b/llvm/include/llvm/IR/LLVMContext.h
index 792e59a30362..0caddad25bfe 100644
--- a/llvm/include/llvm/IR/LLVMContext.h
+++ b/llvm/include/llvm/IR/LLVMContext.h
@@ -204,8 +204,8 @@ class LLVMContext {
 
   bool getMisExpectWarningRequested() const;
   void setMisExpectWarningRequested(bool Requested);
-  void setDiagnosticsMisExpectTolerance(Optional Tolerance);
-  uint64_t getDiagnosticsMisExpectTolerance() const;
+  void setDiagnosticsMisExpectTolerance(Optional Tolerance);
+  uint32_t getDiagnosticsMisExpectTolerance() const;
 
   /// Return the minimum hotness value a diagnostic would need in order
   /// to be included in optimization diagnostics.

diff  --git a/llvm/lib/IR/LLVMContext.cpp b/llvm/lib/IR/LLVMContext.cpp
index 57d72611011e..993bf006 100644
--- a/llvm/lib/IR/LLVMContext.cpp
+++ b/llvm/lib/IR/LLVMContext.cpp
@@ -148,10 +148,10 @@ uint64_t LLVMContext::getDiagnosticsHotnessThreshold() 
const {
   return pImpl->DiagnosticsHotnessThreshold.value_or(UINT64_MAX);
 }
 void LLVMContext::setDiagnosticsMisExpectTolerance(
-Optional Tolerance) {
+Optional Tolerance) {
   pImpl->DiagnosticsMisExpectTolerance = Tolerance;
 }
-uint64_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
+uint32_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
   return pImpl->DiagnosticsMisExpectTolerance.value_or(0);
 }
 

diff  --git a/llvm/lib/IR/LLVMContextImpl.h b/llvm/lib/IR/LLVMContextImpl.h
index a36e46fe2465..0b1e5194222f 100644
--- a/llvm/lib/IR/LLVMContextImpl.h
+++ b/llvm/lib/IR/LLVMContextImpl.h
@@ -1387,8 +1387,8 @@ class LLVMContextImpl {
   Optional DiagnosticsHotnessThreshold = 0;
 
   /// The percentage of 
diff erence between profiling branch weights and
-  // llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
-  Optional DiagnosticsMisExpectTolerance = 0;
+  /// llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
+  Optional DiagnosticsMisExpectTolerance = 0;
   bool MisExpectWarningRequested = false;
 
   /// The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.

diff  --git a/llvm/lib/Transforms/Utils/MisExpect.cpp 
b/llvm/lib/Transforms/Utils/MisExpect.cpp
index 8f94902b331f..28649b083f3b 100644
--- a/llvm/lib/Transforms/Utils/MisExpect.cpp
+++ b/llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -58,7 +58,7 @@ static cl::opt PGOWarnMisExpect(
 cl::desc("Use this option to turn on/off "
  "warnings about incorrec

[PATCH] D131935: [clang][llvm][NFC] Change misexpect's tolerance option to be 32-bit

2022-08-17 Thread Paul Kirth 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 rG656c5d652ce1: [clang][llvm][NFC] Change misexpect's 
tolerance option to be 32-bit (authored by paulkirth).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131935

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/IR/LLVMContext.h
  llvm/lib/IR/LLVMContext.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/Transforms/Utils/MisExpect.cpp


Index: llvm/lib/Transforms/Utils/MisExpect.cpp
===
--- llvm/lib/Transforms/Utils/MisExpect.cpp
+++ llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -58,7 +58,7 @@
 cl::desc("Use this option to turn on/off "
  "warnings about incorrect usage of llvm.expect intrinsics."));
 
-static cl::opt MisExpectTolerance(
+static cl::opt MisExpectTolerance(
 "misexpect-tolerance", cl::init(0),
 cl::desc("Prevents emiting diagnostics when profile counts are "
  "within N% of the threshold.."));
@@ -72,7 +72,7 @@
 }
 
 uint64_t getMisExpectTolerance(LLVMContext &Ctx) {
-  return std::max(static_cast(MisExpectTolerance),
+  return std::max(static_cast(MisExpectTolerance),
   Ctx.getDiagnosticsMisExpectTolerance());
 }
 
Index: llvm/lib/IR/LLVMContextImpl.h
===
--- llvm/lib/IR/LLVMContextImpl.h
+++ llvm/lib/IR/LLVMContextImpl.h
@@ -1387,8 +1387,8 @@
   Optional DiagnosticsHotnessThreshold = 0;
 
   /// The percentage of difference between profiling branch weights and
-  // llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
-  Optional DiagnosticsMisExpectTolerance = 0;
+  /// llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
+  Optional DiagnosticsMisExpectTolerance = 0;
   bool MisExpectWarningRequested = false;
 
   /// The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.
Index: llvm/lib/IR/LLVMContext.cpp
===
--- llvm/lib/IR/LLVMContext.cpp
+++ llvm/lib/IR/LLVMContext.cpp
@@ -148,10 +148,10 @@
   return pImpl->DiagnosticsHotnessThreshold.value_or(UINT64_MAX);
 }
 void LLVMContext::setDiagnosticsMisExpectTolerance(
-Optional Tolerance) {
+Optional Tolerance) {
   pImpl->DiagnosticsMisExpectTolerance = Tolerance;
 }
-uint64_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
+uint32_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
   return pImpl->DiagnosticsMisExpectTolerance.value_or(0);
 }
 
Index: llvm/include/llvm/IR/LLVMContext.h
===
--- llvm/include/llvm/IR/LLVMContext.h
+++ llvm/include/llvm/IR/LLVMContext.h
@@ -204,8 +204,8 @@
 
   bool getMisExpectWarningRequested() const;
   void setMisExpectWarningRequested(bool Requested);
-  void setDiagnosticsMisExpectTolerance(Optional Tolerance);
-  uint64_t getDiagnosticsMisExpectTolerance() const;
+  void setDiagnosticsMisExpectTolerance(Optional Tolerance);
+  uint32_t getDiagnosticsMisExpectTolerance() const;
 
   /// Return the minimum hotness value a diagnostic would need in order
   /// to be included in optimization diagnostics.
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -113,8 +113,8 @@
 
 // Parse misexpect tolerance argument value.
 // Valid option values are integers in the range [0, 100)
-inline Expected> parseToleranceOption(StringRef Arg) {
-  int64_t Val;
+inline Expected> parseToleranceOption(StringRef Arg) {
+  uint32_t Val;
   if (Arg.getAsInteger(10, Val))
 return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Not an integer: %s", Arg.data());
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -424,7 +424,7 @@
 
   /// The maximum percentage profiling weights can deviate from the expected
   /// values in order to be included in misexpect diagnostics.
-  Optional DiagnosticsMisExpectTolerance = 0;
+  Optional DiagnosticsMisExpectTolerance = 0;
 
 public:
   // Define accessors/mutators for code generation options of enumeration type.


Index: llvm/lib/Transforms/Utils/MisExpect.cpp
===
--- llvm/lib/Transforms/Utils/MisExpect.cpp
+++ llvm/lib/Transforms/Utils/MisExpect.cpp
@@ -58,7 +58,7 @@
 cl::desc("Use this option to turn on/off "
  "warnings about incorrect usage of llvm.expect intrinsi

[PATCH] D131942: [clang][Inter[ Implement bool and nullptr literal expressions

2022-08-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Disasm.cpp:26
 inline std::enable_if_t::value, T> ReadArg(Program &P,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();

erichkeane wrote:
> Are you sure this isn't intentional that this is passed by value?  With a 
> name like CodePtr, it certainly SOUNDS like it means to be passed by value.
`CodePtr::read()` advances the pointer that `CodePtr` wraps , so copying just 
to call `read()` on it makes little sense. E.g. in 
https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Interp/Interp.cpp#L401-L412,
 `ReadArg` must advance the `CodePtr`, otherwise two consecutive `ReadArg` 
calls will read the same thing.



Comment at: clang/lib/AST/Interp/Function.h:69
   /// Returns a pointer to the start of the code.
-  CodePtr getCodeBegin() const;
+  CodePtr getCodeBegin() const { return Code.data(); }
   /// Returns a pointer to the end of the code.

erichkeane wrote:
> is this an unrelated NFC change?  In the future, please keep this out of 
> patches that do stuff.
Okay.



Comment at: clang/test/AST/Interp/literals.cpp:14
+constexpr bool getTrue() { return true; }
+constexpr bool getFalse() { return false; }

erichkeane wrote:
> can you also do a 'getNullptr'?  Also, a static-assert for all 3 of the 
> functions as well.
I can do a `getNull()`, but I can't call any of the functions yet, function 
calls aren't implemented yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131942

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


[PATCH] D131942: [clang][Inter[ Implement bool and nullptr literal expressions

2022-08-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 453284.

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

https://reviews.llvm.org/D131942

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Disasm.cpp
  clang/lib/AST/Interp/Function.cpp
  clang/lib/AST/Interp/Function.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Source.h
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/literals.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++11 -verify %s
+
+static_assert(true, "");
+static_assert(false, ""); // expected-error{{failed}}
+static_assert(nullptr == nullptr, "");
+static_assert(1 == 1, "");
+static_assert(1 == 3, ""); // expected-error{{failed}}
+
+constexpr int number = 10;
+static_assert(number == 10, "");
+static_assert(number != 10, ""); // expected-error{{failed}}
+
+constexpr bool getTrue() { return true; }
+constexpr bool getFalse() { return false; }
+constexpr void* getNull() { return nullptr; }
Index: clang/lib/AST/Interp/Source.h
===
--- clang/lib/AST/Interp/Source.h
+++ clang/lib/AST/Interp/Source.h
@@ -22,7 +22,7 @@
 class Function;
 
 /// Pointer into the code segment.
-class CodePtr {
+class CodePtr final {
 public:
   CodePtr() : Ptr(nullptr) {}
 
@@ -43,6 +43,8 @@
 
   bool operator!=(const CodePtr &RHS) const { return Ptr != RHS.Ptr; }
 
+  operator bool() const { return Ptr; }
+
   /// Reads data and advances the pointer.
   template  std::enable_if_t::value, T> read() {
 using namespace llvm::support;
@@ -63,7 +65,7 @@
 };
 
 /// Describes the statement/declaration an opcode was generated from.
-class SourceInfo {
+class SourceInfo final {
 public:
   SourceInfo() {}
   SourceInfo(const Stmt *E) : Source(E) {}
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -956,13 +956,13 @@
 
 template 
 inline std::enable_if_t::value, T> ReadArg(InterpState &S,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();
 }
 
 template 
 inline std::enable_if_t::value, T> ReadArg(InterpState &S,
-  CodePtr OpPC) {
+  CodePtr &OpPC) {
   uint32_t ID = OpPC.read();
   return reinterpret_cast(S.P.getNativePointer(ID));
 }
Index: clang/lib/AST/Interp/Interp.cpp
===
--- clang/lib/AST/Interp/Interp.cpp
+++ clang/lib/AST/Interp/Interp.cpp
@@ -399,8 +399,13 @@
   return false;
 }
 bool Interpret(InterpState &S, APValue &Result) {
+  assert(!S.Current->isRoot());
   CodePtr PC = S.Current->getPC();
 
+  // Empty program.
+  if (!PC)
+return true;
+
   for (;;) {
 auto Op = PC.read();
 CodePtr OpPC = PC;
Index: clang/lib/AST/Interp/Function.h
===
--- clang/lib/AST/Interp/Function.h
+++ clang/lib/AST/Interp/Function.h
@@ -66,13 +66,17 @@
   unsigned getArgSize() const { return ArgSize; }
 
   /// Returns a pointer to the start of the code.
-  CodePtr getCodeBegin() const;
+  CodePtr getCodeBegin() const { return Code.data(); }
   /// Returns a pointer to the end of the code.
-  CodePtr getCodeEnd() const;
+  CodePtr getCodeEnd() const { return Code.data() + Code.size(); }
 
   /// Returns the original FunctionDecl.
   const FunctionDecl *getDecl() const { return F; }
 
+  /// Returns the name of the function decl this code
+  /// was generated for.
+  const std::string getName() const { return F->getNameInfo().getAsString(); }
+
   /// Returns the location.
   SourceLocation getLoc() const { return Loc; }
 
Index: clang/lib/AST/Interp/Function.cpp
===
--- clang/lib/AST/Interp/Function.cpp
+++ clang/lib/AST/Interp/Function.cpp
@@ -21,10 +21,6 @@
 : P(P), Loc(F->getBeginLoc()), F(F), ArgSize(ArgSize),
   ParamTypes(std::move(ParamTypes)), Params(std::move(Params)) {}
 
-CodePtr Function::getCodeBegin() const { return Code.data(); }
-
-CodePtr Function::getCodeEnd() const { return Code.data() + Code.size(); }
-
 Function::ParamDescriptor Function::getParamDescriptor(unsigned Offset) const {
   auto It = Params.find(Offset);
   assert(It != Params.end() && "Invalid parameter offset");
Index: clang/lib/AST/Interp/Disasm.cpp
===
--- clang/lib/AST/Interp/Disasm.cpp
+++ clang/lib/AST/Interp/Disasm.cpp
@@ -23,13 +23,13 @@
 
 templa

[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/Interp/Disasm.cpp:26
 inline std::enable_if_t::value, T> ReadArg(Program &P,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();

tbaeder wrote:
> erichkeane wrote:
> > Are you sure this isn't intentional that this is passed by value?  With a 
> > name like CodePtr, it certainly SOUNDS like it means to be passed by value.
> `CodePtr::read()` advances the pointer that `CodePtr` wraps , so copying just 
> to call `read()` on it makes little sense. E.g. in 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Interp/Interp.cpp#L401-L412,
>  `ReadArg` must advance the `CodePtr`, otherwise two consecutive `ReadArg` 
> calls will read the same thing.
my point is; With a struct this small, the 'copy' is cheaper than a 
pass-by-ref.  However, if the pass-by-value causes the ReadArg to read the same 
thing, why was this not a problem before?  More importantly, what in this patch 
makes this change necessary?  



Comment at: clang/test/AST/Interp/literals.cpp:14
+constexpr bool getTrue() { return true; }
+constexpr bool getFalse() { return false; }

tbaeder wrote:
> erichkeane wrote:
> > can you also do a 'getNullptr'?  Also, a static-assert for all 3 of the 
> > functions as well.
> I can do a `getNull()`, but I can't call any of the functions yet, function 
> calls aren't implemented yet.
ah, thanks for that clarificaiton. When doing the function-calls, please see if 
you can add that here as well.


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

https://reviews.llvm.org/D131942

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


[PATCH] D131926: [clang-tidy] Fix for bugprone-sizeof-expression PR57167

2022-08-17 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx updated this revision to Diff 453286.
chrish_ericsson_atx added a comment.

Corrected git-clang-format issue.


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

https://reviews.llvm.org/D131926

Files:
  clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-2.c
  clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
@@ -232,10 +232,8 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
   sum += sizeof(&S);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
-  sum += sizeof(MyStruct*);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
-  sum += sizeof(PMyStruct);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(MyStruct*);  // FIXME: Warning here prior to 15f3cd6bfc6, 
consider whether to add it back.
+  sum += sizeof(PMyStruct);  // FIXME: Warning here prior to 15f3cd6bfc6, 
consider whether to add it back.
   sum += sizeof(PS);
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
   sum += sizeof(PS2);
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-2.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-2.c
@@ -0,0 +1,62 @@
+// RUN: %check_clang_tidy %s bugprone-sizeof-expression %t -- --
+// RUN: %check_clang_tidy %s bugprone-sizeof-expression %t -- -- -x c++
+
+#ifdef __cplusplus
+#define STRKWD
+#else
+#define STRKWD struct
+#endif
+
+int Test5() {
+  typedef int Array10[10];
+
+  struct MyStruct {
+Array10 arr;
+Array10* ptr;
+  };
+
+  typedef struct TypedefStruct {
+Array10 arr;
+Array10* ptr;
+  } TypedefStruct;
+
+  typedef const STRKWD MyStruct TMyStruct;
+  typedef const STRKWD MyStruct *PMyStruct;
+  typedef TMyStruct *PMyStruct2;
+  typedef const TypedefStruct *PTTStruct;
+
+  STRKWD MyStruct S;
+  TypedefStruct TS;
+  PMyStruct PS;
+  PMyStruct2 PS2;
+  Array10 A10;
+  PTTStruct PTTS;
+
+  int sum = 0;
+  sum += sizeof(&S);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(__typeof(&S));
+  sum += sizeof(&TS);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(__typeof(&TS));
+  sum += sizeof(STRKWD MyStruct*);
+  sum += sizeof(__typeof(STRKWD MyStruct*));
+  sum += sizeof(TypedefStruct*);
+  sum += sizeof(__typeof(TypedefStruct*));
+  sum += sizeof(PTTS);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(PMyStruct);
+  sum += sizeof(PS);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(PS2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(&A10);
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+
+#ifdef __cplusplus
+  MyStruct &rS = S;
+  sum += sizeof(rS); // same as sizeof(S), not a pointer.  So should not warn.
+#endif
+
+  return sum;
+}
Index: clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -147,8 +147,8 @@
   const auto StructAddrOfExpr = unaryOperator(
   hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
 hasType(hasCanonicalType(recordType());
-  const auto PointerToStructType = hasUnqualifiedDesugaredType(
-  pointerType(pointee(hasCanonicalType(recordType();
+  const auto PointerToStructType =
+  hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
   const auto PointerToStructExpr = ignoringParenImpCasts(expr(
   hasType(hasCanonicalType(PointerToStructType)), unless(cxxThisExpr(;
 


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp
@@ -232,10 +232,8 @@
   // C

[PATCH] D132031: Do not evaluate dependent immediate invocations

2022-08-17 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 created this revision.
Herald added a project: All.
usaxena95 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We deferred the evaluation of dependent immediate invocations in 
https://reviews.llvm.org/D119375.
We should also not consider them referenced from a non-consteval
context.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132031

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -649,6 +649,21 @@
 static_assert(bar<15>() == 15);
 static_assert(baz() == sizeof(int));
 
+
+namespace issue_55601 {
+template
+class Bar {
+  // Dependent immmediate expressions should be evaluated at instantiation. 
+  consteval static T x() { return 5; }
+ public:
+  Bar() : a(x()) {}
+
+ private:
+  int a;
+};
+Bar f;
+Bar g;
+} // namespace issue_55601
 } // namespace value_dependent
 
 namespace default_argument {
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19673,10 +19673,10 @@
 if (Method->isVirtual() &&
 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
   OdrUse = false;
-
   if (auto *FD = dyn_cast(E->getDecl()))
 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
-FD->isConsteval() && !RebuildingImmediateInvocation)
+FD->isConsteval() && !RebuildingImmediateInvocation &&
+!FD->isDependentContext())
   ExprEvalContexts.back().ReferenceToConsteval.insert(E);
   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
  RefsMinusAssignments);


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -649,6 +649,21 @@
 static_assert(bar<15>() == 15);
 static_assert(baz() == sizeof(int));
 
+
+namespace issue_55601 {
+template
+class Bar {
+  // Dependent immmediate expressions should be evaluated at instantiation. 
+  consteval static T x() { return 5; }
+ public:
+  Bar() : a(x()) {}
+
+ private:
+  int a;
+};
+Bar f;
+Bar g;
+} // namespace issue_55601
 } // namespace value_dependent
 
 namespace default_argument {
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19673,10 +19673,10 @@
 if (Method->isVirtual() &&
 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
   OdrUse = false;
-
   if (auto *FD = dyn_cast(E->getDecl()))
 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
-FD->isConsteval() && !RebuildingImmediateInvocation)
+FD->isConsteval() && !RebuildingImmediateInvocation &&
+!FD->isDependentContext())
   ExprEvalContexts.back().ReferenceToConsteval.insert(E);
   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
  RefsMinusAssignments);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131469: [Clang] change default storing path of `-ftime-trace`

2022-08-17 Thread Jamie Schmeiser via Phabricator via cfe-commits
jamieschmeiser added a comment.

Good progress.




Comment at: clang/lib/Driver/Driver.cpp:97
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 

This include isn't necessary.  There are asserts already in the file so this is 
transitively included.



Comment at: clang/lib/Driver/Driver.cpp:4668
+  // if `-ftime-trace` or `-ftime-trace=` are specified
+  if (TimeTrace || TimeTraceFile) {
+SmallString<128> TracePath("");

I think the quick return style is generally preferred.  In this case, test the 
negative and return.  It is easier to follow and limits indenting.



Comment at: clang/lib/Driver/Driver.cpp:4674
+for (auto &J : C.getJobs()) {
+  if (J.getSource().getKind() == Action::LinkJobClass &&
+  !J.getOutputFilenames().empty()) {

Can you have a link job without an output filename?  If not, then just have an 
assert for !empty.  Again, the negative test and continue might be easier to 
understand.



Comment at: clang/lib/Driver/Driver.cpp:4679
+  TracePath = llvm::sys::path::parent_path(
+  SmallString<128>(J.getOutputFilenames()[0].c_str()));
+} else {

you create the same small string twice.  better to create a temporary.



Comment at: clang/lib/Driver/Driver.cpp:4689
+  if (J.getSource().getKind() == Action::AssembleJobClass ||
+  J.getSource().getKind() == Action::BackendJobClass) {
+SmallString<128> OutputPath(J.getOutputFilenames()[0].c_str());

Again, test negative with continue
Do you also want CompileJobClass?



Comment at: clang/lib/Driver/Driver.cpp:4700
+llvm::sys::path::append(TracePath,
+llvm::sys::path::filename(OutputPath));
+llvm::sys::path::replace_extension(TracePath, "json");

You are changing TracePath, which will then be altered when you loop back.  I 
think you need to use a copy of TracePath.



Comment at: clang/lib/Driver/Driver.cpp:4714
+}
+
+assert(arg.size() > strlen("-ftime-trace") &&

Can you compute the full path to the directory before the loop and then just 
copy it and add the name in the loop for each file?



Comment at: clang/lib/Driver/Driver.cpp:4725
+auto &JArgs = J.getArguments();
+bool exist = false;
+for (unsigned I = 0; I < JArgs.size(); ++I) {

Variables should start with an uppercase letter


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131469

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


[PATCH] D131547: [Clang][AArch64] Use generic extract/insert vector for svget/svset/svcreate tuples

2022-08-17 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

In D131547#3723083 , @dmgreen wrote:

> I think we usually try to do the same, if the intrinsics have been in 
> released compilers. There is an example in 
> https://reviews.llvm.org/D98487#change-tOTTgECYYAO5, hopefully these would be 
> equally simple.

We don't really have the intention in keeping compatibility for intrinsics like 
these, since the vector.extract/insert intrinsics are the proper way to 
insert/extract vectors and they have been around for quite some time now. Also 
these intrinsics are quite specific to the initial SVE ACLE implementation when 
we first upstreamed it, so it's not very likely that anyone else is using them.




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:9085-9097
+  auto *VTy = dyn_cast(Ty);
+  unsigned I = cast(Ops[1])->getSExtValue();
+
+ if (TypeFlags.isTupleSet()){
+   auto *SrcTy = dyn_cast(Ops[2]->getType());
+   unsigned MinElts = SrcTy->getElementCount().getKnownMinValue();
+   Value *Idx = ConstantInt::get(CGM.Int64Ty, I * MinElts);

I think you could simplify this further to:

   auto *SingleVecTy = cast(
   TypeFlags.isTupleSet() ? Ops[2]->getType() : Ty);

   unsigned I = cast(Ops[1])->getSExtValue();
   Value *Idx =
   ConstantInt::get(CGM.Int64Ty, I * SingleVecTy->getMinNumElements());
  
   if (TypeFlags.isTupleSet())
 return Builder.CreateExtractVector(Ty, Ops[0], Ops[2], Idx);
   else
 return Builder.CreateInsertVector(Ty, Ops[0], Idx);




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:9106
+
+  auto *VTy = dyn_cast(Ty);
+  auto *SrcTy = dyn_cast(Ops[0]->getType());

Casting to `VectorType` here isn't actually necessary, because both 
`llvm::PoisonValue::get()` and `Builder.CreateInsertVector()` take a `Type*`.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:9107
+  auto *VTy = dyn_cast(Ty);
+  auto *SrcTy = dyn_cast(Ops[0]->getType());
+  unsigned MinElts = SrcTy->getElementCount().getKnownMinValue();

nit: If you cast this to `llvm::ScalableVectorType` you can call 
`SrcTy->getMinNumElements()` directly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131547

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


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

2022-08-17 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin abandoned this revision.
cor3ntin added a comment.

No longer pursuing that as llvm 14 seems EOL


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] D131547: [Clang][AArch64] Use generic extract/insert vector for svget/svset/svcreate tuples

2022-08-17 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

In D131547#3728842 , @sdesmalen wrote:

> In D131547#3723083 , @dmgreen wrote:
>
>> I think we usually try to do the same, if the intrinsics have been in 
>> released compilers. There is an example in 
>> https://reviews.llvm.org/D98487#change-tOTTgECYYAO5, hopefully these would 
>> be equally simple.
>
> We don't really have the intention in keeping compatibility for intrinsics 
> like these, since the vector.extract/insert intrinsics are the proper way to 
> insert/extract vectors and they have been around for quite some time now. 
> Also these intrinsics are quite specific to the initial SVE ACLE 
> implementation when we first upstreamed it, so it's not very likely that 
> anyone else is using them.

I'm not sure what you mean by "keeping compatibility", they just need to be 
replaced in the autoupdate code. If there was a release of llvm which emitted 
the intrinsics, then the default assumption is that someone might have bitcode 
that uses them. Luckily it is really simple to add the autoupgrade code in most 
cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131547

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


[PATCH] D131780: [clang-tidy] Do not trigger cppcoreguidelines-avoid-const-or-ref-data-members on lambda captures

2022-08-17 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp:191
+  auto r5 = [&x5]{};
+}

njames93 wrote:
> Can you add some cases with implicit capture (using [=] and [&])
I should have been more clear, you need to actually use the variables inside 
the lambda to implicitly capture them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

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


[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder marked 3 inline comments as done.
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Disasm.cpp:26
 inline std::enable_if_t::value, T> ReadArg(Program &P,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();

erichkeane wrote:
> tbaeder wrote:
> > erichkeane wrote:
> > > Are you sure this isn't intentional that this is passed by value?  With a 
> > > name like CodePtr, it certainly SOUNDS like it means to be passed by 
> > > value.
> > `CodePtr::read()` advances the pointer that `CodePtr` wraps , so copying 
> > just to call `read()` on it makes little sense. E.g. in 
> > https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Interp/Interp.cpp#L401-L412,
> >  `ReadArg` must advance the `CodePtr`, otherwise two consecutive `ReadArg` 
> > calls will read the same thing.
> my point is; With a struct this small, the 'copy' is cheaper than a 
> pass-by-ref.  However, if the pass-by-value causes the ReadArg to read the 
> same thing, why was this not a problem before?  More importantly, what in 
> this patch makes this change necessary?  
Nothing in this patch, if you e.g. take this code:
```
constexpr int func() { return 5; }
```
and run it with `clang++ -std=c++20 -fexperimental-new-constant-interpreter`, 
the constant interpreter runs into an assertion while evaluating the bytecode 
for that function. Switching `ReadArg` to take the codeptr by reference fixes 
that. So I could probably postpone the change to a later patch but it's one of 
the first problems I ran into while working on the codebase.


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

https://reviews.llvm.org/D131942

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


[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/AST/Interp/Disasm.cpp:26
 inline std::enable_if_t::value, T> ReadArg(Program &P,
-   CodePtr OpPC) {
+   CodePtr &OpPC) {
   return OpPC.read();

tbaeder wrote:
> erichkeane wrote:
> > tbaeder wrote:
> > > erichkeane wrote:
> > > > Are you sure this isn't intentional that this is passed by value?  With 
> > > > a name like CodePtr, it certainly SOUNDS like it means to be passed by 
> > > > value.
> > > `CodePtr::read()` advances the pointer that `CodePtr` wraps , so copying 
> > > just to call `read()` on it makes little sense. E.g. in 
> > > https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/Interp/Interp.cpp#L401-L412,
> > >  `ReadArg` must advance the `CodePtr`, otherwise two consecutive 
> > > `ReadArg` calls will read the same thing.
> > my point is; With a struct this small, the 'copy' is cheaper than a 
> > pass-by-ref.  However, if the pass-by-value causes the ReadArg to read the 
> > same thing, why was this not a problem before?  More importantly, what in 
> > this patch makes this change necessary?  
> Nothing in this patch, if you e.g. take this code:
> ```
> constexpr int func() { return 5; }
> ```
> and run it with `clang++ -std=c++20 -fexperimental-new-constant-interpreter`, 
> the constant interpreter runs into an assertion while evaluating the bytecode 
> for that function. Switching `ReadArg` to take the codeptr by reference fixes 
> that. So I could probably postpone the change to a later patch but it's one 
> of the first problems I ran into while working on the codebase.
I see, thanks for the explanation.  I think it is fine now, it just wasn't 
clear that this was covered by a test or necessary.


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

https://reviews.llvm.org/D131942

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


[clang] 74b5dad - Add N2653 to the C2x status page

2022-08-17 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-08-17T11:30:31-04:00
New Revision: 74b5dad5e944db21e56e6d81eb14f11891a741ab

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

LOG: Add N2653 to the C2x status page

This was accidentally missing from the Feb 2022 paper section.

Added: 


Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 8d4dbe2612749..bae3ed5d4195b 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -1055,6 +1055,11 @@ C2x implementation status
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2879.pdf";>N2879
   Yes
 
+
+  char8_t: A type for UTF-8 characters and strings
+  https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2653.htm";>N2653
+  No
+
 
   Clarification for max exponent macros-update
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2882.pdf";>N2882



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


[PATCH] D132030: [analyzer] Pass correct bldrCtx to computeObjectUnderConstruction

2022-08-17 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource created this revision.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
tomasz-kaminski-sonarsource added a reviewer: xazax.hun.
Herald added a subscriber: rnkovacs.
tomasz-kaminski-sonarsource edited the summary of this revision.
tomasz-kaminski-sonarsource updated this revision to Diff 453294.
tomasz-kaminski-sonarsource added a comment.
tomasz-kaminski-sonarsource published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixed warrning checks and added newline.


tomasz-kaminski-sonarsource added a comment.

This is now ready for review.


In case when the prvalue is returned from the function (kind is one
of `SimpleReturnedValueKind`, `CXX17ElidedCopyReturnedValueKind`),
then it construction happens in context of the caller.
We pass `BldrCtx` explicitly, as `currBldrCtx` will always refer to callee
context.

In the following example:

  `
  struct Result {int value; };
  Result create() { return Result{10}; }
  int accessValue(Result r) { return r.value; }
  
  void test() {
 for (int i = 0; i < 2; ++i)
accessValue(create());
  }

In case when the returned object was constructed directly into the
argument to a function call `accessValue(create())`, this led to
inappropriate value of `blockCount` being used to locate parameter region,
and as a consequence resulting object (from `create()`) was constructed
into a different region, that was later read by inlined invocation of
outer function (`accessValue`).
This manifests itself only in case when calling block is visited more
than once (loop in above example), as otherwise there is no in `blockCount`
value between callee and caller context.
This happens only in case when copy elision is disabled (before C++17).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132030

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/test/Analysis/copy-elision.cpp

Index: clang/test/Analysis/copy-elision.cpp
===
--- clang/test/Analysis/copy-elision.cpp
+++ clang/test/Analysis/copy-elision.cpp
@@ -20,6 +20,7 @@
 #endif
 
 void clang_analyzer_eval(bool);
+void clang_analyzer_dump(int);
 
 namespace variable_functional_cast_crash {
 
@@ -418,3 +419,31 @@
 }
 
 } // namespace address_vector_tests
+
+namespace arg_directly_from_return_in_loop {
+
+struct Result {
+  int value;
+};
+
+Result create() {
+  return Result{10};
+}
+
+int accessValue(Result r) {
+  return r.value;
+}
+
+void test() {
+  for (int i = 0; i < 3; ++i) {
+int v = accessValue(create());
+if (i == 0) {
+  clang_analyzer_dump(v); // expected-warning {{10 S32b}}
+} else {
+  clang_analyzer_dump(v); // expected-warning {{10 S32b}}
+  // was {{reg_${{[0-9]+}} }} for C++11
+}
+  }
+}
+
+} // namespace arg_directly_from_return_in_loop
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -111,9 +111,15 @@
   return LValue;
 }
 
+// In case when the prvalue is returned from the function (kind is one of
+// SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then
+// it's materialization happens in context of the caller.
+// We pass BldrCtx explicitly, as currBldrCtx always refers to callee's context.
 SVal ExprEngine::computeObjectUnderConstruction(
-const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
-const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx) {
+const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx,
+const LocationContext *LCtx, const ConstructionContext *CC,
+EvalCallOptions &CallOpts, unsigned Idx) {
+
   SValBuilder &SVB = getSValBuilder();
   MemRegionManager &MRMgr = SVB.getRegionManager();
   ASTContext &ACtx = SVB.getContext();
@@ -209,8 +215,11 @@
   CallerLCtx = CallerLCtx->getParent();
   assert(!isa(CallerLCtx));
 }
+
+NodeBuilderContext CallerBldrCtx(getCoreEngine(),
+ SFC->getCallSiteBlock(), CallerLCtx);
 return computeObjectUnderConstruction(
-cast(SFC->getCallSite()), State, CallerLCtx,
+cast(SFC->getCallSite()), State, &CallerBldrCtx, CallerLCtx,
 RTC->getConstructionContext(), CallOpts);
   } else {
 // We are on the top frame of the analysis. We do not know where is the
@@ -250,7 +259,7 @@
   EvalCallOptions PreEli

[PATCH] D131926: [clang-tidy] Fix for bugprone-sizeof-expression PR57167

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-2.c:42
+  sum += sizeof(__typeof(&TS));
+  sum += sizeof(STRKWD MyStruct*);
+  sum += sizeof(__typeof(STRKWD MyStruct*));

Based on the documentation, I would expect this one to be diagnosed.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp:236-238
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
   sum += sizeof(PMyStruct);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate

mizvekov wrote:
> chrish_ericsson_atx wrote:
> > mizvekov wrote:
> > > chrish_ericsson_atx wrote:
> > > > njames93 wrote:
> > > > > mizvekov wrote:
> > > > > > Is this change really desirable, or should we put a FIXME here?
> > > > > Not warning on these cases seems like a pretty big red flag, 
> > > > > especially the `MyStruct *`.
> > > > Thank you for your comment!  I'm not sure I fully agree that this is a 
> > > > red flag.  I'm inclined to think that whether or not there should be a 
> > > > warning on `MyStruct *` or `PMyStruct` is a pretty subjective.  These 
> > > > are both very common idioms, and are meaningful.  I do appreciate the 
> > > > perspective that `MyStruct *` is just one character different from 
> > > > `MyStruct`, and as such, it might be a typo to ask for sizeof the 
> > > > pointer, when you really wanted sizeof the struct.  But the 
> > > > counter-argument (accidentally asking for sizeof the struct when you 
> > > > really wanted the pointer size) is just as valid-- and the checker 
> > > > obviously cannot warn in that case.   
> > > > 
> > > > I am perfectly fine with kicking the can down the road a bit by 
> > > > replacing the discarded `// CHECK-MESSAGES` directive with a `// 
> > > > FIXME`, as @mizvekov suggested.  I expect that when someone circles 
> > > > back to really deeply reconsider the semantics of this checker, there 
> > > > will be a number of changes (other existing warnings dropped, warnings 
> > > > for new and missed cases added, much better sync between C and C++, as 
> > > > well as intentional consideration of things like __typeof__ (in it's 
> > > > various forms) and decltype, rather than the haphazard coarse-grain 
> > > > matching that seems to be going on now.
> > > I agree with this patch only in so far that:
> > > 
> > > * This is effectively a partial revert of the changes made in 
> > > https://reviews.llvm.org/rG15f3cd6bfc670ba6106184a903eb04be059e5977
> > > * The checker was pretty much buggy to begin with.
> > > * That change significantly increased the amount of patterns we would 
> > > accept, but at the same time the existing tests did not pick that up and 
> > > this was not carefully considered.
> > > * It seems unreasonable that there is effectively no way to shut this 
> > > warning up per site, except by a NOLINT directive.
> > > 
> > > If the amount of false positives is so high now that this check is 
> > > unusable, then this is just a question of reverting to a less broken 
> > > state temporarily.
> > > 
> > > But otherwise we can't leave it in the reverted state either. Without 
> > > that change to use the canonical type or something similar, there is no 
> > > reason to suppose any of these test cases would work at all as clang 
> > > evolves and we improve the quality of implementation wrt type sugar 
> > > retention.
> > @mizvekov, I agree with your reasoning for saying "we can't leave it in the 
> > reverted state either".  But I'm not sure how to ensure that this gets the 
> > needed attention.  Should we just file a separate PR on github to track the 
> > needed refactoring?  I do not believe I'll have the bandwidth to look at 
> > this in the next few months.
> > 
> > In the meantime, assuming the bots are happy with patchset 2, I'll land 
> > this as-is later today.
> > 
> > Thank you very much for your feedback!
> Oh please wait for others to review, I don't think landing today is 
> reasonable!
> 
> I am not really a stakeholder for this checker except for that original 
> change.
> 
> I would advise for you to wait for another more responsible reviewer to 
> accept as well before merging, unless this gets stale for a long time and no 
> one else seems to be interested.
> Thank you for your comment! I'm not sure I fully agree that this is a red 
> flag. I'm inclined to think that whether or not there should be a warning on 
> MyStruct * or PMyStruct is a pretty subjective. These are both very common 
> idioms, and are meaningful. I do appreciate the perspective that MyStruct * 
> is just one character different from MyStruct, and as such, it might be a 
> typo to ask for sizeof the pointer, when you really wanted sizeof the struct. 
> But the counter-argument (accidentally asking for sizeof the struct when you 
> r

[PATCH] D132017: [clang][analyzer] Add errno modeling to StreamChecker

2022-08-17 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 453297.
balazske added a comment.

StdLibraryFunctionsChecker should not overwrite errno constraints
that are set by StreamChecker.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132017

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-errno.c

Index: clang/test/Analysis/stream-errno.c
===
--- /dev/null
+++ clang/test/Analysis/stream-errno.c
@@ -0,0 +1,196 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,debug.ExprInspection -analyzer-output text -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,apiModeling.StdCLibraryFunctions,debug.ExprInspection -analyzer-output text -verify %s
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_func.h"
+
+extern void clang_analyzer_eval(int);
+extern void clang_analyzer_dump(int);
+
+void check_fopen(void) {
+  FILE *F = fopen("xxx", "r");
+  // expected-note@-1{{Assuming that function 'fopen' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_tmpfile(void) {
+  FILE *F = tmpfile();
+  // expected-note@-1{{Assuming that function 'tmpfile' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_freopen(void) {
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  F = freopen("xxx", "w", F);
+  // expected-note@-1{{Assuming that function 'freopen' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+4{{'F' is null}}
+  // expected-note@+3{{Taking true branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_fclose(void) {
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  int Ret = fclose(F);
+  // expected-note@-1{{Assuming that function 'fclose' is successful, in this case the value 'errno' may be undefined after the call and should not be used}}
+  // expected-note@+2{{Taking true branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (Ret == EOF) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}} expected-note{{TRUE}}
+if (errno) {}
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno' [alpha.unix.Errno]}}
+  // expected-note@-1{{An undefined value may be read from 'errno'}}
+}
+
+void check_fread(void) {
+  char Buf[10];
+  FILE *F = tmpfile();
+  // expected-note@+4{{'F' is non-null}}
+  // expected-note@+3{{Taking false branch}}
+  // expected-note@+2{{'F' is non-null}}
+  // expected-note@+1{{Taking false branch}}
+  if (!F)
+return;
+  fread(Buf, 0, 1, F);
+  // expected-note@+2{{Taking false branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (errno) {} // no-warning
+  fread(Buf, 1, 0, F);
+  // expected-note@+2{{Taking false branch}}
+  // expected-note@+1{{Taking false branch}}
+  if (errno) {} // no-warning
+
+  int R = fread(Buf, 1, 10, F);
+  // expected-note@-1{{function 'fread' is successful}}
+

[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM as well; should we add a release note for this? I suspect not because it's 
improving an experimental feature that's not really ready for prime time yet, 
but I don't know how others feel.


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

https://reviews.llvm.org/D131942

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


[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D131942#3728974 , @aaron.ballman 
wrote:

> LGTM as well; should we add a release note for this? I suspect not because 
> it's improving an experimental feature that's not really ready for prime time 
> yet, but I don't know how others feel.

That was my thought on it, though thinking further, I wonder if there is value 
to it to show 'signs of life' in the release notes?


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

https://reviews.llvm.org/D131942

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


[PATCH] D131683: Diagnosing the Future Keywords

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI is failing with a failure that looks like it's relevant:

   TEST 'Clang :: Parser/static_assert.c' FAILED 

  Script:
  --
  : 'RUN: at line 1';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c2x -DTEST_SPELLING -verify=c2x 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 2';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c2x -DTEST_SPELLING -fms-compatibility 
-verify=c2x-ms 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 3';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c2x -Wpre-c2x-compat -verify=c2x-compat 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 4';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c99 -verify=c99 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 5';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c99 -pedantic -verify=c99-pedantic 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 6';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c++17 -verify=cxx17 -x c++ 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 7';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c++17 -pedantic -verify=cxx17-pedantic -x 
c++ C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 8';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c++98 -verify=cxx98 -x c++ 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 9';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c++98 -pedantic -verify=cxx98-pedantic -x 
c++ C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  : 'RUN: at line 10';   
c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include 
-nostdsysteminc -fsyntax-only -std=c++17 -Wpre-c++17-compat 
-verify=cxx17-compat -x c++ 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c
  --
  Exit Code: 1
  
  Command Output (stdout):
  --
  $ ":" "RUN: at line 1"
  $ "c:\ws\w9\llvm-project\premerge-checks\build\bin\clang.exe" "-cc1" 
"-internal-isystem" 
"c:\ws\w9\llvm-project\premerge-checks\build\lib\clang\16.0.0\include" 
"-nostdsysteminc" "-fsyntax-only" "-std=c2x" "-DTEST_SPELLING" "-verify=c2x" 
"C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c"
  # command stderr:
  error: 'error' diagnostics expected but not seen: 
File 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c Line 
18: expected parameter declarator
File 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c Line 
18: expected ')'
File 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c Line 
18: a type specifier is required for all declarations
  error: 'warning' diagnostics seen but not expected: 
File 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c Line 
18: use of 'static_assert' without inclusion of  is a Microsoft 
extension
  error: 'note' diagnostics expected but not seen: 
File 
C:\ws\w9\llvm-project\premerge-checks\clang\test\Parser\static_assert.c Line 
18: to match this '('
  5 errors generated.
  
  error: command failed with exit status: 1
  
  --
  
  

I think this is coming from the fact that you're marking a bunch of keywords as 
being C2x keywords. That's correct insomuch as they are C2x keywords. But it's 
incorrect because we haven't actually implemented those features ye

[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D131942#3728994 , @erichkeane 
wrote:

> In D131942#3728974 , @aaron.ballman 
> wrote:
>
>> LGTM as well; should we add a release note for this? I suspect not because 
>> it's improving an experimental feature that's not really ready for prime 
>> time yet, but I don't know how others feel.
>
> That was my thought on it, though thinking further, I wonder if there is 
> value to it to show 'signs of life' in the release notes?

@tbaeder -- do you have plans to continue to add support to the experimental 
constant expression evaluator?

If this is code that we have people actively working on with plans to bring it 
to completion, then I think showing signs of life in the release notes is a 
good idea. If we don't have anyone who is planning to bring this through to 
completion, I think we should seriously considering pulling it out of the tree 
rather than trying to maintain parallel constant expression evaluators. (We 
wouldn't be pulling it out of the tree because we don't like the design, so if 
someone wanted to resurrect it in the future because they planned to complete 
it, we'd gladly welcome it.)


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

https://reviews.llvm.org/D131942

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


[PATCH] D131685: [clang][AST] RecursiveASTVisitor should visit owned TagDecl of friend type.

2022-08-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

This looks like a reasonable representation of such record decls to me.

Changing the AST to nest them under typelocs instead is indeed a bigger project 
(and it's hard to say whether it's a good idea without a lot of digging).




Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:1577-1578
 DEF_TRAVERSE_DECL(FriendTemplateDecl, {
+  // FIXME: Traverse getOwnedTagDecl like at the FriendDecl case?
+  // (FriendTemplateDecl is not used)
   if (D->getFriendType())

davrec wrote:
> I don't think anything is necessary here, because we should never see an 
> `OwnedTagDecl` here.
> In the FriendDecl case the ElaboratedType only has an OwnedTagDecl when 
> `struct Fr` has not yet been declared before the friend decl.
> In the documentation of FriendTemplateDecl on the other hand these examples 
> are given:
> ```
> /// template \ class A {
> ///   friend class MyVector; // not a friend template
> ///   template \ friend class B; // not a friend template
> ///   template \ friend class Foo::Nested; // friend template
> /// };
> ```
> So, a FriendTemplateDecl is only created when referencing a nested class 
> template member.  But that *must* have been declared before the friend decl, 
> or we will get an error:
> 
> ```
> template struct B;
> template struct A { template friend struct B::Fr; 
> }; //ERROR: no member named 'Fr' in B
> ```
> 
> So the OwnedTagDecl should always be nullptr here/the issue should never 
> arise in this case.
> 
That sounds plausible to me, FriendTemplateDecl is extremely obscure and 
possibly badly designed.
I'd probably err on the side of not adding a FIXME unless we're sure something 
needs to be done, as I doubt anyone will ever remove it.



Comment at: clang/unittests/AST/ASTContextParentMapTest.cpp:145
+  EXPECT_THAT(Ctx.getParents(FrBLoc), ElementsAre(DynTypedNode::create(FrB)));
+  if (FrATagDecl)
+EXPECT_THAT(Ctx.getParents(*FrATagDecl),

I'm confused why this is conditional: isn't this the main thing that we're 
testing? Why do we want the test to silently pass if the AST structure changes 
so that ownedTagDecl is null? It's hard to tell from reading the code if 
anything is being tested at all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131685

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


[PATCH] D132031: Do not evaluate dependent immediate invocations

2022-08-17 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.

Thank you, this LGTM, though I did have a testing question. Also, please be 
sure to add a release note for the fix.




Comment at: clang/test/SemaCXX/cxx2a-consteval.cpp:665
+Bar f;
+Bar g;
+} // namespace issue_55601

Do you think it's worth it to add a test case like:
```
struct derp {
  derp(int); // Can't be used in a constant expression

  consteval operator int() const { return 5; }
};

Bar d; // Error
```
to demonstrate that we evaluated properly at instantiation time, or do you 
think existing coverage already demonstrates this well enough?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132031

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


[PATCH] D131547: [Clang][AArch64] Use generic extract/insert vector for svget/svset/svcreate tuples

2022-08-17 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

In D131547#3728867 , @dmgreen wrote:

> In D131547#3728842 , @sdesmalen 
> wrote:
>
>> In D131547#3723083 , @dmgreen 
>> wrote:
>>
>>> I think we usually try to do the same, if the intrinsics have been in 
>>> released compilers. There is an example in 
>>> https://reviews.llvm.org/D98487#change-tOTTgECYYAO5, hopefully these would 
>>> be equally simple.
>>
>> We don't really have the intention in keeping compatibility for intrinsics 
>> like these, since the vector.extract/insert intrinsics are the proper way to 
>> insert/extract vectors and they have been around for quite some time now. 
>> Also these intrinsics are quite specific to the initial SVE ACLE 
>> implementation when we first upstreamed it, so it's not very likely that 
>> anyone else is using them.
>
> I'm not sure what you mean by "keeping compatibility", they just need to be 
> replaced in the autoupdate code. If there was a release of llvm which emitted 
> the intrinsics, then the default assumption is that someone might have 
> bitcode that uses them.

What I meant with 'keeping compatibility' is exactly what you described; 
bitcode/IR that uses the old intrinsics remaining to work with newer versions 
of LLVM.

My point was that these intrinsics have not been in LLVM for that long and have 
a very limited scope, so are unlikely to have accrued much legacy. I don't 
really expect a practical use-case where people have legacy SVE ACLE bitcode 
that they need to compile with a newer version of LLVM. So unless someone 
explicitly requests the compatibility, we'd rather remove them in favour of 
adding code that will never be used.

Is there a formal requirement that LLVM must remain backward compatible with 
older LLVM IR (beyond the target-independent parts)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131547

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


[PATCH] D131555: [Clang] Propagate const context info when emitting compound literal

2022-08-17 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

This seems reasonable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131555

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


[PATCH] D131926: [clang-tidy] Fix for bugprone-sizeof-expression PR57167

2022-08-17 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp:236-238
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
   sum += sizeof(PMyStruct);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate

aaron.ballman wrote:
> mizvekov wrote:
> > chrish_ericsson_atx wrote:
> > > mizvekov wrote:
> > > > chrish_ericsson_atx wrote:
> > > > > njames93 wrote:
> > > > > > mizvekov wrote:
> > > > > > > Is this change really desirable, or should we put a FIXME here?
> > > > > > Not warning on these cases seems like a pretty big red flag, 
> > > > > > especially the `MyStruct *`.
> > > > > Thank you for your comment!  I'm not sure I fully agree that this is 
> > > > > a red flag.  I'm inclined to think that whether or not there should 
> > > > > be a warning on `MyStruct *` or `PMyStruct` is a pretty subjective.  
> > > > > These are both very common idioms, and are meaningful.  I do 
> > > > > appreciate the perspective that `MyStruct *` is just one character 
> > > > > different from `MyStruct`, and as such, it might be a typo to ask for 
> > > > > sizeof the pointer, when you really wanted sizeof the struct.  But 
> > > > > the counter-argument (accidentally asking for sizeof the struct when 
> > > > > you really wanted the pointer size) is just as valid-- and the 
> > > > > checker obviously cannot warn in that case.   
> > > > > 
> > > > > I am perfectly fine with kicking the can down the road a bit by 
> > > > > replacing the discarded `// CHECK-MESSAGES` directive with a `// 
> > > > > FIXME`, as @mizvekov suggested.  I expect that when someone circles 
> > > > > back to really deeply reconsider the semantics of this checker, there 
> > > > > will be a number of changes (other existing warnings dropped, 
> > > > > warnings for new and missed cases added, much better sync between C 
> > > > > and C++, as well as intentional consideration of things like 
> > > > > __typeof__ (in it's various forms) and decltype, rather than the 
> > > > > haphazard coarse-grain matching that seems to be going on now.
> > > > I agree with this patch only in so far that:
> > > > 
> > > > * This is effectively a partial revert of the changes made in 
> > > > https://reviews.llvm.org/rG15f3cd6bfc670ba6106184a903eb04be059e5977
> > > > * The checker was pretty much buggy to begin with.
> > > > * That change significantly increased the amount of patterns we would 
> > > > accept, but at the same time the existing tests did not pick that up 
> > > > and this was not carefully considered.
> > > > * It seems unreasonable that there is effectively no way to shut this 
> > > > warning up per site, except by a NOLINT directive.
> > > > 
> > > > If the amount of false positives is so high now that this check is 
> > > > unusable, then this is just a question of reverting to a less broken 
> > > > state temporarily.
> > > > 
> > > > But otherwise we can't leave it in the reverted state either. Without 
> > > > that change to use the canonical type or something similar, there is no 
> > > > reason to suppose any of these test cases would work at all as clang 
> > > > evolves and we improve the quality of implementation wrt type sugar 
> > > > retention.
> > > @mizvekov, I agree with your reasoning for saying "we can't leave it in 
> > > the reverted state either".  But I'm not sure how to ensure that this 
> > > gets the needed attention.  Should we just file a separate PR on github 
> > > to track the needed refactoring?  I do not believe I'll have the 
> > > bandwidth to look at this in the next few months.
> > > 
> > > In the meantime, assuming the bots are happy with patchset 2, I'll land 
> > > this as-is later today.
> > > 
> > > Thank you very much for your feedback!
> > Oh please wait for others to review, I don't think landing today is 
> > reasonable!
> > 
> > I am not really a stakeholder for this checker except for that original 
> > change.
> > 
> > I would advise for you to wait for another more responsible reviewer to 
> > accept as well before merging, unless this gets stale for a long time and 
> > no one else seems to be interested.
> > Thank you for your comment! I'm not sure I fully agree that this is a red 
> > flag. I'm inclined to think that whether or not there should be a warning 
> > on MyStruct * or PMyStruct is a pretty subjective. These are both very 
> > common idioms, and are meaningful. I do appreciate the perspective that 
> > MyStruct * is just one character different from MyStruct, and as such, it 
> > might be a typo to ask for sizeof the pointer, when you really wanted 
> > sizeof the struct. But the counter-argument (accidentally asking for sizeof 
> > the struct when you really wanted the pointer size) is just as valid-- and 
> > the checker obviously cannot warn in that case.
> 
> I agree with @njames93 that th

[PATCH] D130586: [cmake] Use `CMAKE_INSTALL_LIBDIR` too

2022-08-17 Thread John Ericson via Phabricator via cfe-commits
Ericson2314 updated this revision to Diff 453328.
Ericson2314 marked an inline comment as done.
Ericson2314 added a comment.

Rebase, fix outdated comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130586

Files:
  bolt/runtime/CMakeLists.txt
  clang/CMakeLists.txt
  clang/cmake/caches/Android-stage2.cmake
  clang/cmake/caches/Android.cmake
  clang/cmake/modules/AddClang.cmake
  clang/cmake/modules/CMakeLists.txt
  clang/include/clang/Config/config.h.cmake
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  clang/tools/libclang/CMakeLists.txt
  clang/tools/scan-build-py/CMakeLists.txt
  cmake/Modules/GNUInstallPackageDir.cmake
  compiler-rt/cmake/Modules/CompilerRTAIXUtils.cmake
  compiler-rt/cmake/Modules/CompilerRTUtils.cmake
  compiler-rt/cmake/base-config-ix.cmake
  compiler-rt/docs/BuildingCompilerRT.rst
  flang/CMakeLists.txt
  flang/cmake/modules/AddFlang.cmake
  flang/cmake/modules/CMakeLists.txt
  libc/CMakeLists.txt
  libc/lib/CMakeLists.txt
  libcxx/CMakeLists.txt
  libcxx/docs/BuildingLibcxx.rst
  libcxxabi/CMakeLists.txt
  libunwind/CMakeLists.txt
  libunwind/docs/BuildingLibunwind.rst
  lld/CMakeLists.txt
  lld/cmake/modules/AddLLD.cmake
  lld/cmake/modules/CMakeLists.txt
  lldb/cmake/modules/AddLLDB.cmake
  lldb/cmake/modules/LLDBConfig.cmake
  lldb/cmake/modules/LLDBGenerateConfig.cmake
  lldb/cmake/modules/LLDBStandalone.cmake
  lldb/include/lldb/Host/Config.h.cmake
  lldb/source/API/CMakeLists.txt
  lldb/source/Host/linux/HostInfoLinux.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangHost.cpp
  lldb/tools/intel-features/CMakeLists.txt
  lldb/unittests/Expression/ClangParserTest.cpp
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/cmake/modules/AddOCaml.cmake
  llvm/cmake/modules/CMakeLists.txt
  llvm/cmake/modules/LLVMConfig.cmake.in
  llvm/docs/CMake.rst
  llvm/tools/llvm-config/BuildVariables.inc.in
  llvm/tools/llvm-config/llvm-config.cpp
  llvm/tools/llvm-shlib/CMakeLists.txt
  llvm/utils/gn/secondary/clang/include/clang/Config/BUILD.gn
  llvm/utils/gn/secondary/lldb/include/lldb/Host/BUILD.gn
  llvm/utils/gn/secondary/llvm/tools/llvm-config/BUILD.gn
  mlir/CMakeLists.txt
  mlir/cmake/modules/AddMLIR.cmake
  mlir/cmake/modules/AddMLIRPython.cmake
  mlir/cmake/modules/CMakeLists.txt
  mlir/test/CMakeLists.txt
  openmp/CMakeLists.txt
  openmp/README.rst
  polly/cmake/CMakeLists.txt
  polly/cmake/polly_macros.cmake
  polly/test/CMakeLists.txt
  pstl/CMakeLists.txt
  third-party/benchmark/src/CMakeLists.txt
  utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h

Index: utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
===
--- utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
+++ utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h
@@ -67,8 +67,8 @@
 /* Default architecture for SystemZ. */
 #define CLANG_SYSTEMZ_DEFAULT_ARCH "z10"
 
-/* Multilib suffix for libdir. */
-#define CLANG_LIBDIR_SUFFIX ""
+/* Multilib basename for libdir. */
+#define CLANG_INSTALL_LIBDIR_BASENAME "lib"
 
 /* Relative directory for resource files */
 #define CLANG_RESOURCE_DIR ""
Index: third-party/benchmark/src/CMakeLists.txt
===
--- third-party/benchmark/src/CMakeLists.txt
+++ third-party/benchmark/src/CMakeLists.txt
@@ -79,7 +79,7 @@
 configure_package_config_file (
   ${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in
   ${project_config}
-  INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}
+  INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
   NO_SET_AND_CHECK_MACRO
   NO_CHECK_REQUIRED_COMPONENTS_MACRO
 )
@@ -100,8 +100,8 @@
   install(
 TARGETS ${targets_to_export}
 EXPORT ${targets_export_name}
-ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
-LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
+LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
 RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
 INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
 
Index: pstl/CMakeLists.txt
===
--- pstl/CMakeLists.txt
+++ pstl/CMakeLists.txt
@@ -88,10 +88,10 @@
 install(EXPORT ParallelSTLTargets
 FILE ParallelSTLTargets.cmake
 NAMESPACE pstl::
-DESTINATION lib/cmake/ParallelSTL)
+DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/ParallelSTL")
 install(FILES "${CMAKE_CURRENT_BINARY_DIR}/ParallelSTLConfig.cmake"
   "${CMAKE_CURRENT_BINARY_DIR}/ParallelSTLConfigVersion.cmake"
-DESTINATION lib/cmake/ParallelSTL)
+DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/ParallelSTL")
 install(DIRECTORY include/
  

[PATCH] D131255: Fix Wbitfield-constant-conversion on 1-bit signed bitfield

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

After some more thought and some offline discussions, I think I have a 
reasonable way forward: let's add `-Wsingle-bit-bitfield-constant-conversion` 
as a new warning group under `-Wbitfield-constant-conversion` that controls the 
diagnostic for one-bit bitfields. The diagnostic behavior here is pedantically 
correct and will help catch some bugs for folks, but there's enough existing 
code using `1` and not misbehaving (probably because they're not inspecting the 
value except in a boolean context) that having separate control seems useful.

What do others think?

In D131255#3725818 , @bjope wrote:

> A similar warning (when assigning -1 to an unsigned bitfield) can be given by 
> both gcc and clang by using ` -Wsign-conversion` but that is not part of 
> `-Wall` either. But maybe that is a totally different thing.

It's a different thing.  When the bit-field is unsigned, the conversion from 
signed is well-defined and so we only issue a `-Wconversion` warning, but it 
doesn't technically truncate the bit-field. That's also why we don't diagnose: 
https://godbolt.org/z/WW9477jfG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131255

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


[PATCH] D132030: [analyzer] Pass correct bldrCtx to computeObjectUnderConstruction

2022-08-17 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource updated this revision to Diff 453334.
tomasz-kaminski-sonarsource added a comment.

Fixed formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132030

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  clang/test/Analysis/copy-elision.cpp

Index: clang/test/Analysis/copy-elision.cpp
===
--- clang/test/Analysis/copy-elision.cpp
+++ clang/test/Analysis/copy-elision.cpp
@@ -20,6 +20,7 @@
 #endif
 
 void clang_analyzer_eval(bool);
+void clang_analyzer_dump(int);
 
 namespace variable_functional_cast_crash {
 
@@ -418,3 +419,31 @@
 }
 
 } // namespace address_vector_tests
+
+namespace arg_directly_from_return_in_loop {
+
+struct Result {
+  int value;
+};
+
+Result create() {
+  return Result{10};
+}
+
+int accessValue(Result r) {
+  return r.value;
+}
+
+void test() {
+  for (int i = 0; i < 3; ++i) {
+int v = accessValue(create());
+if (i == 0) {
+  clang_analyzer_dump(v); // expected-warning {{10 S32b}}
+} else {
+  clang_analyzer_dump(v); // expected-warning {{10 S32b}}
+  // was {{reg_${{[0-9]+}} }} for C++11
+}
+  }
+}
+
+} // namespace arg_directly_from_return_in_loop
Index: clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -111,9 +111,15 @@
   return LValue;
 }
 
+// In case when the prvalue is returned from the function (kind is one of
+// SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then
+// it's materialization happens in context of the caller.
+// We pass BldrCtx explicitly, as currBldrCtx always refers to callee's context.
 SVal ExprEngine::computeObjectUnderConstruction(
-const Expr *E, ProgramStateRef State, const LocationContext *LCtx,
-const ConstructionContext *CC, EvalCallOptions &CallOpts, unsigned Idx) {
+const Expr *E, ProgramStateRef State, const NodeBuilderContext *BldrCtx,
+const LocationContext *LCtx, const ConstructionContext *CC,
+EvalCallOptions &CallOpts, unsigned Idx) {
+
   SValBuilder &SVB = getSValBuilder();
   MemRegionManager &MRMgr = SVB.getRegionManager();
   ASTContext &ACtx = SVB.getContext();
@@ -209,8 +215,11 @@
   CallerLCtx = CallerLCtx->getParent();
   assert(!isa(CallerLCtx));
 }
+
+NodeBuilderContext CallerBldrCtx(getCoreEngine(),
+ SFC->getCallSiteBlock(), CallerLCtx);
 return computeObjectUnderConstruction(
-cast(SFC->getCallSite()), State, CallerLCtx,
+cast(SFC->getCallSite()), State, &CallerBldrCtx, CallerLCtx,
 RTC->getConstructionContext(), CallOpts);
   } else {
 // We are on the top frame of the analysis. We do not know where is the
@@ -250,7 +259,7 @@
   EvalCallOptions PreElideCallOpts = CallOpts;
 
   SVal V = computeObjectUnderConstruction(
-  TCC->getConstructorAfterElision(), State, LCtx,
+  TCC->getConstructorAfterElision(), State, BldrCtx, LCtx,
   TCC->getConstructionContextAfterElision(), CallOpts);
 
   // FIXME: This definition of "copy elision has not failed" is unreliable.
@@ -318,7 +327,7 @@
   CallEventManager &CEMgr = getStateManager().getCallEventManager();
   auto getArgLoc = [&](CallEventRef<> Caller) -> Optional {
 const LocationContext *FutureSFC =
-Caller->getCalleeStackFrame(currBldrCtx->blockCount());
+Caller->getCalleeStackFrame(BldrCtx->blockCount());
 // Return early if we are unable to reliably foresee
 // the future stack frame.
 if (!FutureSFC)
@@ -337,7 +346,7 @@
 // because this-argument is implemented as a normal argument in
 // operator call expressions but not in operator declarations.
 const TypedValueRegion *TVR = Caller->getParameterLocation(
-*Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount());
+*Caller->getAdjustedParameterIndex(Idx), BldrCtx->blockCount());
 if (!TVR)
   return None;
 
Index: clang/lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -485,9 +485,9 @@
 
   EvalCallOptions CallOpts;
   ExprEngine &Engine = getState()->getStateManager().getOwningEngine();
-  SVal RetVal =
-Engine.computeObjectUnderConstruction(getOriginExpr(), getState(),
-  getLocationContext(), CC, CallOpts);
+  SVa

[PATCH] D131992: [Support] compression proposal for a enum->spec->impl approach

2022-08-17 Thread Cole Kissane via Phabricator via cfe-commits
ckissane added inline comments.



Comment at: llvm/include/llvm/Support/Compression.h:95-98
+  static CompressionSpecRef Unknown;
+  static CompressionSpecRef None;
+  static CompressionSpecRef Zlib;
+  static CompressionSpecRef ZStd;

dblaikie wrote:
> ckissane wrote:
> > dblaikie wrote:
> > > Generally we don't want more variables that need global constructors in 
> > > LLVM - so these should probably be function-local statics in functions 
> > > instead.
> > > (I don't think we need a CompressionSpecRef for `Unknown` or `None`, 
> > > though)
> > these are just shortcuts to the function local statics of 
> > `CompressionSpecRef getCompressionSpec(uint8_t Kind)`
> Yeah, though they're still globals with non-trivial construction, which is to 
> be avoided in LLVM ( 
> https://llvm.org/docs/CodingStandards.html#do-not-use-static-constructors )
> 
> So they should either be removed (I think that's probably the right tradeoff, 
> and the one I showed in my proposal - callers that want only one specific 
> compression algorithm can pay the small runtime overhead of going through the 
> switch unnecessarily) or replaced with global functions that use function 
> local statics so the initialization is only paid when the functions are 
> called, and not by every program that links in LLVM for any reason.
I concur with removal


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131992

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


[PATCH] D131926: [clang-tidy] Fix for bugprone-sizeof-expression PR57167

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM aside from removing some comments now that we figured out what's going on. 
Please hold off on landing for a day or two in case @njames93 has other 
opinions though.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp:235-236
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
-  sum += sizeof(MyStruct*);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
-  sum += sizeof(PMyStruct);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
+  sum += sizeof(MyStruct*);  // FIXME: Warning here prior to 15f3cd6bfc6, 
consider whether to add it back.
+  sum += sizeof(PMyStruct);  // FIXME: Warning here prior to 15f3cd6bfc6, 
consider whether to add it back.
   sum += sizeof(PS);





Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression.cpp:236-238
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate
   sum += sizeof(PMyStruct);
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 
'sizeof(A*)'; pointer to aggregate

mizvekov wrote:
> aaron.ballman wrote:
> > mizvekov wrote:
> > > chrish_ericsson_atx wrote:
> > > > mizvekov wrote:
> > > > > chrish_ericsson_atx wrote:
> > > > > > njames93 wrote:
> > > > > > > mizvekov wrote:
> > > > > > > > Is this change really desirable, or should we put a FIXME here?
> > > > > > > Not warning on these cases seems like a pretty big red flag, 
> > > > > > > especially the `MyStruct *`.
> > > > > > Thank you for your comment!  I'm not sure I fully agree that this 
> > > > > > is a red flag.  I'm inclined to think that whether or not there 
> > > > > > should be a warning on `MyStruct *` or `PMyStruct` is a pretty 
> > > > > > subjective.  These are both very common idioms, and are meaningful. 
> > > > > >  I do appreciate the perspective that `MyStruct *` is just one 
> > > > > > character different from `MyStruct`, and as such, it might be a 
> > > > > > typo to ask for sizeof the pointer, when you really wanted sizeof 
> > > > > > the struct.  But the counter-argument (accidentally asking for 
> > > > > > sizeof the struct when you really wanted the pointer size) is just 
> > > > > > as valid-- and the checker obviously cannot warn in that case.   
> > > > > > 
> > > > > > I am perfectly fine with kicking the can down the road a bit by 
> > > > > > replacing the discarded `// CHECK-MESSAGES` directive with a `// 
> > > > > > FIXME`, as @mizvekov suggested.  I expect that when someone circles 
> > > > > > back to really deeply reconsider the semantics of this checker, 
> > > > > > there will be a number of changes (other existing warnings dropped, 
> > > > > > warnings for new and missed cases added, much better sync between C 
> > > > > > and C++, as well as intentional consideration of things like 
> > > > > > __typeof__ (in it's various forms) and decltype, rather than the 
> > > > > > haphazard coarse-grain matching that seems to be going on now.
> > > > > I agree with this patch only in so far that:
> > > > > 
> > > > > * This is effectively a partial revert of the changes made in 
> > > > > https://reviews.llvm.org/rG15f3cd6bfc670ba6106184a903eb04be059e5977
> > > > > * The checker was pretty much buggy to begin with.
> > > > > * That change significantly increased the amount of patterns we would 
> > > > > accept, but at the same time the existing tests did not pick that up 
> > > > > and this was not carefully considered.
> > > > > * It seems unreasonable that there is effectively no way to shut this 
> > > > > warning up per site, except by a NOLINT directive.
> > > > > 
> > > > > If the amount of false positives is so high now that this check is 
> > > > > unusable, then this is just a question of reverting to a less broken 
> > > > > state temporarily.
> > > > > 
> > > > > But otherwise we can't leave it in the reverted state either. Without 
> > > > > that change to use the canonical type or something similar, there is 
> > > > > no reason to suppose any of these test cases would work at all as 
> > > > > clang evolves and we improve the quality of implementation wrt type 
> > > > > sugar retention.
> > > > @mizvekov, I agree with your reasoning for saying "we can't leave it in 
> > > > the reverted state either".  But I'm not sure how to ensure that this 
> > > > gets the needed attention.  Should we just file a separate PR on github 
> > > > to track the needed refactoring?  I do not believe I'll have the 
> > > > bandwidth to look at this in the next few months.
> > > > 
> > > > In the meantime, assuming the bots are happy with patchset 2, I'll land 
> > > > this as-is later today.
> > > > 
> > > > Thank you very much for your feedback!
> > > Oh 

[PATCH] D113107: Support of expression granularity for _Float16.

2022-08-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added inline comments.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3140
+  return CGF.Builder.CreateFPExt(result, ConvertType(E->getType()));
+  }
+  return result;

rjmccall wrote:
> zahiraam wrote:
> > rjmccall wrote:
> > > Please extract this block out as:
> > > 
> > > ```
> > > llvm::Value *EmitPromotedValue(llvm::Value *result, QualType 
> > > PromotionType);
> > > ```
> > These changes you are proposing is when the argument of the unary __imag / 
> > __real is of type _Complex Float16. I would think that this new method 
> > EmitPromotedValue would be replacing the equivalent code in 
> > ComplexEmitter::EmitPromoted instead,  not in the scalar emitter, right?
> I probably mixed up which emitter I commented on.  The upshot is that I would 
> like there to be `EmitPromotedValue` and `EmitUnpromotedValue` helper 
> functions on both emitters (which of course would take/return an 
> `llvm::Value*` on the scalar emitter and a `CGComplexPair` on the complex 
> emitter), just so that we have all the value promotion/unpromotion logic for 
> each emitter in one place.
Let's see if what I have done is satisfactory! It's not quite "symmetrical" for 
scalar and complex. Let me know. Thanks.


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

https://reviews.llvm.org/D113107

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


[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

In D131942#3729057 , @aaron.ballman 
wrote:

> In D131942#3728994 , @erichkeane 
> wrote:
>
>> In D131942#3728974 , 
>> @aaron.ballman wrote:
>>
>>> LGTM as well; should we add a release note for this? I suspect not because 
>>> it's improving an experimental feature that's not really ready for prime 
>>> time yet, but I don't know how others feel.
>>
>> That was my thought on it, though thinking further, I wonder if there is 
>> value to it to show 'signs of life' in the release notes?
>
> @tbaeder -- do you have plans to continue to add support to the experimental 
> constant expression evaluator?
>
> If this is code that we have people actively working on with plans to bring 
> it to completion, then I think showing signs of life in the release notes is 
> a good idea. If we don't have anyone who is planning to bring this through to 
> completion, I think we should seriously considering pulling it out of the 
> tree rather than trying to maintain parallel constant expression evaluators. 
> (We wouldn't be pulling it out of the tree because we don't like the design, 
> so if someone wanted to resurrect it in the future because they planned to 
> complete it, we'd gladly welcome it.)

I certainly plan to keep working on it. I have a few more such patches locally 
that you'll have pleasure reviewing I'm sure :). It think adding a small 
changelog note is fine of course.


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

https://reviews.llvm.org/D131942

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


[PATCH] D113107: Support of expression granularity for _Float16.

2022-08-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

With this last patch, the behaviors of CodeGen/volatile-1.c and 
CodeGenCXX/volatile-1.cpp have changed ( change with __imag). I have uploaded 
the changes but still trying to figure out what exactly changed and why. Thanks.


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

https://reviews.llvm.org/D113107

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


[PATCH] D131618: [WIP][Do NOT review] LLD related changes for -ffat-lto-objects support

2022-08-17 Thread Arda Unal via Phabricator via cfe-commits
arda updated this revision to Diff 453345.
arda added a comment.
Herald added subscribers: cfe-commits, aheejin.
Herald added a project: clang.

Add clang and llvm related changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131618

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/CodeGen/BackendUtil.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  lld/ELF/Config.h
  lld/ELF/Driver.cpp
  lld/ELF/InputFiles.cpp
  lld/ELF/Options.td
  lld/test/ELF/fatlto/Inputs/a-fatLTO.o
  lld/test/ELF/fatlto/Inputs/a-thinLTO.bc
  lld/test/ELF/fatlto/Inputs/a.c
  lld/test/ELF/fatlto/Inputs/a.h
  lld/test/ELF/fatlto/Inputs/a.o
  lld/test/ELF/fatlto/Inputs/main-fatLTO.o
  lld/test/ELF/fatlto/Inputs/main-thinLTO.bc
  lld/test/ELF/fatlto/Inputs/main.c
  lld/test/ELF/fatlto/Inputs/main.o
  lld/test/ELF/fatlto/fatlto.test
  llvm/include/llvm/Bitcode/BitcodeWriter.h
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/Object/ObjectFile.cpp

Index: llvm/lib/Object/ObjectFile.cpp
===
--- llvm/lib/Object/ObjectFile.cpp
+++ llvm/lib/Object/ObjectFile.cpp
@@ -79,7 +79,7 @@
 bool ObjectFile::isSectionBitcode(DataRefImpl Sec) const {
   Expected NameOrErr = getSectionName(Sec);
   if (NameOrErr)
-return *NameOrErr == ".llvmbc";
+return *NameOrErr == ".llvmbc" || *NameOrErr == ".fatlto";
   consumeError(NameOrErr.takeError());
   return false;
 }
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -4953,6 +4953,37 @@
   llvm_unreachable("Unimplemented ObjectFormatType");
 }
 
+static const char *getSectionNameForBitcodeForFatLTO(const Triple &T) {
+  switch (T.getObjectFormat()) {
+  case Triple::MachO:
+llvm::report_fatal_error("MachO is not yet implemented for FatLTO");
+break;
+  case Triple::COFF:
+llvm::report_fatal_error("COFF is not yet implemented for FatLTO");
+break;
+  case Triple::ELF:
+return ".fatlto";
+  case Triple::Wasm:
+llvm::report_fatal_error("Wasm is not yet implemented for FatLTO");
+break;
+  case Triple::UnknownObjectFormat:
+return ".fatlto";
+  case Triple::GOFF:
+llvm::report_fatal_error("GOFF is not yet implemented for FatLTO");
+break;
+  case Triple::SPIRV:
+llvm::report_fatal_error("SPIRV is not yet implemented for FatLTO");
+break;
+  case Triple::XCOFF:
+llvm::report_fatal_error("XCOFF is not yet implemented for FatLTO");
+break;
+  case Triple::DXContainer:
+llvm::report_fatal_error("DXContainer is not yet implemented for FatLTO");
+break;
+  }
+  llvm_unreachable("Unimplemented ObjectFormatType");
+}
+
 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
 bool EmbedBitcode, bool EmbedCmdline,
 const std::vector &CmdArgs) {
@@ -5045,3 +5076,68 @@
   llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
   NewUsed->setSection("llvm.metadata");
 }
+
+void llvm::embedBitcodeInFatObject(llvm::Module &M, llvm::MemoryBufferRef Buf) {
+  // Save llvm.compiler.used and remove it.
+  SmallVector UsedArray;
+  SmallVector UsedGlobals;
+  Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
+  GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
+  for (auto *GV : UsedGlobals) {
+if (GV->getName() != "llvm.embedded.module" &&
+GV->getName() != "llvm.cmdline")
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+  }
+  if (Used)
+Used->eraseFromParent();
+
+  // Embed the bitcode for the llvm module.
+  std::string Data;
+  ArrayRef ModuleData;
+  Triple T(M.getTargetTriple());
+
+  if (Buf.getBufferSize() == 0 ||
+  !isBitcode((const unsigned char *)Buf.getBufferStart(),
+ (const unsigned char *)Buf.getBufferEnd())) {
+// If the input is LLVM Assembly, bitcode is produced by serializing
+// the module. Use-lists order need to be preserved in this case.
+llvm::raw_string_ostream OS(Data);
+llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
+ModuleData =
+ArrayRef((const uint8_t *)OS.str().data(), OS.str().size());
+  } else
+// If the input is LLVM bitcode, write the input byte stream directly.
+ModuleData = ArrayRef((const uint8_t *)Buf.getBufferStart(),
+   Buf.getBufferSize());
+  llvm::Constant *ModuleConstant =
+  llvm::ConstantDataArray::get(M.getContext(), ModuleData);
+  llvm::GlobalVariable *GV = new 

[PATCH] D131942: [clang][Interp] Implement bool and nullptr literal expressions

2022-08-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D131942#3729379 , @tbaeder wrote:

> In D131942#3729057 , @aaron.ballman 
> wrote:
>
>> In D131942#3728994 , @erichkeane 
>> wrote:
>>
>>> In D131942#3728974 , 
>>> @aaron.ballman wrote:
>>>
 LGTM as well; should we add a release note for this? I suspect not because 
 it's improving an experimental feature that's not really ready for prime 
 time yet, but I don't know how others feel.
>>>
>>> That was my thought on it, though thinking further, I wonder if there is 
>>> value to it to show 'signs of life' in the release notes?
>>
>> @tbaeder -- do you have plans to continue to add support to the experimental 
>> constant expression evaluator?
>>
>> If this is code that we have people actively working on with plans to bring 
>> it to completion, then I think showing signs of life in the release notes is 
>> a good idea. If we don't have anyone who is planning to bring this through 
>> to completion, I think we should seriously considering pulling it out of the 
>> tree rather than trying to maintain parallel constant expression evaluators. 
>> (We wouldn't be pulling it out of the tree because we don't like the design, 
>> so if someone wanted to resurrect it in the future because they planned to 
>> complete it, we'd gladly welcome it.)
>
> I certainly plan to keep working on it. I have a few more such patches 
> locally that you'll have pleasure reviewing I'm sure :). It think adding a 
> small changelog note is fine of course.

Fantastic! As long as it's heading in the right direction rather than getting 
more and more stale, I'm happy to keep it in-tree. I'm fine either way on the 
release note.


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

https://reviews.llvm.org/D131942

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


[PATCH] D131632: [clang] Enable output of SARIF diagnostics

2022-08-17 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 453346.
abrahamcd added a comment.

Removed Clang name from FileCheck test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131632

Files:
  clang/include/clang/Frontend/SARIFDiagnostic.h
  clang/include/clang/Frontend/SARIFDiagnosticPrinter.h
  clang/lib/Frontend/CMakeLists.txt
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/SARIFDiagnostic.cpp
  clang/lib/Frontend/SARIFDiagnosticPrinter.cpp
  clang/test/Frontend/sarif-diagnostics.cpp
  clang/unittests/Frontend/CMakeLists.txt
  clang/unittests/Frontend/SARIFDiagnosticTest.cpp

Index: clang/unittests/Frontend/SARIFDiagnosticTest.cpp
===
--- /dev/null
+++ clang/unittests/Frontend/SARIFDiagnosticTest.cpp
@@ -0,0 +1,123 @@
+// RUN: %clang -fdiagnostics-format=sarif %s -o %t.exe -DGTEST
+// RUN: %clang -fsyntax-only -Wall -Wextra -fdiagnostics-format=sarif %s 2>
+// %t.diags || true RUN: %t.exe < %t.diags
+
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
+#include "llvm/Support/JSON.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Program.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+#include 
+
+namespace {
+
+constexpr llvm::StringRef BrokenProgram = R"(// Example errors below start on line 2
+void main() {
+  int i = hello;
+
+  float test = 1a.0;
+
+  if (true)
+bool Yes = true;
+return;
+
+  bool j = hi;
+}
+})";
+
+TEST(SARIFDiagnosticTest, TestFields) {
+  llvm::SmallString<256> SearchDir;
+  llvm::sys::fs::current_path(SearchDir);
+  
+  SearchDir.append("/../../../bin");
+
+  llvm::ErrorOr ClangPathOrErr =
+  llvm::sys::findProgramByName("clang", {SearchDir});
+  ASSERT_TRUE(ClangPathOrErr);
+  const std::string &ClangPath = *ClangPathOrErr;
+
+  llvm::ErrorOr EchoPathOrErr =
+  llvm::sys::findProgramByName("echo");
+  ASSERT_TRUE(EchoPathOrErr);
+  const std::string &EchoPath = *EchoPathOrErr;
+
+  int EchoInputFD;
+  llvm::SmallString<32> EchoInputFile, EchoOutputFile;
+  llvm::sys::fs::createTemporaryFile("echo-input", "", EchoInputFD,
+ EchoInputFile);
+  llvm::sys::fs::createTemporaryFile("echo-output", "", EchoOutputFile);
+  llvm::FileRemover InputRemover(EchoInputFile.c_str());
+  llvm::FileRemover OutputRemover(EchoOutputFile.c_str());
+
+  llvm::Optional Redirects[] = {
+  EchoInputFile.str(), EchoOutputFile.str(), llvm::StringRef("")};
+
+  int RunResult = llvm::sys::ExecuteAndWait(EchoPath, {"echo", BrokenProgram},
+llvm::None, Redirects);
+  ASSERT_EQ(RunResult, 0);
+
+  llvm::SmallString<32> ClangErrFile;
+  llvm::sys::fs::createTemporaryFile("clang-err", "", ClangErrFile);
+  llvm::FileRemover ClangErrRemover(ClangErrFile.c_str());
+
+  llvm::Optional ClangRedirects[] = {
+  EchoOutputFile.str(), llvm::StringRef(""), ClangErrFile.str()};
+  llvm::StringRef Args[] = {"clang",
+"-xc++",
+"-",
+"-fsyntax-only",
+"-Wall",
+"-Wextra",
+"-fdiagnostics-format=sarif"};
+
+  int ClangResult =
+  llvm::sys::ExecuteAndWait(ClangPath, Args, llvm::None, ClangRedirects);
+  ASSERT_EQ(ClangResult, 1);
+
+  auto ClangErrBuf = llvm::MemoryBuffer::getFile(ClangErrFile.c_str());
+  ASSERT_TRUE(ClangErrBuf);
+  llvm::StringRef ClangErr = ClangErrBuf.get()->getBuffer();
+  ASSERT_EQ(ClangErr.str(), "hi");
+
+  llvm::Expected Value = llvm::json::parse(ClangErr.str());
+  ASSERT_FALSE(!Value);
+
+  llvm::json::Object *SarifDoc = Value->getAsObject();
+
+  const llvm::json::Array *Runs = SarifDoc->getArray("runs");
+  const llvm::json::Object *TheRun = Runs->back().getAsObject();
+  const llvm::json::Array *Results = TheRun->getArray("results");
+  
+  // Check Artifacts
+  const llvm::json::Array *Artifacts = TheRun->getArray("artifacts");
+  const llvm::json::Object *TheArtifact = Artifacts->back().getAsObject();
+  const llvm::json::Object *Location = TheArtifact->getObject("location");
+
+  ASSERT_TRUE(Location->getInteger("index").has_value());
+  ASSERT_TRUE(Location->getString("uri").has_value());
+
+  EXPECT_EQ(Location->getInteger("index").value(), 0);
+  EXPECT_EQ(Location->getString("uri").value(), "file://");
+
+  // Check Driver
+  const llvm::json::Object *Driver =
+  TheRun->getObject("tool")->getObject("driver");
+
+  ASSERT_TRUE(Driver->getString("name").has_value());
+  ASSERT_TRUE(Driver->getString("fullName").has_value());
+
+  EXPECT_EQ(Driver->getString("name").value(), "clang");
+  EXPECT_EQ(Driver->getString("fullName").value(), "clang-15");
+
+  // Check Rules
+  const llvm::json::Array *R

[PATCH] D113107: Support of expression granularity for _Float16.

2022-08-17 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:213
 TestAndClearIgnoreImag();
+PromotionType = getPromotionType(E->getSubExpr()->getType());
+if (!PromotionType.isNull())

Same problem



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:288
+const auto *BT = dyn_cast(Ty);
+if (BT->getKind() == BuiltinType::Float16)
+  PromotedTy = CGF.getContext().FloatTy;

You can just use `isFloat16Type()` here.



Comment at: clang/lib/CodeGen/CGExprComplex.cpp:609
+  ComplexPairTy Op;
+  PromotionType = getPromotionType(E->getSubExpr()->getType());
+  if (!PromotionType.isNull())

This is overwriting the argument, so the code below doesn't understand whether 
it's supposed to be emitting a promoted result or not.  You can test this with 
something like:

```
cf16 = -cf16;
```

Here the context does not want a promoted result, but you will produce one 
anyway.

Because this operator does its own arithmetic, like the binary operators, it 
needs to follow the same basic logic:
- remember whether you're supposed to emit a promoted result
- if not, check whether you should do the arithmetic promoted anyway
- if you did the arithmetic promoted, but you're not supposed to emit a 
promoted result, unpromote the result



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:626
 TestAndClearIgnoreResultAssign();
+PromotionType = getPromotionType(E->getSubExpr()->getType());
+if (!PromotionType.isNull())

Same problem



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:2857
+  Value *Op;
+  PromotionType = getPromotionType(E->getSubExpr()->getType());
+  if (!PromotionType.isNull())

Same problem



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3073
   Expr *Op = E->getSubExpr();
+  PromotionType = getPromotionType(E->getSubExpr()->getType());
   if (Op->getType()->isAnyComplexType()) {

Same problem.  However, since `__real` and `__imag` don't really do arithmetic, 
we don't need to voluntarily promote here — you shoul emit the operand promoted 
if and only if we're given a promotion type.


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

https://reviews.llvm.org/D113107

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


[PATCH] D131874: [Clang] Tighten restrictions on enum out of range diagnostic to avoid constant initialization

2022-08-17 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik updated this revision to Diff 453350.
shafik marked 2 inline comments as done.
shafik added a comment.

- Simplify condition to set `ConstexprVar` even more


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

https://reviews.llvm.org/D131874

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp


Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2419,6 +2419,13 @@
 
 enum EMaxInt {emaxint1=-1, emaxint2=__INT_MAX__};
 
+enum NumberType {};
+
+E2 testDefaultArgForParam(E2 e2Param = (E2)-1) { // ok, not a constant 
expression context
+  E2 e2LocalInit = e2Param; // ok, not a constant expression context
+  return e2LocalInit;
+}
+
 void testValueInRangeOfEnumerationValues() {
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
@@ -2454,6 +2461,8 @@
   constexpr EMaxInt x19 = static_cast(__INT_MAX__-1);
   constexpr EMaxInt x20 = static_cast((long)__INT_MAX__+1);
   // expected-error@-1 {{integer value 2147483648 is outside the valid range 
of values [-2147483648, 2147483647] for this enumeration type}}
+
+  const NumberType neg_one = (NumberType) ((NumberType) 0 - (NumberType) 1); 
// ok, not a constant expression context
 }
 
 enum SortOrder {
@@ -2470,3 +2479,8 @@
 return;
 }
 }
+
+GH50055::E2 GlobalInitNotCE1 = (GH50055::E2)-1; // ok, not a constant 
expression context
+GH50055::E2 GlobalInitNotCE2 = GH50055::testDefaultArgForParam(); // ok, not a 
constant expression context
+constexpr GH50055::E2 GlobalInitCE = (GH50055::E2)-1;
+// expected-error@-1 {{integer value -1 is outside the valid range of values 
[0, 7] for this enumeration type}}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -13536,6 +13536,18 @@
 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
 DestType->isEnumeralType()) {
+
+  bool ConstexprVar = true;
+
+  // We know if we are here that we are in a context that we might require
+  // a constant expression or a context that requires a constant
+  // value. But if we are initializing a value we don't know if it is a
+  // constexpr variable or not. We can check the EvaluatingDecl to 
determine
+  // if it constexpr or not. If not then we don't want to emit a 
diagnostic.
+  if (const auto *VD = dyn_cast_or_null(
+  Info.EvaluatingDecl.dyn_cast()))
+ConstexprVar = VD->isConstexpr();
+
   const EnumType *ET = dyn_cast(DestType.getCanonicalType());
   const EnumDecl *ED = ET->getDecl();
   // Check that the value is within the range of the enumeration values.
@@ -13555,13 +13567,14 @@
 ED->getValueRange(Max, Min);
 --Max;
 
-if (ED->getNumNegativeBits() &&
+if (ED->getNumNegativeBits() && ConstexprVar &&
 (Max.slt(Result.getInt().getSExtValue()) ||
  Min.sgt(Result.getInt().getSExtValue(
-  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
-   
diag::warn_constexpr_unscoped_enum_out_of_range)
-  << llvm::toString(Result.getInt(),10) << Min.getSExtValue() << 
Max.getSExtValue();
-else if (!ED->getNumNegativeBits() &&
+  Info.Ctx.getDiagnostics().Report(
+  E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
+  << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
+  << Max.getSExtValue();
+else if (!ED->getNumNegativeBits() && ConstexprVar &&
  Max.ult(Result.getInt().getZExtValue()))
   Info.Ctx.getDiagnostics().Report(E->getExprLoc(),

diag::warn_constexpr_unscoped_enum_out_of_range)


Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2419,6 +2419,13 @@
 
 enum EMaxInt {emaxint1=-1, emaxint2=__INT_MAX__};
 
+enum NumberType {};
+
+E2 testDefaultArgForParam(E2 e2Param = (E2)-1) { // ok, not a constant expression context
+  E2 e2LocalInit = e2Param; // ok, not a constant expression context
+  return e2LocalInit;
+}
+
 void testValueInRangeOfEnumerationValues() {
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
@@ -2454,6 +2461,8 @@
   constexpr EMaxInt x19 = static_cast(__INT_MAX__-1);
   constexpr EMaxInt x20 = static_cast((long)__INT_MAX__+1);
   // expected-error@-1 {{integer value 2147483648 is outside the valid range of values [-2147483648, 2147483647] for this enumeration type}}
+
+ 

[PATCH] D129507: [llvm-objcopy] Add option to dump embedded offloading images

2022-08-17 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 453354.
jhuber6 added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Moving to clang packager.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129507

Files:
  clang/test/Driver/offload-packager.c
  clang/tools/clang-offload-packager/ClangOffloadPackager.cpp

Index: clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
===
--- clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
+++ clang/tools/clang-offload-packager/ClangOffloadPackager.cpp
@@ -33,11 +33,20 @@
 static cl::OptionCategory
 ClangOffloadPackagerCategory("clang-offload-packager options");
 
-static cl::opt OutputFile("o", cl::Required,
-   cl::desc("Write output to ."),
+static cl::opt OutputFile("o", cl::desc("Write output to ."),
cl::value_desc("file"),
cl::cat(ClangOffloadPackagerCategory));
 
+static cl::opt InputFile(cl::Positional,
+  cl::desc("Extract from ."),
+  cl::value_desc("file"),
+  cl::cat(ClangOffloadPackagerCategory));
+
+static cl::opt AllowMissing(
+"allow-missing",
+cl::desc("Create empty files if images are missing when unpackaging.\n"),
+cl::init(false), cl::cat(ClangOffloadPackagerCategory));
+
 static cl::list
 DeviceImages("image",
  cl::desc("List of key and value arguments. Required keywords "
@@ -49,26 +58,7 @@
   OS << clang::getClangToolFullVersion("clang-offload-packager") << '\n';
 }
 
-int main(int argc, const char **argv) {
-  sys::PrintStackTraceOnErrorSignal(argv[0]);
-  cl::HideUnrelatedOptions(ClangOffloadPackagerCategory);
-  cl::SetVersionPrinter(PrintVersion);
-  cl::ParseCommandLineOptions(
-  argc, argv,
-  "A utility for bundling several object files into a single binary.\n"
-  "The output binary can then be embedded into the host section table\n"
-  "to create a fatbinary containing offloading code.\n");
-
-  if (Help) {
-cl::PrintHelpMessage();
-return EXIT_SUCCESS;
-  }
-
-  auto reportError = [argv](Error E) {
-logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
-return EXIT_FAILURE;
-  };
-
+static Error bundleImages() {
   SmallVector BinaryData;
   raw_svector_ostream OS(BinaryData);
   for (StringRef Image : DeviceImages) {
@@ -77,18 +67,17 @@
 
 StringMap Args;
 for (StringRef Arg : llvm::split(Image, ",")) {
-  auto KeyAndValue = Arg.split("=");
-  if (Args.count(KeyAndValue.first))
-Args[KeyAndValue.first] =
-Saver.save(Args[KeyAndValue.first] + "," + KeyAndValue.second);
+  auto [Key, Value] = Arg.split("=");
+  if (Args.count(Key))
+Args[Key] = Saver.save(Args[Key] + "," + Value);
   else
-Args[KeyAndValue.first] = KeyAndValue.second;
+Args[Key] = Value;
 }
 
 if (!Args.count("triple") || !Args.count("file"))
-  return reportError(createStringError(
+  return createStringError(
   inconvertibleErrorCode(),
-  "'file' and 'triple' are required image arguments"));
+  "'file' and 'triple' are required image arguments");
 
 OffloadBinary::OffloadingImage ImageBinary{};
 std::unique_ptr DeviceImage;
@@ -98,7 +87,7 @@
 llvm::ErrorOr> ObjectOrErr =
 llvm::MemoryBuffer::getFileOrSTDIN(KeyAndValue.getValue());
 if (std::error_code EC = ObjectOrErr.getError())
-  return reportError(errorCodeToError(EC));
+  return errorCodeToError(EC);
 
 // Clang uses the '.o' suffix for LTO bitcode.
 if (identify_magic((*ObjectOrErr)->getBuffer()) == file_magic::bitcode)
@@ -115,18 +104,146 @@
 }
 std::unique_ptr Buffer = OffloadBinary::write(ImageBinary);
 if (Buffer->getBufferSize() % OffloadBinary::getAlignment() != 0)
-  return reportError(
-  createStringError(inconvertibleErrorCode(),
-"Offload binary has invalid size alignment"));
+  return createStringError(inconvertibleErrorCode(),
+   "Offload binary has invalid size alignment");
 OS << Buffer->getBuffer();
   }
 
   Expected> OutputOrErr =
   FileOutputBuffer::create(OutputFile, BinaryData.size());
   if (!OutputOrErr)
-return reportError(OutputOrErr.takeError());
+return OutputOrErr.takeError();
   std::unique_ptr Output = std::move(*OutputOrErr);
   std::copy(BinaryData.begin(), BinaryData.end(), Output->getBufferStart());
   if (Error E = Output->commit())
-return reportError(std::move(E));
+return std::move(E);
+  return Error::success();
+}
+
+static Expected>>
+extractOffloadFiles(MemoryBufferRef Contents) {
+  if (identify

[clang-tools-extra] fa8f861 - [clang-tidy] hicpp-signed-bitwise - Return location of the operand (and not of the operator beginning)

2022-08-17 Thread Nathan James via cfe-commits

Author: Vladimir Plyashkun
Date: 2022-08-17T19:25:59+01:00
New Revision: fa8f8616028abbc10aa5a3ad4641e8a40ec20cc8

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

LOG: [clang-tidy] hicpp-signed-bitwise - Return location of the operand (and 
not of the operator beginning)

Currently, the "hicpp/signed-bitwise" check returns the beginning of the 
binary/unary operator as location, which sometimes confuses users in the IDE 
due to incorrect [[ 
https://youtrack.jetbrains.com/issue/CPP-12445/Clang-Tidy-highlighting-for-binary-operators-applied-to-wrong-operand
 | highlighting ]].
Yes, the offset from Ranges can be used for this particular check, but i 
suppose better solution is to return begin location of the problematic operand 
instead of operator.

Reviewed By: njames93

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp 
b/clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp
index 415babe9890d6..35631bdbf3614 100644
--- a/clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp
+++ b/clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp
@@ -80,24 +80,24 @@ void SignedBitwiseCheck::check(const 
MatchFinder::MatchResult &Result) {
  "No signed operand found in problematic bitwise operations");
 
   bool IsUnary = false;
-  SourceLocation Location;
+  SourceLocation OperatorLoc;
 
   if (const auto *UnaryOp = N.getNodeAs("unary-signed")) {
 IsUnary = true;
-Location = UnaryOp->getBeginLoc();
+OperatorLoc = UnaryOp->getOperatorLoc();
   } else {
 if (const auto *BinaryOp =
 N.getNodeAs("binary-no-sign-interference"))
-  Location = BinaryOp->getBeginLoc();
+  OperatorLoc = BinaryOp->getOperatorLoc();
 else if (const auto *BinaryOp =
  N.getNodeAs("binary-sign-interference"))
-  Location = BinaryOp->getBeginLoc();
+  OperatorLoc = BinaryOp->getOperatorLoc();
 else
   llvm_unreachable("unexpected matcher result");
   }
-  diag(Location, "use of a signed integer operand with a "
- "%select{binary|unary}0 bitwise operator")
-  << IsUnary << SignedOperand->getSourceRange();
+  diag(SignedOperand->getBeginLoc(), "use of a signed integer operand with a "
+ "%select{binary|unary}0 bitwise operator")
+  << IsUnary << SignedOperand->getSourceRange() << OperatorLoc;
 }
 
 } // namespace hicpp

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
index 56237d8b70cc4..c963157956589 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
@@ -8,14 +8,14 @@ void examples() {
 
   URes = UValue & 1u; //Ok
   URes = UValue & -1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use of a signed integer operand 
with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: use of a signed integer operand 
with a binary bitwise operator
 
   unsigned URes2 = URes << 1; //Ok
 
   int IResult;
   IResult = 10 & 2; //Ok
   IResult = 3 << -1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand 
with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: use of a signed integer operand 
with a binary bitwise operator
 
   int Int = 30;
   IResult = Int << 1;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
index 58cc911d108ea..bea9366ea5a30 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
@@ -42,7 +42,7 @@ void binary_bitwise() {
   UResult = SValue & -1;
   // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand 
with a binary bitwise operator
   UResult&= 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand 
with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand 
with a binary bitwise operator
 
   UResult = UValue & 1u; // Ok
   UResult = UValue & UValue; // Ok
@@ -63,43 +63,43 @@ void binary_bitwise() {
 
   // More complex expressions.
   UResult = UValue & (SByte1 + (SByte1 | SByte2)

[PATCH] D131678: hicpp-signed-bitwise - Return location of the operand (and not of the operator beginning)

2022-08-17 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfa8f8616028a: [clang-tidy] hicpp-signed-bitwise - Return 
location of the operand (and not of… (authored by vladimir.plyashkun, committed 
by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131678

Files:
  clang-tools-extra/clang-tidy/hicpp/SignedBitwiseCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise-integer-literals.cpp
  clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/hicpp/signed-bitwise.cpp
@@ -42,7 +42,7 @@
   UResult = SValue & -1;
   // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator
   UResult&= 1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator
 
   UResult = UValue & 1u; // Ok
   UResult = UValue & UValue; // Ok
@@ -63,43 +63,43 @@
 
   // More complex expressions.
   UResult = UValue & (SByte1 + (SByte1 | SByte2));
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: use of a signed integer operand with a binary bitwise operator
   // CHECK-MESSAGES: :[[@LINE-2]]:33: warning: use of a signed integer operand with a binary bitwise operator
 
   // The rest is to demonstrate functionality but all operators are matched equally.
   // Therefore functionality is the same for all binary operations.
   UByte1 = UByte1 | UByte2; // Ok
   UByte1 = UByte1 | SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use of a signed integer operand with a binary bitwise operator
   UByte1|= SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
   UByte1|= UByte2; // Ok
 
   UByte1 = UByte1 ^ UByte2; // Ok
   UByte1 = UByte1 ^ SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: use of a signed integer operand with a binary bitwise operator
   UByte1^= SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
   UByte1^= UByte2; // Ok
 
   UByte1 = UByte1 >> UByte2; // Ok
   UByte1 = UByte1 >> SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: use of a signed integer operand with a binary bitwise operator
   UByte1>>= SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator
   UByte1>>= UByte2; // Ok
 
   UByte1 = UByte1 << UByte2; // Ok
   UByte1 = UByte1 << SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: use of a signed integer operand with a binary bitwise operator
   UByte1<<= SByte2;
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a binary bitwise operator
   UByte1<<= UByte2; // Ok
 
   int SignedInt1 = 1 << 12;
   // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator
   int SignedInt2 = 1u << 12;
-  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: use of a signed integer operand with a binary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: use of a signed integer operand with a binary bitwise operator
 }
 
 void f1(unsigned char c) {}
@@ -113,28 +113,28 @@
   UByte1 = ~UByte1; // Ok
   SByte1 = ~UByte1;
   SByte1 = ~SByte1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use of a signed integer operand with a unary bitwise operator
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use of a signed integer operand with a unary bitwise operator
   UByte1 = ~SByte1;
-  // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use

[PATCH] D127233: [CodeGen] Sort llvm.global_ctors by lexing order before emission

2022-08-17 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen updated this revision to Diff 453373.
ychen added a comment.

- add more explanation as comments
- rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127233

Files:
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/test/CodeGenCXX/static-init-inline-variable.cpp

Index: clang/test/CodeGenCXX/static-init-inline-variable.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/static-init-inline-variable.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -std=c++17 -S -emit-llvm -disable-llvm-passes -o - %s -triple x86_64-linux-gnu | FileCheck %s
+
+struct A {
+  int x;
+  A(int x) : x(x) {}
+  ~A() {}
+};
+
+inline int a = 1;
+inline A b(a + 1);
+inline int c = b.x + 1;
+int d = c;
+
+// CHECK: @llvm.global_ctors = appending global [3 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @__cxx_global_var_init, ptr @b }, { i32, ptr, ptr } { i32 65535, ptr @__cxx_global_var_init.2, ptr @c }, { i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_static_init_inline_variable.cpp, ptr null }]
Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -2687,7 +2687,7 @@
 }
 
 CGF.FinishFunction();
-AddGlobalCtor(GlobalInitFn, Priority, nullptr);
+AddGlobalCtor(GlobalInitFn, Priority);
   }
 
   if (getCXXABI().useSinitAndSterm())
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -282,12 +282,15 @@
 
 public:
   struct Structor {
-Structor() : Priority(0), Initializer(nullptr), AssociatedData(nullptr) {}
-Structor(int Priority, llvm::Constant *Initializer,
+Structor()
+: Priority(0), LexOrder(~0u), Initializer(nullptr),
+  AssociatedData(nullptr) {}
+Structor(int Priority, unsigned LexOrder, llvm::Constant *Initializer,
  llvm::Constant *AssociatedData)
-: Priority(Priority), Initializer(Initializer),
+: Priority(Priority), LexOrder(LexOrder), Initializer(Initializer),
   AssociatedData(AssociatedData) {}
 int Priority;
+unsigned LexOrder;
 llvm::Constant *Initializer;
 llvm::Constant *AssociatedData;
   };
@@ -1602,6 +1605,7 @@
 
   // FIXME: Hardcoding priority here is gross.
   void AddGlobalCtor(llvm::Function *Ctor, int Priority = 65535,
+ unsigned LexOrder = ~0U,
  llvm::Constant *AssociatedData = nullptr);
   void AddGlobalDtor(llvm::Function *Dtor, int Priority = 65535,
  bool IsDtorAttrFunc = false);
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -47,6 +47,7 @@
 #include "clang/CodeGen/BackendUtil.h"
 #include "clang/CodeGen/ConstantInitBuilder.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
@@ -560,6 +561,9 @@
 if (PGOStats.hasDiagnostics())
   PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
   }
+  llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) {
+return L.LexOrder < R.LexOrder;
+  });
   EmitCtorList(GlobalCtors, "llvm.global_ctors");
   EmitCtorList(GlobalDtors, "llvm.global_dtors");
   EmitGlobalAnnotations();
@@ -1584,9 +1588,10 @@
 /// AddGlobalCtor - Add a function to the list that will be called before
 /// main() runs.
 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
+  unsigned LexOrder,
   llvm::Constant *AssociatedData) {
   // FIXME: Type coercion of void()* types.
-  GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
+  GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData));
 }
 
 /// AddGlobalDtor - Add a function to the list that will be called
@@ -1600,7 +1605,7 @@
   }
 
   // FIXME: Type coercion of void()* types.
-  GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
+  GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr));
 }
 
 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
Index: clang/lib/CodeGen/CGDeclCXX.cpp
===
--- clang/lib/CodeGen/CGDeclCXX.cpp
+++ clang/lib/CodeGen/CGDeclCXX.cpp
@@ -562,7 +562,7 @@
   Priority = 400;
 
 if (Priority != -1)
-  AddGlobalCtor(Fn, Priority, COMDATKey);
+  AddGlobalCtor(Fn, Priority, ~0U, COMDATKey

[PATCH] D127233: [CodeGen] Sort llvm.global_ctors by lexing order before emission

2022-08-17 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen added inline comments.



Comment at: clang/lib/CodeGen/CGDeclCXX.cpp:580
+I = DelayedCXXInitPosition.find(D);
+unsigned LexOrder = I == DelayedCXXInitPosition.end() ? ~0U : I->second;
+AddGlobalCtor(Fn, 65535, LexOrder, COMDATKey);

efriedma wrote:
> ychen wrote:
> > efriedma wrote:
> > > ychen wrote:
> > > > efriedma wrote:
> > > > > This ensures delayed initialization calls are ordered relative to 
> > > > > each other... but are they ordered correctly relative to non-delayed 
> > > > > initialization calls?  I'm skeptical that using a LexOrder of "~0U" 
> > > > > is really correct.  (For example, if you change the variable "b" in 
> > > > > your testcase to a struct with a destructor.)
> > > > Hmm, That's a great point. I didn't think of that. I'll take a look.
> > > Using `CXXGlobalInits.size()` like this is sort of hard to reason about: 
> > > multiple values can end up with the same LexOrder.  (I'm not sure if all 
> > > the values with the same LexOrder end up sorted correctly.)
> > > 
> > > Instead of trying to reason about whether this is right, can we just use 
> > > a separate counter to assign a unique index to each global init?
> > Agreed that this whole thing is confusing if not looked at closely. IIUC, 
> > LexOrder is unique for each global variables and all global variables with 
> > an initialization are pushed into `CXXGlobalInits` in lexing order 
> > regardless of deferred/non-deferred emission. I could add a counter which 
> > basically tracks the size of `CXXGlobalInits`. Which do you think is more 
> > clear: add an explicit counter or add more comments to `CXXGlobalInits` 
> > explaining the usage?
> For each global, CXXGlobalInits is supposed to contain either a pointer to a 
> function, or nullptr to indicate emission was delayed.  I guess that works as 
> a unique ordering.  But it looks like this codepath doesn't actually insert 
> anything into CXXGlobalInits; it skips that, and goes straight to 
> AddGlobalCtor.  I think that would lead to multiple globals with the same 
> index?  (Not 100% sure about this since the CXXGlobalInits code is scattered 
> all over.)
> 
> If we do expect that there won't be multiple globals with the same index, 
> please add an assertion after we sort GlobalCtors, that there aren't any 
> entries with the same LexOrder value (besides ~0).
> 
> A comment explaining the uniqueness of LexOrder is probably sufficient, given 
> nothing else is trying to produce a LexOrder.
>  (Not 100% sure about this since the CXXGlobalInits code is scattered all 
> over.)
I spoke too soon. You're correct. Using `CXXGlobalInits.size()` is correct in 
that it is the lex order number for the next deferred global variable. So as 
expected, its lex order is different from/bigger than the lex order of all 
previous deferred global variables, and regardless the next global variable is 
non-deferred or deferred, they have the same lex order as the current one but 
the order of insertion into `llvm.global_ctors` is maintained by the following 
stable sort.

I tried to implement the lex order counter approach. Due to the 
deferred/non-deferred partition, I could not simply track it using a plain 
integer counter. Instead, it would look almost the same as 
`DelayedCXXInitPosition` except that it would contain both 
deferred/non-deferred global variables. It does not feel like easier to 
understand the code since there is one more non-trivial state to track. I'll 
try clear this up in the comments instead.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127233

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


[PATCH] D131978: [clang-format] Concepts: allow identifiers after negation

2022-08-17 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel added a comment.

It seems that even with this patch, there is seemingly weird formatting with 
the negation in requires clauses, such as:

  template 
requires !F
 int bar(T t);

This is because the "fake parens" of the unary expression opened is never 
closed by the special case clean-up made for requires clauses
However, it turns out this isn't even valid syntax, as it requires parentheses 
for disambiguation. Adding those brings back correct indentation

  template 
requires(!F)
  int bar(T t);

Is it okay to ignore this case, as it wouldn't even compile?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131978

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


[PATCH] D132056: [HLSL] Restrict to supported targets

2022-08-17 Thread Chris Bieneman via Phabricator via cfe-commits
beanz created this revision.
beanz added reviewers: aaron.ballman, bogner, python3kgae, pow2clk, 
jcranmer-intel.
Herald added subscribers: Anastasia, JDevlieghere.
Herald added a project: All.
beanz requested review of this revision.
Herald added a project: clang.

Someday we would like to support HLSL on a wider range of targets, but
today targeting anything other than `dxil` is likly to cause lots of
headaches. This adds an error and tests to validate that the expected
target is `dxil-?-shadermodel`.

We will continue to do a best effort to ensure the code we write makes
it easy to support other targets (like SPIR-V), but this error will
prevent users from hitting frustrating errors for unsupported cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132056

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/hlsl-lang-targets.hlsl
  clang/test/Preprocessor/predefined-macros-hlsl.c


Index: clang/test/Preprocessor/predefined-macros-hlsl.c
===
--- clang/test/Preprocessor/predefined-macros-hlsl.c
+++ clang/test/Preprocessor/predefined-macros-hlsl.c
@@ -29,20 +29,20 @@
 // PIXEL: #define __SHADER_TARGET_STAGE 0
 // VERTEX: #define __SHADER_TARGET_STAGE 1
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl2015 | FileCheck 
-match-full-lines %s --check-prefixes=STD2015
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl2015 | FileCheck -match-full-lines %s --check-prefixes=STD2015
 // STD2015: #define __HLSL_VERSION 2015
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl2016 | FileCheck 
-match-full-lines %s --check-prefixes=STD2016
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl2016 | FileCheck -match-full-lines %s --check-prefixes=STD2016
 // STD2016: #define __HLSL_VERSION 2016
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl2017 | FileCheck 
-match-full-lines %s --check-prefixes=STD2017
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl2017 | FileCheck -match-full-lines %s --check-prefixes=STD2017
 // STD2017: #define __HLSL_VERSION 2017
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl2018 | FileCheck 
-match-full-lines %s --check-prefixes=STD2018
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl2018 | FileCheck -match-full-lines %s --check-prefixes=STD2018
 // STD2018: #define __HLSL_VERSION 2018
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl2021 | FileCheck 
-match-full-lines %s --check-prefixes=STD2021
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl2021 | FileCheck -match-full-lines %s --check-prefixes=STD2021
 // STD2021: #define __HLSL_VERSION 2021
 
-// RUN: %clang_cc1 %s -E -dM -o - -x hlsl -std=hlsl202x | FileCheck 
-match-full-lines %s --check-prefixes=STD202x
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-library %s -E -dM -o - -x 
hlsl -std=hlsl202x | FileCheck -match-full-lines %s --check-prefixes=STD202x
 // STD202x: #define __HLSL_VERSION 2029
Index: clang/test/Driver/hlsl-lang-targets.hlsl
===
--- /dev/null
+++ clang/test/Driver/hlsl-lang-targets.hlsl
@@ -0,0 +1,15 @@
+// RUN: not %clang -target x86_64-unknown-unknown %s 2>&1 | FileCheck %s 
--check-prefix=X86
+// RUN: not %clang -target dxil-unknown-unknown %s 2>&1 | FileCheck %s 
--check-prefix=DXIL
+// RUN: not %clang -target x86_64-unknown-shadermodel %s 2>&1 | FileCheck %s 
--check-prefix=SM
+// RUN: not %clang -target spirv64-unknown-unknown %s 2>&1 | FileCheck %s 
--check-prefix=SPIRV
+
+
+// A completely unsupported target...
+// X86: error: HLSL code generation is unsupported for target 
'x86_64-unknown-unknown'
+
+// Poorly specified targets
+// DXIL: error: HLSL code generation is unsupported for target 
'dxil-unknown-unknown'
+// SM: error: HLSL code generation is unsupported for target 
'x86_64-unknown-shadermodel'
+
+// Maybe someday
+// SPIRV: error: HLSL code generation is unsupported for target 
'spirv64-unknown-unknown'
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -4111,6 +4111,14 @@
   if (const Arg *A = Args.getLastArg(OPT_frandomize_layout_seed_EQ))
 Opts.RandstructSeed = A->getValue(0);
 
+  // Validate options for HLSL
+  if (Opts.HLSL) {
+bool SupportedTarget = T.getArch() == llvm::Triple::dxil &&
+   T.getOS() == llvm::Triple::ShaderModel;
+if (!SupportedTarget)
+  Diags.Report(diag::err_drv_hlsl_unsupported_target) << T.str();
+  }
+
   return Diags.getNumErrors() == NumErrorsBefore;
 }
 
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
==

[PATCH] D131992: [Support] compression proposal for a enum->spec->impl approach

2022-08-17 Thread Cole Kissane via Phabricator via cfe-commits
ckissane updated this revision to Diff 453379.
ckissane added a comment.

- remove CompressionSpecRefs::{Zlib,ZStd}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131992

Files:
  clang-tools-extra/clangd/index/Serialization.cpp
  clang-tools-extra/clangd/unittests/SerializationTests.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  lld/ELF/Driver.cpp
  lld/ELF/InputSection.cpp
  llvm/include/llvm/Object/Decompressor.h
  llvm/include/llvm/ProfileData/InstrProf.h
  llvm/include/llvm/Support/Compression.h
  llvm/lib/MC/ELFObjectWriter.cpp
  llvm/lib/ObjCopy/ELF/ELFObject.cpp
  llvm/lib/Object/Decompressor.cpp
  llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
  llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
  llvm/lib/ProfileData/InstrProf.cpp
  llvm/lib/ProfileData/InstrProfCorrelator.cpp
  llvm/lib/ProfileData/SampleProfReader.cpp
  llvm/lib/ProfileData/SampleProfWriter.cpp
  llvm/lib/Support/Compression.cpp
  llvm/tools/llvm-mc/llvm-mc.cpp
  llvm/tools/llvm-objcopy/ObjcopyOptions.cpp
  llvm/unittests/ProfileData/InstrProfTest.cpp
  llvm/unittests/Support/CompressionTest.cpp

Index: llvm/unittests/Support/CompressionTest.cpp
===
--- llvm/unittests/Support/CompressionTest.cpp
+++ llvm/unittests/Support/CompressionTest.cpp
@@ -22,31 +22,48 @@
 
 namespace {
 
-#if LLVM_ENABLE_ZLIB
-static void testZlibCompression(StringRef Input, int Level) {
+static void testCompressionAlgorithm(
+StringRef Input, int Level, CompressionSpecRef CompressionScheme,
+std::string ExpectedDestinationBufferTooSmallErrorMessage) {
   SmallVector Compressed;
   SmallVector Uncompressed;
-  zlib::compress(arrayRefFromStringRef(Input), Compressed, Level);
+  CompressionScheme->Implementation->compress(arrayRefFromStringRef(Input),
+  Compressed, Level);
 
   // Check that uncompressed buffer is the same as original.
-  Error E = zlib::uncompress(Compressed, Uncompressed, Input.size());
+  Error E = CompressionScheme->Implementation->decompress(
+  Compressed, Uncompressed, Input.size());
   consumeError(std::move(E));
 
   EXPECT_EQ(Input, toStringRef(Uncompressed));
   if (Input.size() > 0) {
 // Uncompression fails if expected length is too short.
-E = zlib::uncompress(Compressed, Uncompressed, Input.size() - 1);
-EXPECT_EQ("zlib error: Z_BUF_ERROR", llvm::toString(std::move(E)));
+E = CompressionScheme->Implementation->decompress(Compressed, Uncompressed,
+  Input.size() - 1);
+EXPECT_EQ(ExpectedDestinationBufferTooSmallErrorMessage,
+  llvm::toString(std::move(E)));
   }
 }
 
-TEST(CompressionTest, Zlib) {
-  testZlibCompression("", zlib::DefaultCompression);
+#if LLVM_ENABLE_ZLIB
+static void testZlibCompression(StringRef Input, int Level) {
+  testCompressionAlgorithm(Input, Level,
+   getCompressionSpec(CompressionKind::Zlib),
+   "zlib error: Z_BUF_ERROR");
+}
 
-  testZlibCompression("hello, world!", zlib::NoCompression);
-  testZlibCompression("hello, world!", zlib::BestSizeCompression);
-  testZlibCompression("hello, world!", zlib::BestSpeedCompression);
-  testZlibCompression("hello, world!", zlib::DefaultCompression);
+TEST(CompressionTest, Zlib) {
+  CompressionSpecRef CompressionScheme =
+  getCompressionSpec(CompressionKind::Zlib);
+  CompressionImplRef CompressionImplementation =
+  CompressionScheme->Implementation;
+  testZlibCompression("", CompressionImplementation->DefaultLevel);
+
+  testZlibCompression("hello, world!",
+  CompressionImplementation->BestSizeLevel);
+  testZlibCompression("hello, world!",
+  CompressionImplementation->BestSpeedLevel);
+  testZlibCompression("hello, world!", CompressionImplementation->DefaultLevel);
 
   const size_t kSize = 1024;
   char BinaryData[kSize];
@@ -54,38 +71,32 @@
 BinaryData[i] = i & 255;
   StringRef BinaryDataStr(BinaryData, kSize);
 
-  testZlibCompression(BinaryDataStr, zlib::NoCompression);
-  testZlibCompression(BinaryDataStr, zlib::BestSizeCompression);
-  testZlibCompression(BinaryDataStr, zlib::BestSpeedCompression);
-  testZlibCompression(BinaryDataStr, zlib::DefaultCompression);
+  testZlibCompression(BinaryDataStr, CompressionImplementation->BestSizeLevel);
+  testZlibCompression(BinaryDataStr, CompressionImplementation->BestSpeedLevel);
+  testZlibCompression(BinaryDataStr, CompressionImplementation->DefaultLevel);
 }
 #endif
 
 #if LLVM_ENABLE_ZSTD
-static void testZstdCompression(StringRef Input, int Level) {
-  SmallVector Compressed;
-  SmallVector Uncompressed;
-  zstd::compress(arrayRefFromStringRef(Input), Compressed, Level);
 
-  // Check that uncompressed buffer is the sa

[PATCH] D131992: [Support] compression proposal for a enum->spec->impl approach

2022-08-17 Thread Cole Kissane via Phabricator via cfe-commits
ckissane marked 6 inline comments as done.
ckissane added inline comments.



Comment at: llvm/include/llvm/Support/Compression.h:40
+CompressionSpecRef getCompressionSpec(CompressionKind Kind);
+CompressionSpecRef getSchemeDetails(CompressionImplRef Implementation);
+

dblaikie wrote:
> I don't think we need this function?
removed



Comment at: llvm/include/llvm/Support/Compression.h:46
+  const StringRef Name;
+  const bool Supported;
+  const StringRef Status; // either "supported", or "unsupported: REASON"

dblaikie wrote:
> Probably don't need this member - it should be communicated by the 
> non-null-ness of `Implementation`?
removed Supported bool



Comment at: llvm/include/llvm/Support/Compression.h:87
+
+  CompressionSpecRef spec() { return getCompressionSpec(Kind); }
+

dblaikie wrote:
> the imple could have a pointer back to the spec, rather than having to do 
> another lookup/need another function? (though, if the levels are moved to the 
> impl, maybe this API is not needed?)
`levels are moved to the impl, [thus] this API is not needed`



Comment at: llvm/lib/Object/Decompressor.cpp:50
+return createError(
+"Decompressor provided nullptr (None) CompressionScheme*");
+  if (!CompressionScheme->Implementation)

ckissane wrote:
> dblaikie wrote:
> > This probably isn't a useful error message for a user. And this code is 
> > unreachable/untestable, right? The above code would've already errored out 
> > on "unsupported compression type"?
> true, it is essentially a repeat of the above
redundancy removed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131992

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


[PATCH] D131618: [WIP][Do NOT review] LLD related changes for -ffat-lto-objects support

2022-08-17 Thread Arda Unal via Phabricator via cfe-commits
arda updated this revision to Diff 453386.
arda added a comment.

Replace section name from .fatlto to .llvm.lto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131618

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/CodeGen/BackendUtil.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  lld/ELF/Config.h
  lld/ELF/Driver.cpp
  lld/ELF/InputFiles.cpp
  lld/ELF/Options.td
  lld/test/ELF/fatlto/Inputs/a.c
  lld/test/ELF/fatlto/Inputs/a.h
  lld/test/ELF/fatlto/Inputs/main.c
  lld/test/ELF/fatlto/fatlto.test
  llvm/include/llvm/Bitcode/BitcodeWriter.h
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/Object/ObjectFile.cpp

Index: llvm/lib/Object/ObjectFile.cpp
===
--- llvm/lib/Object/ObjectFile.cpp
+++ llvm/lib/Object/ObjectFile.cpp
@@ -79,7 +79,7 @@
 bool ObjectFile::isSectionBitcode(DataRefImpl Sec) const {
   Expected NameOrErr = getSectionName(Sec);
   if (NameOrErr)
-return *NameOrErr == ".llvmbc";
+return *NameOrErr == ".llvmbc" || *NameOrErr == ".llvm.lto";
   consumeError(NameOrErr.takeError());
   return false;
 }
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -4953,6 +4953,37 @@
   llvm_unreachable("Unimplemented ObjectFormatType");
 }
 
+static const char *getSectionNameForBitcodeForFatLTO(const Triple &T) {
+  switch (T.getObjectFormat()) {
+  case Triple::MachO:
+llvm::report_fatal_error("MachO is not yet implemented for FatLTO");
+break;
+  case Triple::COFF:
+llvm::report_fatal_error("COFF is not yet implemented for FatLTO");
+break;
+  case Triple::ELF:
+return ".llvm.lto";
+  case Triple::Wasm:
+llvm::report_fatal_error("Wasm is not yet implemented for FatLTO");
+break;
+  case Triple::UnknownObjectFormat:
+return ".llvm.lto";
+  case Triple::GOFF:
+llvm::report_fatal_error("GOFF is not yet implemented for FatLTO");
+break;
+  case Triple::SPIRV:
+llvm::report_fatal_error("SPIRV is not yet implemented for FatLTO");
+break;
+  case Triple::XCOFF:
+llvm::report_fatal_error("XCOFF is not yet implemented for FatLTO");
+break;
+  case Triple::DXContainer:
+llvm::report_fatal_error("DXContainer is not yet implemented for FatLTO");
+break;
+  }
+  llvm_unreachable("Unimplemented ObjectFormatType");
+}
+
 void llvm::embedBitcodeInModule(llvm::Module &M, llvm::MemoryBufferRef Buf,
 bool EmbedBitcode, bool EmbedCmdline,
 const std::vector &CmdArgs) {
@@ -5045,3 +5076,68 @@
   llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
   NewUsed->setSection("llvm.metadata");
 }
+
+void llvm::embedBitcodeInFatObject(llvm::Module &M, llvm::MemoryBufferRef Buf) {
+  // Save llvm.compiler.used and remove it.
+  SmallVector UsedArray;
+  SmallVector UsedGlobals;
+  Type *UsedElementType = Type::getInt8Ty(M.getContext())->getPointerTo(0);
+  GlobalVariable *Used = collectUsedGlobalVariables(M, UsedGlobals, true);
+  for (auto *GV : UsedGlobals) {
+if (GV->getName() != "llvm.embedded.module" &&
+GV->getName() != "llvm.cmdline")
+  UsedArray.push_back(
+  ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
+  }
+  if (Used)
+Used->eraseFromParent();
+
+  // Embed the bitcode for the llvm module.
+  std::string Data;
+  ArrayRef ModuleData;
+  Triple T(M.getTargetTriple());
+
+  if (Buf.getBufferSize() == 0 ||
+  !isBitcode((const unsigned char *)Buf.getBufferStart(),
+ (const unsigned char *)Buf.getBufferEnd())) {
+// If the input is LLVM Assembly, bitcode is produced by serializing
+// the module. Use-lists order need to be preserved in this case.
+llvm::raw_string_ostream OS(Data);
+llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
+ModuleData =
+ArrayRef((const uint8_t *)OS.str().data(), OS.str().size());
+  } else
+// If the input is LLVM bitcode, write the input byte stream directly.
+ModuleData = ArrayRef((const uint8_t *)Buf.getBufferStart(),
+   Buf.getBufferSize());
+  llvm::Constant *ModuleConstant =
+  llvm::ConstantDataArray::get(M.getContext(), ModuleData);
+  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
+  M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
+  ModuleConstant);
+  GV->setSection(getSectionNameForBitcodeForFatLTO(T));
+  // Set alignment to 1 to prevent padding between two contributions from input
+  // sections after linking.
+  GV->s

[PATCH] D130510: Missing tautological compare warnings due to unary operators

2022-08-17 Thread Muhammad Usman Shahid via Phabricator via cfe-commits
Codesbyusman updated this revision to Diff 453388.
Codesbyusman added a comment.

updated test cases.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Analysis/CFG.cpp
  clang/test/Sema/warn-bitwise-compare.c
  clang/test/SemaCXX/warn-bitwise-compare.cpp
  clang/test/SemaCXX/warn-unreachable.cpp

Index: clang/test/SemaCXX/warn-unreachable.cpp
===
--- clang/test/SemaCXX/warn-unreachable.cpp
+++ clang/test/SemaCXX/warn-unreachable.cpp
@@ -396,16 +396,18 @@
   if (y == -1 && y != -1)  // expected-note {{silence}}
 calledFun();// expected-warning {{will never be executed}}
 
-  // TODO: Extend warning to the following code:
-  if (x < -1)
-calledFun();
-  if (x == -1)
-calledFun();
+  if (x == -1)   // expected-note {{silence}}
+calledFun(); // expected-warning {{will never be executed}}
 
-  if (x != -1)
+  if (x != -1)   // expected-note {{silence}}
 calledFun();
   else
+calledFun(); // expected-warning {{will never be executed}}
+
+  // TODO: Extend warning to the following code:
+  if (x < -1)
 calledFun();
+ 
   if (-1 > x)
 calledFun();
   else
Index: clang/test/SemaCXX/warn-bitwise-compare.cpp
===
--- clang/test/SemaCXX/warn-bitwise-compare.cpp
+++ clang/test/SemaCXX/warn-bitwise-compare.cpp
@@ -11,3 +11,15 @@
   bool b4 = !!(x | 5);
   // expected-warning@-1 {{bitwise or with non-zero value always evaluates to true}}
 }
+
+template   // silence
+void foo(int x) {
+bool b1 = (x & sizeof(T)) == 8;
+bool b2 = (x & I) == 8;
+bool b3 = (x & 4) == 8; // expected-warning {{bitwise comparison always evaluates to false}}
+}
+
+void run(int x) {
+foo<4, int>(8); // expected-note {{in instantiation of function template specialization 'foo<4, int>' requested here}}
+}
+
Index: clang/test/Sema/warn-bitwise-compare.c
===
--- clang/test/Sema/warn-bitwise-compare.c
+++ clang/test/Sema/warn-bitwise-compare.c
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wall -Wno-unused %s
 
 #define mydefine 2
+#define mydefine2 -2
 
 enum {
   ZERO,
@@ -11,29 +12,85 @@
 void f(int x) {
   if ((8 & x) == 3) {}  // expected-warning {{bitwise comparison always evaluates to false}}
   if ((x & 8) == 4) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((-8 & x) == 3) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((x & -8) == 4) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+
   if ((x & 8) != 4) {}  // expected-warning {{bitwise comparison always evaluates to true}}
   if ((2 & x) != 4) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+  if ((x & -8) != 4) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+  if ((-2 & x) != 3) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+ 
   if ((x | 4) == 3) {}  // expected-warning {{bitwise comparison always evaluates to false}}
   if ((x | 3) != 4) {}  // expected-warning {{bitwise comparison always evaluates to true}}
   if ((5 | x) != 3) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+
+  if ((x | -4) == 3) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((x | -3) != 4) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+  if ((-5 | x) != 3) {}  // expected-warning {{bitwise comparison always evaluates to true}}
+  
   if ((x & 0x15) == 0x13) {} // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((x & 0xFFEB) == 0x13) {} // expected-warning {{bitwise comparison always evaluates to false}}
+
   if ((0x23 | x) == 0x155){} // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((0xFFDD | x) == 0x155){} // expected-warning {{bitwise comparison always evaluates to false}}
 
   if (!!((8 & x) == 3)) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+  if (!!((-8 & x) == 3)) {}  // expected-warning {{bitwise comparison always evaluates to false}}
+
   int y = ((8 & x) == 3) ? 1 : 2;  // expected-warning {{bitwise comparison always evaluates to false}}
+  y = ((-8 & x) == 3) ? 1 : 2;  // expected-warning {{bitwise comparison always evaluates to false}}
+  y = ((3 | x) != 5) ? 1 : 2;  // expected-warning {{bitwise comparison always evaluates to true}}
+  y = ((-3 | x) != 5) ? 1 : 2;  // expected-warning {{bitwise comparison always evaluates to true}}
+
+  if ((x & 0) != !0) {} // expected-warning {{bitwise comparison always evaluates to true}}
+  if ((x & 0) == !0) {} // expected-warning {{bitwise comparison always evaluates to false}}
+  if ((x & 2) == !0) {} // expected-warning {{bitwise comparison al

[PATCH] D131874: [Clang] Tighten restrictions on enum out of range diagnostic to avoid constant initialization

2022-08-17 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik updated this revision to Diff 453389.
shafik marked an inline comment as done.
shafik added a comment.

- Added `consteval` test with default parameters


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

https://reviews.llvm.org/D131874

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -865,3 +865,15 @@
 }
 
 } // namespace multiple_default_constructors
+
+namespace GH50055 {
+enum E {e1=0, e2=1};
+consteval int testDefaultArgForParam(E eParam = (E)-1) {
+// expected-error@-1 {{integer value -1 is outside the valid range of values 
[0, 1] for this enumeration type}}
+  return (int)eParam;
+}
+
+int test() {
+  return testDefaultArgForParam() + testDefaultArgForParam((E)1);
+}
+}
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -2419,6 +2419,13 @@
 
 enum EMaxInt {emaxint1=-1, emaxint2=__INT_MAX__};
 
+enum NumberType {};
+
+E2 testDefaultArgForParam(E2 e2Param = (E2)-1) { // ok, not a constant 
expression context
+  E2 e2LocalInit = e2Param; // ok, not a constant expression context
+  return e2LocalInit;
+}
+
 void testValueInRangeOfEnumerationValues() {
   constexpr E1 x1 = static_cast(-8);
   constexpr E1 x2 = static_cast(8);
@@ -2454,6 +2461,8 @@
   constexpr EMaxInt x19 = static_cast(__INT_MAX__-1);
   constexpr EMaxInt x20 = static_cast((long)__INT_MAX__+1);
   // expected-error@-1 {{integer value 2147483648 is outside the valid range 
of values [-2147483648, 2147483647] for this enumeration type}}
+
+  const NumberType neg_one = (NumberType) ((NumberType) 0 - (NumberType) 1); 
// ok, not a constant expression context
 }
 
 enum SortOrder {
@@ -2470,3 +2479,8 @@
 return;
 }
 }
+
+GH50055::E2 GlobalInitNotCE1 = (GH50055::E2)-1; // ok, not a constant 
expression context
+GH50055::E2 GlobalInitNotCE2 = GH50055::testDefaultArgForParam(); // ok, not a 
constant expression context
+constexpr GH50055::E2 GlobalInitCE = (GH50055::E2)-1;
+// expected-error@-1 {{integer value -1 is outside the valid range of values 
[0, 7] for this enumeration type}}
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -13536,6 +13536,18 @@
 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
 DestType->isEnumeralType()) {
+
+  bool ConstexprVar = true;
+
+  // We know if we are here that we are in a context that we might require
+  // a constant expression or a context that requires a constant
+  // value. But if we are initializing a value we don't know if it is a
+  // constexpr variable or not. We can check the EvaluatingDecl to 
determine
+  // if it constexpr or not. If not then we don't want to emit a 
diagnostic.
+  if (const auto *VD = dyn_cast_or_null(
+  Info.EvaluatingDecl.dyn_cast()))
+ConstexprVar = VD->isConstexpr();
+
   const EnumType *ET = dyn_cast(DestType.getCanonicalType());
   const EnumDecl *ED = ET->getDecl();
   // Check that the value is within the range of the enumeration values.
@@ -13555,13 +13567,14 @@
 ED->getValueRange(Max, Min);
 --Max;
 
-if (ED->getNumNegativeBits() &&
+if (ED->getNumNegativeBits() && ConstexprVar &&
 (Max.slt(Result.getInt().getSExtValue()) ||
  Min.sgt(Result.getInt().getSExtValue(
-  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
-   
diag::warn_constexpr_unscoped_enum_out_of_range)
-  << llvm::toString(Result.getInt(),10) << Min.getSExtValue() << 
Max.getSExtValue();
-else if (!ED->getNumNegativeBits() &&
+  Info.Ctx.getDiagnostics().Report(
+  E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
+  << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
+  << Max.getSExtValue();
+else if (!ED->getNumNegativeBits() && ConstexprVar &&
  Max.ult(Result.getInt().getZExtValue()))
   Info.Ctx.getDiagnostics().Report(E->getExprLoc(),

diag::warn_constexpr_unscoped_enum_out_of_range)


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -865,3 +865,15 @@
 }
 
 } // namespace multiple_default_constructors
+
+namespace

[PATCH] D130531: [IR] Use Min behavior for module flag "PIC Level"

2022-08-17 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130531

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


  1   2   >