[PATCH] D124816: [Tooling] use different FileManager for each CWD

2022-05-06 Thread Shi Chen via Phabricator via cfe-commits
Kale added a comment.

In D124816#3494243 , @dexonsmith 
wrote:

> Two high-level comments:
>
> - Making these functions `virtual` makes it harder to reason about possible 
> implementations, but I don't think that's necessary for what you're doing 
> here. Why not expose `ToolFileManager` as a container of filemanagers which 
> ToolInvocation takes by parameter, then calls `getOrCreateFileManager()` on 
> at time of need passing relevant arguments (e.g., CWD)?
>   - This could also create/manage the relevant VFS instance, to which the 
> FileManager is fundamentally tied. See also below.
> - I don't think this goes far enough. The FileManager keeps state for any 
> accessed file, which can be wrong any time the VFS changes at all, not just 
> if the `CWD` is different. E.g., different `-ivfsoverlay` options are passed, 
> or someone is reading from an `InMemoryFileSystem` vs. from disk.
>   - AFAICT, every call to `FileManager::setVirtualFileSystem()` is 
> fundamentally unsound unless the new FS is equivalent to the old one or the 
> filemanager hasn't been used yet.

Thanks for your careful and useful suggestions. With your explanation, I 
realized that the change of VFS of course should be considered as well. I'll 
revise this patch and tries to cope with it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124816

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


[PATCH] D125037: [pseudo] Add fuzzer for the pseudoparser.

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp:81
+  bool PrintForest = false;
+  unsigned O = 1;
+  for (int I = 1; I < *Argc; ++I) {

hokein wrote:
> nit: I'd suggest using another name -- `O` looks similar to the number 
> literal `0`.  
Realized I can use std::remove_if here instead which is cleaner.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125037

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


[clang-tools-extra] 1616bd9 - [pseudo] Add fuzzer for the pseudoparser.

2022-05-06 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-05-06T09:22:28+02:00
New Revision: 1616bd9ef4eb46a340a8765eab440f99e9008003

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

LOG: [pseudo] Add fuzzer for the pseudoparser.

As confirmation, running this locally found 2 crashes:
 - trivial: crashes on file with no tokens
 - lexer: hits an assertion failure on bytes: 0x5c,0xa,0x5c,0x1,0x65,0x5c,0xa

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

Added: 
clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
clang-tools-extra/pseudo/fuzzer/Main.cpp
clang-tools-extra/pseudo/test/fuzzer.cpp

Modified: 
clang-tools-extra/pseudo/CMakeLists.txt
clang-tools-extra/pseudo/test/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/pseudo/CMakeLists.txt 
b/clang-tools-extra/pseudo/CMakeLists.txt
index fe7f7c63fb75..e94737f7f3e8 100644
--- a/clang-tools-extra/pseudo/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/CMakeLists.txt
@@ -2,6 +2,7 @@ include_directories(include)
 include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
 add_subdirectory(lib)
 add_subdirectory(tool)
+add_subdirectory(fuzzer)
 if(CLANG_INCLUDE_TESTS)
   add_subdirectory(unittests)
   add_subdirectory(test)

diff  --git a/clang-tools-extra/pseudo/fuzzer/CMakeLists.txt 
b/clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
new file mode 100644
index ..fc583de8b011
--- /dev/null
+++ b/clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
@@ -0,0 +1,14 @@
+set(LLVM_LINK_COMPONENTS
+  FuzzMutate
+  Support
+  )
+
+add_llvm_fuzzer(clang-pseudo-fuzzer
+  Fuzzer.cpp
+  DUMMY_MAIN Main.cpp
+  )
+
+target_link_libraries(clang-pseudo-fuzzer
+  PRIVATE
+  clangPseudo
+  )

diff  --git a/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp 
b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
new file mode 100644
index ..4907fc9f9c04
--- /dev/null
+++ b/clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
@@ -0,0 +1,106 @@
+//===-- Fuzzer.cpp - Fuzz the pseudoparser 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-pseudo/DirectiveTree.h"
+#include "clang-pseudo/Forest.h"
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/LRTable.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+class Fuzzer {
+  clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
+  std::unique_ptr G;
+  LRTable T;
+  bool Print;
+
+public:
+  Fuzzer(llvm::StringRef GrammarPath, bool Print) : Print(Print) {
+llvm::ErrorOr> GrammarText =
+llvm::MemoryBuffer::getFile(GrammarPath);
+if (std::error_code EC = GrammarText.getError()) {
+  llvm::errs() << "Error: can't read grammar file '" << GrammarPath
+   << "': " << EC.message() << "\n";
+  std::exit(1);
+}
+std::vector Diags;
+G = Grammar::parseBNF(GrammarText->get()->getBuffer(), Diags);
+if (!Diags.empty()) {
+  for (const auto &Diag : Diags)
+llvm::errs() << Diag << "\n";
+  std::exit(1);
+}
+T = LRTable::buildSLR(*G);
+  }
+
+  void operator()(llvm::StringRef Code) {
+std::string CodeStr = Code.str(); // Must be null-terminated.
+auto RawStream = lex(CodeStr, LangOpts);
+auto DirectiveStructure = DirectiveTree::parse(RawStream);
+clang::pseudo::chooseConditionalBranches(DirectiveStructure, RawStream);
+// FIXME: strip preprocessor directives
+auto ParseableStream =
+clang::pseudo::stripComments(cook(RawStream, LangOpts));
+
+clang::pseudo::ForestArena Arena;
+clang::pseudo::GSS GSS;
+auto &Root = glrParse(ParseableStream,
+  clang::pseudo::ParseParams{*G, T, Arena, GSS});
+if (Print)
+  llvm::outs() << Root.dumpRecursive(*G);
+  }
+};
+
+Fuzzer *Fuzz = nullptr;
+
+} // namespace
+} // namespace pseudo
+} // namespace clang
+
+extern "C" {
+
+// Set up the fuzzer from command line flags:
+//  -grammar= (required) - path to cxx.bnf
+//  -print - used for testing the fuzzer
+int LLVMFuzzerInitialize(int *Argc, char ***Argv) {
+  llvm::StringRef GrammarFile;
+  bool PrintForest = false;
+  auto ConsumeArg = [&](llvm::StringRef Arg) -> bool {
+if (Arg.consume_front("-grammar=")) {
+  GrammarFile = Arg;
+  return true;
+} else if (Arg == "-print") {

[PATCH] D125037: [pseudo] Add fuzzer for the pseudoparser.

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG1616bd9ef4eb: [pseudo] Add fuzzer for the pseudoparser. 
(authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D125037?vs=427421&id=427542#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125037

Files:
  clang-tools-extra/pseudo/CMakeLists.txt
  clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
  clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
  clang-tools-extra/pseudo/fuzzer/Main.cpp
  clang-tools-extra/pseudo/test/CMakeLists.txt
  clang-tools-extra/pseudo/test/fuzzer.cpp

Index: clang-tools-extra/pseudo/test/fuzzer.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/fuzzer.cpp
@@ -0,0 +1,4 @@
+// RUN: clang-pseudo-fuzzer -grammar=%cxx-bnf-file -print %s | FileCheck %s
+int x;
+// CHECK: translation-unit := declaration-seq
+// CHECK: simple-type-specifier := INT
Index: clang-tools-extra/pseudo/test/CMakeLists.txt
===
--- clang-tools-extra/pseudo/test/CMakeLists.txt
+++ clang-tools-extra/pseudo/test/CMakeLists.txt
@@ -1,5 +1,6 @@
 set(CLANG_PSEUDO_TEST_DEPS
   clang-pseudo
+  clang-pseudo-fuzzer
   ClangPseudoTests
   )
 
Index: clang-tools-extra/pseudo/fuzzer/Main.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/fuzzer/Main.cpp
@@ -0,0 +1,16 @@
+//===--- Main.cpp - Entry point to sanity check the fuzzer ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "llvm/FuzzMutate/FuzzerCLI.h"
+
+extern "C" int LLVMFuzzerInitialize(int *, char ***);
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *, size_t);
+int main(int argc, char *argv[]) {
+  return llvm::runFuzzerOnInputs(argc, argv, LLVMFuzzerTestOneInput,
+ LLVMFuzzerInitialize);
+}
Index: clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
@@ -0,0 +1,106 @@
+//===-- Fuzzer.cpp - Fuzz the pseudoparser ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang-pseudo/DirectiveTree.h"
+#include "clang-pseudo/Forest.h"
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/LRTable.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+class Fuzzer {
+  clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
+  std::unique_ptr G;
+  LRTable T;
+  bool Print;
+
+public:
+  Fuzzer(llvm::StringRef GrammarPath, bool Print) : Print(Print) {
+llvm::ErrorOr> GrammarText =
+llvm::MemoryBuffer::getFile(GrammarPath);
+if (std::error_code EC = GrammarText.getError()) {
+  llvm::errs() << "Error: can't read grammar file '" << GrammarPath
+   << "': " << EC.message() << "\n";
+  std::exit(1);
+}
+std::vector Diags;
+G = Grammar::parseBNF(GrammarText->get()->getBuffer(), Diags);
+if (!Diags.empty()) {
+  for (const auto &Diag : Diags)
+llvm::errs() << Diag << "\n";
+  std::exit(1);
+}
+T = LRTable::buildSLR(*G);
+  }
+
+  void operator()(llvm::StringRef Code) {
+std::string CodeStr = Code.str(); // Must be null-terminated.
+auto RawStream = lex(CodeStr, LangOpts);
+auto DirectiveStructure = DirectiveTree::parse(RawStream);
+clang::pseudo::chooseConditionalBranches(DirectiveStructure, RawStream);
+// FIXME: strip preprocessor directives
+auto ParseableStream =
+clang::pseudo::stripComments(cook(RawStream, LangOpts));
+
+clang::pseudo::ForestArena Arena;
+clang::pseudo::GSS GSS;
+auto &Root = glrParse(ParseableStream,
+  clang::pseudo::ParseParams{*G, T, Arena, GSS});
+if (Print)
+  llvm::outs() << Root.dumpRecursive(*G);
+  }
+};
+
+Fuzzer *Fuzz = nullptr;
+
+} // namespace
+} // namespace pseudo
+} // namespace clang
+
+extern "C" {
+
+// Set up the fuzzer from command line flags:
+//  -grammar= (required) - path to cxx.bnf
+//  -print   

[PATCH] D125037: [pseudo] Add fuzzer for the pseudoparser.

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This adds a false dependency between check-clang-pseudo and all of LLVM via the 
FuzzMutate library.
(We use FuzzerCLI.h, but there's also a bunch of utilities for fuzzing IR).
I'll try to split that library up to avoid the false dependency in a followup.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125037

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


[PATCH] D124983: [HLSL} add -fcgl option flag.

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

Add emit_pristine_llvm to make fcgl easier to understand.
Also change unit test to lib test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124983

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/HLSL.cpp
  clang/test/Driver/dxc_fcgl.hlsl


Index: clang/test/Driver/dxc_fcgl.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_fcgl.hlsl
@@ -0,0 +1,5 @@
+// RUN: %clang_dxc -fcgl foo.hlsl -### %s 2>&1 | FileCheck %s
+
+// Make sure fcgl option flag which translated into "-S" "-emit-llvm" 
"-disable-llvm-passes".
+// CHECK:"-S" "-emit-llvm" "-disable-llvm-passes"
+
Index: clang/lib/Driver/ToolChains/HLSL.cpp
===
--- clang/lib/Driver/ToolChains/HLSL.cpp
+++ clang/lib/Driver/ToolChains/HLSL.cpp
@@ -169,6 +169,15 @@
   if (!isLegalValidatorVersion(ValVerStr, getDriver()))
 continue;
 }
+if (A->getOption().getID() == options::OPT_emit_pristine_llvm) {
+  // Translate fcgl into -S -emit-llvm and -disable-llvm-passes.
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_emit_llvm));
+  DAL->AddFlagArg(nullptr,
+  Opts.getOption(options::OPT_disable_llvm_passes));
+  A->claim();
+  continue;
+}
 DAL->append(A);
   }
   // Add default validator version if not set.
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3470,7 +3470,9 @@
 
 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
   types::ID InputType) {
-  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version};
+  const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
+ options::OPT_S, 
options::OPT_emit_llvm,
+ options::OPT_disable_llvm_passes};
 
   for (const auto &Arg : ForwardedArguments)
 if (const auto *A = Args.getLastArg(Arg))
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -6736,6 +6736,8 @@
 
 def dxc_Group : OptionGroup<"">, Flags<[DXCOption]>,
   HelpText<"dxc compatibility options">;
+class DXCFlag : Option<["/", "-"], name, KIND_FLAG>,
+  Group, Flags<[DXCOption, NoXarchOption]>;
 class DXCJoinedOrSeparate : Option<["/", "-"], name,
   KIND_JOINED_OR_SEPARATE>, Group, Flags<[DXCOption, 
NoXarchOption]>;
 
@@ -6760,3 +6762,8 @@
  "lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, lib_6_x,"
  "ms_6_5, ms_6_6, ms_6_7,"
  "as_6_5, as_6_6, as_6_7">;
+def emit_pristine_llvm : DXCFlag<"emit-pristine-llvm">,
+  HelpText<"Emit pristine LLVM IR from the frontend by not running any LLVM 
passes at all."
+   "Same as -S + -emit-llvm + -disable-llvm-passes.">;
+def fcgl : DXCFlag<"fcgl">, Alias,
+  HelpText<"Emit pristine LLVM IR from the frontend by not running any LLVM 
passes at all.">;


Index: clang/test/Driver/dxc_fcgl.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_fcgl.hlsl
@@ -0,0 +1,5 @@
+// RUN: %clang_dxc -fcgl foo.hlsl -### %s 2>&1 | FileCheck %s
+
+// Make sure fcgl option flag which translated into "-S" "-emit-llvm" "-disable-llvm-passes".
+// CHECK:"-S" "-emit-llvm" "-disable-llvm-passes"
+
Index: clang/lib/Driver/ToolChains/HLSL.cpp
===
--- clang/lib/Driver/ToolChains/HLSL.cpp
+++ clang/lib/Driver/ToolChains/HLSL.cpp
@@ -169,6 +169,15 @@
   if (!isLegalValidatorVersion(ValVerStr, getDriver()))
 continue;
 }
+if (A->getOption().getID() == options::OPT_emit_pristine_llvm) {
+  // Translate fcgl into -S -emit-llvm and -disable-llvm-passes.
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_S));
+  DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_emit_llvm));
+  DAL->AddFlagArg(nullptr,
+  Opts.getOption(options::OPT_disable_llvm_passes));
+  A->claim();
+  continue;
+}
 DAL->append(A);
   }
   // Add default validator version if not set.
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3470,7 +3470,9 @@
 
 static void RenderHLSLOptions(const ArgList &Args, ArgSt

[PATCH] D125078: Implement a feature to show line numbers in diagnostics

2022-05-06 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui created this revision.
Herald added a project: All.
ken-matsui requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

I implemented a feature to show line numbers with left margins in diagnostics 
like GCC-9 does. Ref: 
https://developers.redhat.com/blog/2019/03/08/usability-improvements-in-gcc-9


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125078

Files:
  clang/include/clang/Basic/DiagnosticOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
  clang/test/FixIt/fixit-newline-style.c
  clang/test/FixIt/fixit-unicode-with-utf8-output.c
  clang/test/FixIt/fixit-unicode.c
  clang/test/Frontend/diag-show-line-numbers.c
  clang/test/Frontend/source-col-map.c
  clang/test/Lexer/header.cpp
  clang/test/Lexer/string-literal-errors.cpp
  clang/test/Misc/caret-diags-macros.c
  clang/test/Misc/caret-diags-multiline.cpp
  clang/test/Misc/diag-macro-backtrace.c
  clang/test/Misc/message-length.c
  clang/test/Misc/tabstop.c
  clang/test/Misc/unnecessary-elipses.cpp
  clang/test/Misc/unprintable.c
  clang/test/Misc/wrong-encoding.c
  clang/test/Parser/brackets.c
  clang/test/Parser/brackets.cpp
  clang/test/Preprocessor/ucn-pp-identifier.c
  clang/test/SemaCXX/struct-class-redecl.cpp

Index: clang/test/SemaCXX/struct-class-redecl.cpp
===
--- clang/test/SemaCXX/struct-class-redecl.cpp
+++ clang/test/SemaCXX/struct-class-redecl.cpp
@@ -87,113 +87,113 @@
 /*
 *** 'X' messages ***
 CHECK: warning: struct 'X' was previously declared as a class
-CHECK: {{^}}typedef struct X * X_t;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}4 | typedef struct X * X_t;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class X;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}3 | class X;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: error: use of 'X' with tag type that does not match previous declaration
-CHECK: {{^}}union X { int x; float y; };
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}class{{$}}
+CHECK: {{^}}5 | union X { int x; float y; };
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | class{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class X;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}3 | class X;
+CHECK: {{^}}  |   ^{{$}}
 *** 'Y' messages ***
 CHECK: warning: 'Y' defined as a class template here but
   previously declared as a struct template
-CHECK: {{^}}template class Y { };
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}8 | template class Y { };
+CHECK: {{^}}  |   ^{{$}}
 CHECK: note: did you mean class here?
-CHECK: {{^}}template struct Y;
-CHECK: {{^}} ^~{{$}}
-CHECK: {{^}} class{{$}}
+CHECK: {{^}}7 | template struct Y;
+CHECK: {{^}}  |  ^~{{$}}
+CHECK: {{^}}  |  class{{$}}
 *** 'A' messages ***
 CHECK: warning: struct 'A' was previously declared as a class
-CHECK: {{^}}struct A;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   18 | struct A;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class A;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   17 | class A;
+CHECK: {{^}}  |   ^{{$}}
 *** 'B' messages ***
 CHECK: warning: struct 'B' was previously declared as a class
-CHECK: {{^}}struct B;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   23 | struct B;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class B;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   21 | class B;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: 'B' defined as a struct here but previously declared as a class
-CHECK: {{^}}struct B {};
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   24 | struct B {};
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: did you mean struct here?
-CHECK: {{^}}class B;
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}struct{{$}}
+CHECK: {{^}}   21 | class B;
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | struct{{$}}
 CHECK: note: did you mean struct here?
-CHECK: {{^}}class B;
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}struct{{$}}
+CHECK: {{^}}   20 | class B;
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | struct{{$}}
 *** 'C' messages ***
 CHECK: warning: struct 'C' was previously declared as a class
-CHECK: {{^}}struct C;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   27 | struct C;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class C;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   26 | class C;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: warning: class 'C' was previously declared as a struct
-CHECK: {{^}}class C;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   30 | class C;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}struct C;
-CHECK: {{^}}   ^{{$}}
+CHECK: {{^}}   27 | struct C;
+CHECK: {{^}}  |^{{$}}
 CHECK: warnin

[PATCH] D125078: Implement a feature to show line numbers in diagnostics

2022-05-06 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui updated this revision to Diff 427546.
ken-matsui added a comment.

Remove unnecessary includes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125078

Files:
  clang/include/clang/Basic/DiagnosticOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp
  clang/test/Analysis/Checkers/WebKit/uncounted-lambda-captures.cpp
  clang/test/FixIt/fixit-newline-style.c
  clang/test/FixIt/fixit-unicode-with-utf8-output.c
  clang/test/FixIt/fixit-unicode.c
  clang/test/Frontend/diag-show-line-numbers.c
  clang/test/Frontend/source-col-map.c
  clang/test/Lexer/header.cpp
  clang/test/Lexer/string-literal-errors.cpp
  clang/test/Misc/caret-diags-macros.c
  clang/test/Misc/caret-diags-multiline.cpp
  clang/test/Misc/diag-macro-backtrace.c
  clang/test/Misc/message-length.c
  clang/test/Misc/tabstop.c
  clang/test/Misc/unnecessary-elipses.cpp
  clang/test/Misc/unprintable.c
  clang/test/Misc/wrong-encoding.c
  clang/test/Parser/brackets.c
  clang/test/Parser/brackets.cpp
  clang/test/Preprocessor/ucn-pp-identifier.c
  clang/test/SemaCXX/struct-class-redecl.cpp

Index: clang/test/SemaCXX/struct-class-redecl.cpp
===
--- clang/test/SemaCXX/struct-class-redecl.cpp
+++ clang/test/SemaCXX/struct-class-redecl.cpp
@@ -87,113 +87,113 @@
 /*
 *** 'X' messages ***
 CHECK: warning: struct 'X' was previously declared as a class
-CHECK: {{^}}typedef struct X * X_t;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}4 | typedef struct X * X_t;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class X;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}3 | class X;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: error: use of 'X' with tag type that does not match previous declaration
-CHECK: {{^}}union X { int x; float y; };
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}class{{$}}
+CHECK: {{^}}5 | union X { int x; float y; };
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | class{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class X;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}3 | class X;
+CHECK: {{^}}  |   ^{{$}}
 *** 'Y' messages ***
 CHECK: warning: 'Y' defined as a class template here but
   previously declared as a struct template
-CHECK: {{^}}template class Y { };
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}8 | template class Y { };
+CHECK: {{^}}  |   ^{{$}}
 CHECK: note: did you mean class here?
-CHECK: {{^}}template struct Y;
-CHECK: {{^}} ^~{{$}}
-CHECK: {{^}} class{{$}}
+CHECK: {{^}}7 | template struct Y;
+CHECK: {{^}}  |  ^~{{$}}
+CHECK: {{^}}  |  class{{$}}
 *** 'A' messages ***
 CHECK: warning: struct 'A' was previously declared as a class
-CHECK: {{^}}struct A;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   18 | struct A;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class A;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   17 | class A;
+CHECK: {{^}}  |   ^{{$}}
 *** 'B' messages ***
 CHECK: warning: struct 'B' was previously declared as a class
-CHECK: {{^}}struct B;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   23 | struct B;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class B;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   21 | class B;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: 'B' defined as a struct here but previously declared as a class
-CHECK: {{^}}struct B {};
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   24 | struct B {};
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: did you mean struct here?
-CHECK: {{^}}class B;
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}struct{{$}}
+CHECK: {{^}}   21 | class B;
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | struct{{$}}
 CHECK: note: did you mean struct here?
-CHECK: {{^}}class B;
-CHECK: {{^}}^{{$}}
-CHECK: {{^}}struct{{$}}
+CHECK: {{^}}   20 | class B;
+CHECK: {{^}}  | ^{{$}}
+CHECK: {{^}}  | struct{{$}}
 *** 'C' messages ***
 CHECK: warning: struct 'C' was previously declared as a class
-CHECK: {{^}}struct C;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   27 | struct C;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}class C;
-CHECK: {{^}}  ^{{$}}
+CHECK: {{^}}   26 | class C;
+CHECK: {{^}}  |   ^{{$}}
 CHECK: warning: class 'C' was previously declared as a struct
-CHECK: {{^}}class C;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   30 | class C;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{^}}struct C;
-CHECK: {{^}}   ^{{$}}
+CHECK: {{^}}   27 | struct C;
+CHECK: {{^}}  |^{{$}}
 CHECK: warning: struct 'C' was previously declared as a class
-CHECK: {{^}}struct C;
-CHECK: {{^}}^{{$}}
+CHECK: {{^}}   32 | struct C;
+CHECK: {{^}}  | ^{{$}}
 CHECK: note: previous use is here
-CHECK: {{

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-05-06 Thread Balázs Benics via Phabricator via cfe-commits
steakhal reopened this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

This patch triggers a crash with this minimized example.
assertion at L205: `"The result operation type must have at least the same 
number of bits as its operands."`

  // build/bin/clang -cc1 -triple x86_64-unknown-linux-gnu -analyze 
-analyzer-checker=core,apiModeling repro.c
  
  typedef long ssize_t;
  ssize_t write(int, const void *, unsigned long);
  
  int crash(int x, int fd) {
unsigned wres = write(fd, "a", 1);
if (wres) {}
int t1 = x - wres;
if (wres < 0) {}
return x + t1;
  }

The debugger showed these values:

  op: BO_Sub
  resultTy: unsigned int
  resultIntTy.isUnsigned(): true
  Sym: reg
  RHSValue: APInt(64b, 18446744073709551615u -1s)
  resultIntTy.getBitWidth(): 32
  RHS.getBitWidth(): 64

Please investigate this @tomasz-kaminski-sonarsource


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D124435: [X86] Always extend the integer parameters in callee

2022-05-06 Thread LiuChen via Phabricator via cfe-commits
LiuChen3 updated this revision to Diff 427551.
LiuChen3 added a comment.

Use `-mextend-small-integers=` instead of boolean option


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124435

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/CodeGen/CGFunctionInfo.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/2007-06-18-SextAttrAggregate.c
  clang/test/CodeGen/X86/integer_argument_passing.c
  clang/test/CodeGen/X86/x86_32-arguments-darwin.c
  clang/test/CodeGen/X86/x86_32-arguments-linux.c
  clang/test/CodeGen/X86/x86_64-arguments-nacl.c
  clang/test/CodeGen/X86/x86_64-arguments.c
  clang/test/CodeGen/attr-noundef.cpp
  clang/test/CodeGen/builtin-align.c
  clang/test/CodeGen/catch-implicit-integer-sign-changes.c
  clang/test/CodeGen/ext-int-cc.c
  clang/test/CodeGen/function-attributes.c
  clang/test/CodeGen/mangle-windows.c
  clang/test/CodeGen/matrix-type-builtins.c
  clang/test/CodeGen/matrix-type-operators.c
  clang/test/CodeGen/ms-inline-asm.c
  clang/test/CodeGen/regcall.c
  clang/test/CodeGen/vectorcall.c
  clang/test/CodeGenCXX/exceptions.cpp
  clang/test/CodeGenCXX/ext-int.cpp
  clang/test/CodeGenCXX/microsoft-abi-eh-cleanups.cpp
  clang/test/CodeGenCXX/new-overflow.cpp
  clang/test/CodeGenCXX/virtual-bases.cpp
  clang/test/CodeGenObjC/property-atomic-bool.m
  clang/test/OpenMP/target_codegen_global_capture.cpp

Index: clang/test/OpenMP/target_codegen_global_capture.cpp
===
--- clang/test/OpenMP/target_codegen_global_capture.cpp
+++ clang/test/OpenMP/target_codegen_global_capture.cpp
@@ -2051,7 +2051,7 @@
 //
 //
 // CHECK3-LABEL: define {{[^@]+}}@_Z3foo
-// CHECK3-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK3-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK3-NEXT:  entry:
 // CHECK3-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK3-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -2335,7 +2335,7 @@
 //
 //
 // CHECK3-LABEL: define {{[^@]+}}@_Z3bar
-// CHECK3-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0]] {
+// CHECK3-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0]] {
 // CHECK3-NEXT:  entry:
 // CHECK3-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK3-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -2642,7 +2642,7 @@
 //
 //
 // CHECK3-LABEL: define {{[^@]+}}@_Z5tbar2
-// CHECK3-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0]] {
+// CHECK3-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0]] {
 // CHECK3-NEXT:  entry:
 // CHECK3-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK3-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -2661,7 +2661,7 @@
 //
 //
 // CHECK3-LABEL: define {{[^@]+}}@_Z4tbarIsEiT_S0_S0_S0_
-// CHECK3-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0]] comdat {
+// CHECK3-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0]] comdat {
 // CHECK3-NEXT:  entry:
 // CHECK3-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK3-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -2975,7 +2975,7 @@
 //
 //
 // CHECK4-LABEL: define {{[^@]+}}@_Z3foo
-// CHECK4-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK4-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK4-NEXT:  entry:
 // CHECK4-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK4-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -3259,7 +3259,7 @@
 //
 //
 // CHECK4-LABEL: define {{[^@]+}}@_Z3bar
-// CHECK4-SAME: (i16 noundef signext [[A:%.*]], i16 noundef signext [[B:%.*]], i16 noundef signext [[C:%.*]], i16 noundef signext [[D:%.*]]) #[[ATTR0]] {
+// CHECK4-SAME: (i16 noundef [[A:%.*]], i16 noundef [[B:%.*]], i16 noundef [[C:%.*]], i16 noundef [[D:%.*]]) #[[ATTR0]] {
 // CHECK4-NEXT:  entry:
 // CHECK4-NEXT:[[A_ADDR:%.*]] = alloca i16, align 2
 // CHECK4-NEXT:[[B_ADDR:%.*]] = alloca i16, align 2
@@ -3566,7 +3566,7 @@
 //
 //
 // CHECK4-LABEL: define {{[^@]+}}@_Z5tbar2
-// CHE

[PATCH] D125081: [FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR.

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: hokein, igor-laevsky.
Herald added subscribers: sdasgup3, wenzhicui, wrengr, Chia-hungDuan, dcaballe, 
cota, teijeong, rdzhabarov, tatianashp, msifontes, jurahul, Kayjukh, grosul1, 
Joonsoo, liufengdb, aartbik, mgester, arpith-jacob, antiagainst, shauheen, 
rriddle, mehdi_amini, usaxena95, kadircet, arphaman, hiraditya, mgorny.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, llvm-commits, stephenneuendorffer, 
nicolasvasilache.
Herald added projects: clang, MLIR, LLVM, clang-tools-extra.

All llvm-project fuzzers use this library to parse command-line arguments.
Many of them don't deal with LLVM IR or modules in any way. Bundling those
functions in one library forces build dependencies that don't need to be there.

Among other things, this means check-clang-pseudo no longer depends on most of
LLVM.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125081

Files:
  clang-tools-extra/clangd/fuzzer/CMakeLists.txt
  clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
  clang/tools/clang-fuzzer/CMakeLists.txt
  llvm/lib/FuzzMutate/CMakeLists.txt
  llvm/tools/llvm-dlang-demangle-fuzzer/CMakeLists.txt
  llvm/tools/llvm-isel-fuzzer/CMakeLists.txt
  llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt
  llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt
  llvm/tools/llvm-opt-fuzzer/CMakeLists.txt
  llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt
  llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt
  llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt
  mlir/tools/mlir-parser-fuzzer/CMakeLists.txt

Index: mlir/tools/mlir-parser-fuzzer/CMakeLists.txt
===
--- mlir/tools/mlir-parser-fuzzer/CMakeLists.txt
+++ mlir/tools/mlir-parser-fuzzer/CMakeLists.txt
@@ -1,5 +1,5 @@
 set(LLVM_LINK_COMPONENTS
-  FuzzMutate
+  FuzzerCLI
   Support
 )
 add_llvm_fuzzer(mlir-parser-fuzzer
Index: llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-yaml-numeric-parser-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Support
-  FuzzMutate
+  FuzzerCLI
 )
 
 add_llvm_fuzzer(llvm-yaml-numeric-parser-fuzzer
Index: llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-special-case-list-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Support
-  FuzzMutate
+  FuzzerCLI
 )
 
 add_llvm_fuzzer(llvm-special-case-list-fuzzer
Index: llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-rust-demangle-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Demangle
-  FuzzMutate
+  FuzzerCLI
   Support
 )
 
Index: llvm/tools/llvm-opt-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-opt-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-opt-fuzzer/CMakeLists.txt
@@ -14,6 +14,7 @@
   AggressiveInstCombine
   InstCombine
   Instrumentation
+  FuzzerCLI
   FuzzMutate
   MC
   ObjCARCOpts
Index: llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-microsoft-demangle-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Demangle
-  FuzzMutate
+  FuzzerCLI
   Support
 )
 
Index: llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-itanium-demangle-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Demangle
-  FuzzMutate
+  FuzzerCLI
   Support
 )
 
Index: llvm/tools/llvm-isel-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-isel-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-isel-fuzzer/CMakeLists.txt
@@ -9,6 +9,7 @@
 BitWriter
 CodeGen
 Core
+FuzzerCLI
 FuzzMutate
 IRReader
 MC
Index: llvm/tools/llvm-dlang-demangle-fuzzer/CMakeLists.txt
===
--- llvm/tools/llvm-dlang-demangle-fuzzer/CMakeLists.txt
+++ llvm/tools/llvm-dlang-demangle-fuzzer/CMakeLists.txt
@@ -1,6 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Demangle
-  FuzzMutate
+  FuzzerCLI
   Support
 )
 
Index: llvm/lib/FuzzMutate/CMakeLists.txt
===
--- llvm/lib/FuzzMutate/CMakeLists.txt
+++ llvm/lib/FuzzMutate/CMakeLists.txt
@@

[PATCH] D125082: [CMake] Include llvm-debuginfod-find in Fuchsia toolchain

2022-05-06 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added reviewers: mysterymath, haowei, leonardchan.
Herald added subscribers: abrachet, mgorny.
Herald added a project: All.
phosek requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125082

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -257,6 +257,7 @@
   llvm-bolt
   llvm-cov
   llvm-cxxfilt
+  llvm-debuginfod-find
   llvm-dlltool
   llvm-dwarfdump
   llvm-dwp


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -257,6 +257,7 @@
   llvm-bolt
   llvm-cov
   llvm-cxxfilt
+  llvm-debuginfod-find
   llvm-dlltool
   llvm-dwarfdump
   llvm-dwp
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125081: [FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR.

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

I'm happy to move FuzzerCLI to a separate directory (and avoid 
PARTIAL_SOURCES_INTENDED) if you prefer.

It's a bunch more mechanical changes and will break secondary build systems 
(gn, bazel), so if so let's agree on a name first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125081

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


[clang] a65afce - [flang][driver] Add support for -save-temps

2022-05-06 Thread Andrzej Warzynski via cfe-commits

Author: Andrzej Warzynski
Date: 2022-05-06T08:41:29Z
New Revision: a65afce731c2fa91effcfa5d4917d6ad90a28bf0

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

LOG: [flang][driver] Add support for -save-temps

This patch adds support for `-save-temps` in `flang-new`, Flang's
compiler driver. The semantics of this option are inherited from Clang.

The file extension for temporary Fortran preprocessed files is set to
`i`. This is identical to what Clang uses for C (or C++) preprocessed
files. I have tried researching what other compilers do here, but I
couldn't find any definitive answers. One GFortran thread [1] suggests
that indeed it is not clear what the right approach should be.

Normally, various phases in Clang/Flang are combined. The `-save-temps`
option works by forcing the compiler to run every phase separately. As
there is no integrated assembler driver in Flang, user will have to use
`-save-temps` together with `-fno-integrated-as`. Otherwise, an
invocation to the integrated assembler would be generated generated,
which is going to fail (i.e. something equivalent to `clang -cc1as` from
Clang).

There are no specific plans for implementing an integrated assembler for
Flang for now. One possible solution would be to share it entirely with
Clang.

Note that on Windows you will get the following error when using
`-fno-integrated-as`:
```bash
  flang-new: error: there is no external assembler that can be used on this 
platform
```
Unfortunately, I don't have access to a Windows machine to investigate
this. Instead, I marked the tests in this patch as unsupported on
Windows.

[1] https://gcc.gnu.org/bugzilla//show_bug.cgi?id=81615

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

Added: 
flang/test/Driver/fno-integrated-as.f90
flang/test/Driver/save-temps.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/include/clang/Driver/Types.def
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f4c34bcf5dea5..d9a4cb23a0934 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3995,9 +3995,9 @@ defm openmp_implicit_rpath: 
BoolFOption<"openmp-implicit-rpath",
   NegFlag>;
 def r : Flag<["-"], "r">, Flags<[LinkerInput,NoArgumentUnused]>,
 Group;
-def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[CC1Option, 
NoXarchOption]>,
+def save_temps_EQ : Joined<["-", "--"], "save-temps=">, Flags<[CC1Option, 
FlangOption, NoXarchOption]>,
   HelpText<"Save intermediate compilation results.">;
-def save_temps : Flag<["-", "--"], "save-temps">, Flags<[NoXarchOption]>,
+def save_temps : Flag<["-", "--"], "save-temps">, Flags<[FlangOption, 
NoXarchOption]>,
   Alias, AliasArgs<["cwd"]>,
   HelpText<"Save intermediate compilation results">;
 def save_stats_EQ : Joined<["-", "--"], "save-stats=">, Flags<[NoXarchOption]>,
@@ -4125,7 +4125,7 @@ def y : Joined<["-"], "y">;
 
 defm integrated_as : BoolFOption<"integrated-as",
   CodeGenOpts<"DisableIntegratedAS">, DefaultFalse,
-  NegFlag, PosFlag,
+  NegFlag, PosFlag,
   BothFlags<[], " the integrated assembler">>;
 
 def fintegrated_cc1 : Flag<["-"], "fintegrated-cc1">,
@@ -4137,7 +4137,7 @@ def fno_integrated_cc1 : Flag<["-"], 
"fno-integrated-cc1">,
 
 def : Flag<["-"], "integrated-as">, Alias, 
Flags<[NoXarchOption]>;
 def : Flag<["-"], "no-integrated-as">, Alias,
-  Flags<[CC1Option, NoXarchOption]>;
+  Flags<[CC1Option, FlangOption, NoXarchOption]>;
 
 def working_directory : JoinedOrSeparate<["-"], "working-directory">, 
Flags<[CC1Option]>,
   HelpText<"Resolve file paths relative to the specified directory">,

diff  --git a/clang/include/clang/Driver/Types.def 
b/clang/include/clang/Driver/Types.def
index 0cf265e05fedc..d00d520d7514c 100644
--- a/clang/include/clang/Driver/Types.def
+++ b/clang/include/clang/Driver/Types.def
@@ -77,7 +77,7 @@ TYPE("c++-module-cpp-output",PP_CXXModule, INVALID,   
  "iim",phases
 TYPE("ada",  Ada,  INVALID, nullptr,  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("assembler",PP_Asm,   INVALID, "s",  
phases::Assemble, phases::Link)
 TYPE("assembler-with-cpp",   Asm,  PP_Asm,  "S",  
phases::Preprocess, phases::Assemble, phases::Link)
-TYPE("f95",  PP_Fortran,   INVALID, nullptr,  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
+TYPE("f95",  PP_Fortran,   INVALID, "i",  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("f95-cpp-input",Fo

[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-06 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa65afce731c2: [flang][driver] Add support for -save-temps 
(authored by awarzynski).

Changed prior to commit:
  https://reviews.llvm.org/D124669?vs=427367&id=427561#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Types.def
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fno-integrated-as.f90
  flang/test/Driver/save-temps.f90

Index: flang/test/Driver/save-temps.f90
===
--- /dev/null
+++ flang/test/Driver/save-temps.f90
@@ -0,0 +1,55 @@
+! Tests for the `-save-temps` flag. As `flang` does not implement `-fc1as` (i.e. a driver for the integrated assembler), we need to
+! use `-fno-integrated-as` here.
+
+! UNSUPPORTED: system-windows
+
+!--
+! Basic case: `-save-temps`
+!--
+! RUN: %flang -save-temps -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK: "-o" "save-temps.i"
+! CHECK-NEXT: "-o" "save-temps.bc"
+! CHECK-NEXT: "-o" "save-temps.s"
+! CHECK-NEXT: "-o" "save-temps.o"
+! CHECK-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=cwd`
+!--
+! This should work the same as -save-temps above
+
+! RUN: %flang -save-temps=cwd -fno-integrated-as  %s -### 2>&1 | FileCheck %s -check-prefix=CWD
+! CWD: "-o" "save-temps.i"
+! CWD-NEXT: "-o" "save-temps.bc"
+! CWD-NEXT: "-o" "save-temps.s"
+! CWD-NEXT: "-o" "save-temps.o"
+! CWD-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=obj`
+!--
+! Check that temp files are saved in the same directory as the output file
+! regardless of whether -o is specified.
+
+! RUN: %flang -save-temps=obj -fno-integrated-as -o obj/dir/a.out %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ
+! CHECK-OBJ: "-o" "obj/dir/save-temps.i"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.bc"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.s"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.o"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/a.out"
+
+! RUN: %flang -save-temps=obj -fno-integrated-as %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+! CHECK-OBJ-NOO: "-o" "save-temps.i"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.bc"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.s"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.o"
+! CHECK-OBJ-NOO-NEXT: "-o" "a.out"
+
+!--
+! `-S` without `-save-temps`
+!--
+! Check for a single `flang -fc1` invocation when NOT using -save-temps.
+! RUN: %flang -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-TEMPS
+! NO-TEMPS: "-fc1"
+! NO-TEMPS-SAME: "-S"
+! NO-TEMPS-SAME: "-o" "save-temps.s"
Index: flang/test/Driver/fno-integrated-as.f90
===
--- /dev/null
+++ flang/test/Driver/fno-integrated-as.f90
@@ -0,0 +1,20 @@
+! Tests for the `-fno-integrated-as` flag.
+
+! UNSUPPORTED: system-windows
+
+!--
+! With `-fno-integrated-as`
+!--
+! Verify that there _is_ a separate line with an assembler invocation
+! RUN: %flang -c -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK-LABEL: "-fc1"
+! CHECK-SAME: "-o" "[[assembly_file:.*]].s"
+! CHECK-NEXT: "-o" "{{.*}}.o" "[[assembly_file:.*]].s"
+
+!-
+! Without `-fno-integrated-as`
+!-
+! Verify that there _is no_ separate line with an assembler invocation
+! RUN: %flang -c %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
+! DEFAULT-LABEL: "-fc1"
+! DEFAULT-SAME: "-o" "{{.*}}.o" "{{.*}}fno-integrated-as.f90"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -42,6 +42,7 @@
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
+! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -56,6 +57,8 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -save-temps=Save intermediate compilation results.
+! HELP-NEXT: -save-tempsSave intermediate compilation results
 ! HELP-NEXT: -std= 

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-05-06 Thread Mikael Holmén via Phabricator via cfe-commits
uabelho added a comment.

In D124658#3495973 , @steakhal wrote:

> This patch triggers a crash with this minimized example.
> assertion at L205: `"The result operation type must have at least the same 
> number of bits as its operands."`
> [...]
> Please investigate this @tomasz-kaminski-sonarsource

Hi,

I've stumbled on this crash as well with this patch.
So

  clang --analyze foo.c

crashes with

  clang: ../../clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp:207: 
clang::ento::SVal (anonymous namespace)::SimpleSValBuilder::MakeSymIntVal(const 
clang::ento::SymExpr *, BinaryOperator::Opcode, const llvm::APSInt &, 
clang::QualType): Assertion `resultIntTy.getBitWidth() >= RHS.getBitWidth() && 
"The result operation type must have at least the same " "number of bits as its 
operands."' failed.
  PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ 
and include the crash backtrace, preprocessed source, and associated run script.
  Stack dump:
  0.Program arguments: /repo/uabelho/master-github/llvm/build-all/bin/clang 
--analyze foo.c
  1. parser at end of file
  2.While analyzing stack: 
#0 Calling h
  3.foo.c:9:9: Error evaluating statement
  4.foo.c:9:9: Error evaluating statement
   #0 0x02e4fbf3 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x2e4fbf3)
   #1 0x02e4d86e llvm::sys::RunSignalHandlers() 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x2e4d86e)
   #2 0x02e4ef92 llvm::sys::CleanupOnSignal(unsigned long) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x2e4ef92)
   #3 0x02db4e03 (anonymous 
namespace)::CrashRecoveryContextImpl::HandleCrash(int, unsigned long) 
CrashRecoveryContext.cpp:0:0
   #4 0x02db4fbd CrashRecoverySignalHandler(int) 
CrashRecoveryContext.cpp:0:0
   #5 0x7fd21e2ce630 __restore_rt sigaction.c:0:0
   #6 0x7fd21ba15387 raise (/lib64/libc.so.6+0x36387)
   #7 0x7fd21ba16a78 abort (/lib64/libc.so.6+0x37a78)
   #8 0x7fd21ba0e1a6 __assert_fail_base (/lib64/libc.so.6+0x2f1a6)
   #9 0x7fd21ba0e252 (/lib64/libc.so.6+0x2f252)
  #10 0x0467e0bb (anonymous 
namespace)::SimpleSValBuilder::MakeSymIntVal(clang::ento::SymExpr const*, 
clang::BinaryOperatorKind, llvm::APSInt const&, clang::QualType) 
SimpleSValBuilder.cpp:0:0
  #11 0x0467a94f (anonymous 
namespace)::SimpleSValBuilder::evalBinOpNN(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::NonLoc, clang::ento::NonLoc, 
clang::QualType) SimpleSValBuilder.cpp:0:0
  #12 0x04688f46 
clang::ento::SValBuilder::evalBinOp(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::SVal, clang::ento::SVal, 
clang::QualType) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x4688f46)
  #13 0x0467f28e clang::ento::SymExprVisitor<(anonymous 
namespace)::SimpleSValBuilder::simplifySValOnce(llvm::IntrusiveRefCntPtr, clang::ento::SVal)::Simplifier, 
clang::ento::SVal>::Visit(clang::ento::SymExpr const*) SimpleSValBuilder.cpp:0:0
  #14 0x0467eccc (anonymous 
namespace)::SimpleSValBuilder::simplifySValOnce(llvm::IntrusiveRefCntPtr, clang::ento::SVal) SimpleSValBuilder.cpp:0:0
  #15 0x0467d814 (anonymous 
namespace)::SimpleSValBuilder::simplifySVal(llvm::IntrusiveRefCntPtr, clang::ento::SVal) SimpleSValBuilder.cpp:0:0
  #16 0x04679ec3 (anonymous 
namespace)::SimpleSValBuilder::evalBinOpNN(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::NonLoc, clang::ento::NonLoc, 
clang::QualType) SimpleSValBuilder.cpp:0:0
  #17 0x04688f46 
clang::ento::SValBuilder::evalBinOp(llvm::IntrusiveRefCntPtr, clang::BinaryOperatorKind, clang::ento::SVal, clang::ento::SVal, 
clang::QualType) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x4688f46)
  #18 0x045f509c 
clang::ento::ExprEngine::VisitBinaryOperator(clang::BinaryOperator const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x45f509c)
  #19 0x045e201a clang::ento::ExprEngine::Visit(clang::Stmt const*, 
clang::ento::ExplodedNode*, clang::ento::ExplodedNodeSet&) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x45e201a)
  #20 0x045dd27e clang::ento::ExprEngine::ProcessStmt(clang::Stmt 
const*, clang::ento::ExplodedNode*) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x45dd27e)
  #21 0x045dcf99 
clang::ento::ExprEngine::processCFGElement(clang::CFGElement, 
clang::ento::ExplodedNode*, unsigned int, clang::ento::NodeBuilderContext*) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x45dcf99)
  #22 0x045c5300 
clang::ento::CoreEngine::HandlePostStmt(clang::CFGBlock const*, unsigned int, 
clang::ento::ExplodedNode*) 
(/repo/uabelho/master-github/llvm/build-all/bin/clang+0x45c5300)
  #23 0x045c437a 
clang::ento::CoreEngine::ExecuteWorkList(clang::

[PATCH] D125084: [test, x86] Fix spurious x86-target-features.c failure

2022-05-06 Thread Thomas Preud'homme via Phabricator via cfe-commits
thopre created this revision.
thopre added reviewers: sconstab, craig.topper, andrew.w.kaylor, zbrid, 
chandlerc.
Herald added subscribers: StephenFan, pengfei.
Herald added a project: All.
thopre requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

x86-target-features.c can spuriously fail when checking for absence of
the string "lvi" in the compiler output due to the temporary path used
for the output file. For example:
"-o" "/tmp/lit-tmp-981j7lvi/x86-target-features-670b86.o"
will make the test fail. This commit checks specifically for lvi as a
target feature, in a similar way to the positive CHECK directive just
above.

Test Plan: fails when using -mlvi-hardening and pass otherwise


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125084

Files:
  clang/test/Driver/x86-target-features.c


Index: clang/test/Driver/x86-target-features.c
===
--- clang/test/Driver/x86-target-features.c
+++ clang/test/Driver/x86-target-features.c
@@ -170,7 +170,7 @@
 // RUN: %clang -target i386-linux-gnu -mlvi-hardening %s -### -o %t.o 2>&1 | 
FileCheck -check-prefix=LVIHARDENING %s
 // RUN: %clang -target i386-linux-gnu -mno-lvi-hardening %s -### -o %t.o 2>&1 
| FileCheck -check-prefix=NO-LVIHARDENING %s
 // LVIHARDENING: "-target-feature" "+lvi-load-hardening" "-target-feature" 
"+lvi-cfi"
-// NO-LVIHARDENING-NOT: lvi
+// NO-LVIHARDENING-NOT: "-target-feature" "+lvi
 
 // RUN: %clang -target i386-linux-gnu -mlvi-hardening 
-mspeculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck 
-check-prefix=LVIHARDENING-SLH %s
 // LVIHARDENING-SLH: error: invalid argument 'mspeculative-load-hardening' not 
allowed with 'mlvi-hardening'


Index: clang/test/Driver/x86-target-features.c
===
--- clang/test/Driver/x86-target-features.c
+++ clang/test/Driver/x86-target-features.c
@@ -170,7 +170,7 @@
 // RUN: %clang -target i386-linux-gnu -mlvi-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVIHARDENING %s
 // RUN: %clang -target i386-linux-gnu -mno-lvi-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-LVIHARDENING %s
 // LVIHARDENING: "-target-feature" "+lvi-load-hardening" "-target-feature" "+lvi-cfi"
-// NO-LVIHARDENING-NOT: lvi
+// NO-LVIHARDENING-NOT: "-target-feature" "+lvi
 
 // RUN: %clang -target i386-linux-gnu -mlvi-hardening -mspeculative-load-hardening %s -### -o %t.o 2>&1 | FileCheck -check-prefix=LVIHARDENING-SLH %s
 // LVIHARDENING-SLH: error: invalid argument 'mspeculative-load-hardening' not allowed with 'mlvi-hardening'
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123676: [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline.

2022-05-06 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius updated this revision to Diff 427566.
curdeius added a comment.

Simplify. Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

Files:
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23606,6 +23606,11 @@
 
   // Don't use the helpers here, since 'mess up' will change the whitespace
   // and these are all whitespace sensitive by definition
+
+  // Newlines are important here.
+  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
+  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
+
   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", 
Style));
   EXPECT_EQ(
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1787,7 +1787,8 @@
 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
 
 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
-tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
+tokenCanStartNewLine(*FormatTok) && Text == Text.upper() &&
+!PreviousToken->isTypeFinalized()) {
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -1027,7 +1027,10 @@
   Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
   tok::pp_define) &&
 it != Macros.end()) {
-  FormatTok->setType(it->second);
+  if (it->second == TT_UntouchableMacroFunc)
+FormatTok->setFinalizedType(TT_UntouchableMacroFunc);
+  else
+FormatTok->setType(it->second);
   if (it->second == TT_IfMacro) {
 // The lexer token currently has type tok::kw_unknown. However, for 
this
 // substitution to be treated correctly in the TokenAnnotator, faking


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23606,6 +23606,11 @@
 
   // Don't use the helpers here, since 'mess up' will change the whitespace
   // and these are all whitespace sensitive by definition
+
+  // Newlines are important here.
+  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
+  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
+
   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
   EXPECT_EQ(
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1787,7 +1787,8 @@
 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
 
 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
-tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
+tokenCanStartNewLine(*FormatTok) && Text == Text.upper() &&
+!PreviousToken->isTypeFinalized()) {
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -1027,7 +1027,10 @@
   Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
   tok::pp_define) &&
 it != Macros.end()) {
-  FormatTok->setType(it->second);
+  if (it->second == TT_UntouchableMacroFunc)
+FormatTok->setFinalizedType(TT_UntouchableMacroFunc);
+  else
+FormatTok->setType(it->second);
   if (it->second == TT_IfMacro) {
 // The lexer token currently has type tok::kw_unknown. However, for this
 // substitution to be treated correctly in the TokenAnnotator, faking
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-06 Thread Stefan Haller via Phabricator via cfe-commits
stefanhaller updated this revision to Diff 427567.
stefanhaller added a comment.

Updated the patch to have both Background and Low

As discussed, we provide both Background and Low now, with Low being the
default; Linux and Windows still implement both the same (as Background), this
could be changed as a followup, as I didn't feel comfortable touching these.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

Files:
  clang-tools-extra/clangd/index/Background.h
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/Support/Threading.h
  llvm/lib/Support/Unix/Threading.inc
  llvm/lib/Support/Windows/Threading.inc

Index: llvm/lib/Support/Windows/Threading.inc
===
--- llvm/lib/Support/Windows/Threading.inc
+++ llvm/lib/Support/Windows/Threading.inc
@@ -121,7 +121,7 @@
   // priorities of the thread as they were before the thread entered background
   // processing mode.
   return SetThreadPriority(GetCurrentThread(),
-   Priority == ThreadPriority::Background
+   Priority != ThreadPriority::Default
? THREAD_MODE_BACKGROUND_BEGIN
: THREAD_MODE_BACKGROUND_END)
  ? SetThreadPriorityResult::SUCCESS
Index: llvm/lib/Support/Unix/Threading.inc
===
--- llvm/lib/Support/Unix/Threading.inc
+++ llvm/lib/Support/Unix/Threading.inc
@@ -18,6 +18,7 @@
 #if defined(__APPLE__)
 #include 
 #include 
+#include 
 #endif
 
 #include 
@@ -258,27 +259,28 @@
   // SCHED_OTHER   the standard round-robin time-sharing policy;
   return !pthread_setschedparam(
  pthread_self(),
- Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
+ Priority == ThreadPriority::Default ? SCHED_OTHER : SCHED_IDLE,
  &priority)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #elif defined(__APPLE__)
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
-  // When setting a thread into background state the scheduling priority is set
-  // to lowest value, disk and network IO are throttled. Network IO will be
-  // throttled for any sockets the thread opens after going into background
-  // state. Any previously opened sockets are not affected.
-
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getiopolicy_np.3.html
-  // I/Os with THROTTLE policy are called THROTTLE I/Os. If a THROTTLE I/O
-  // request occurs within a small time window (usually a fraction of a second)
-  // of another NORMAL I/O request, the thread that issues the THROTTLE I/O is
-  // forced to sleep for a certain interval. This slows down the thread that
-  // issues the THROTTLE I/O so that NORMAL I/Os can utilize most of the disk
-  // I/O bandwidth.
-  return !setpriority(PRIO_DARWIN_THREAD, 0,
-  Priority == ThreadPriority::Background ? PRIO_DARWIN_BG
- : 0)
+  // https://developer.apple.com/documentation/apple-silicon/tuning-your-code-s-performance-for-apple-silicon
+  //
+  // Background - Applies to work that isn’t visible to the user and may take significant
+  // time to complete. Examples include indexing, backing up, or synchronizing data. This
+  // class emphasizes energy efficiency.
+  //
+  // Utility - Applies to work that takes anywhere from a few seconds to a few minutes to
+  // complete. Examples include downloading a document or importing data. This class
+  // offers a balance between responsiveness, performance, and energy efficiency.
+  const auto qosClass = [&](){
+switch (Priority) {
+  case ThreadPriority::Background: return QOS_CLASS_BACKGROUND;
+  case ThreadPriority::Low: return QOS_CLASS_UTILITY;
+  case ThreadPriority::Default: return QOS_CLASS_DEFAULT;
+}
+  }();
+  return !pthread_set_qos_class_self_np(qosClass, 0)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #endif
Index: llvm/include/llvm/Support/Threading.h
===
--- llvm/include/llvm/Support/Threading.h
+++ llvm/include/llvm/Support/Threading.h
@@ -233,15 +233,20 @@
   unsigned get_cpus();
 
   enum class ThreadPriority {
+/// Try to lower current thread's priority as much as possible. Can be used
+/// for long-running tasks that are not time critical; more energy-efficient
+/// than Low.
 Background = 0,
-Default = 1,
+
+/// Try to lower current thread's priority such that it does not affect
+/// foreground tasks significantly. This is a good default for long-running,
+/// latency

[PATCH] D123676: [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline.

2022-05-06 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius marked 5 inline comments as done.
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:23545
+  // Newlines are important here.
+  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
+  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));

curdeius wrote:
> owenpan wrote:
> > Do we really need this test case?
> Not really. I just wrote it to cover both cases but it's covered by existing 
> cases indeed. Will remove.
On a second thought, we don't have any other test with a semicolon and a 
newline, so I'd rather keep this test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[PATCH] D110685: [HIPSPV][4/4] Add option to use llc to emit SPIR-V

2022-05-06 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.
Herald added a subscriber: MaskRay.
Herald added a project: All.

I think it might make more sense to use the option `-fno-llvm-spirv` as we 
don't advertise `llc` as a tool to the developers but `llvm-spirv` we do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110685

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


[PATCH] D125085: [clang-format] Correctly handle SpaceBeforeParens for builtins.

2022-05-06 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

That's a partial fix for https://github.com/llvm/llvm-project/issues/55292.

Before, known builtins behaved differently from other identifiers:

  void f () { return F (__builtin_LINE() + __builtin_FOO ()); }

After:

  void f () { return F (__builtin_LINE () + __builtin_FOO ()); }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125085

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15082,6 +15082,9 @@
   // verifyFormat("X A::operator++ (T);", Space);
   verifyFormat("auto lambda = [] () { return 0; };", Space);
   verifyFormat("int x = int (y);", Space);
+  verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
+  verifyFormat("__builtin_LINE ()", Space);
+  verifyFormat("__builtin_UNKNOWN ()", Space);
 
   FormatStyle SomeSpace = getLLVMStyle();
   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3434,9 +3434,11 @@
 return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
 }
+// Handle builtins like identifiers.
 if (Line.Type != LT_PreprocessorDirective &&
-(Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
- Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier()))
+(Left.is(tok::identifier) || Left.Tok.getIdentifierInfo() ||
+ Left.isFunctionLikeKeyword() || Left.is(tok::r_paren) ||
+ Left.isSimpleTypeSpecifier()))
   return spaceRequiredBeforeParens(Right);
 return false;
   }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -15082,6 +15082,9 @@
   // verifyFormat("X A::operator++ (T);", Space);
   verifyFormat("auto lambda = [] () { return 0; };", Space);
   verifyFormat("int x = int (y);", Space);
+  verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
+  verifyFormat("__builtin_LINE ()", Space);
+  verifyFormat("__builtin_UNKNOWN ()", Space);
 
   FormatStyle SomeSpace = getLLVMStyle();
   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3434,9 +3434,11 @@
 return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
 }
+// Handle builtins like identifiers.
 if (Line.Type != LT_PreprocessorDirective &&
-(Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
- Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier()))
+(Left.is(tok::identifier) || Left.Tok.getIdentifierInfo() ||
+ Left.isFunctionLikeKeyword() || Left.is(tok::r_paren) ||
+ Left.isSimpleTypeSpecifier()))
   return spaceRequiredBeforeParens(Right);
 return false;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.

Thanks a lot, this version looks good to me and I'll follow up with a flag for 
clangd.

In D124715#3493493 , @stefanhaller 
wrote:

> In D124715#3491985 , @sammccall 
> wrote:
>
>> I'm still concerned some users will find this a large regression and we 
>> won't have a good workaround:
>>
>> - it'll use a lot more battery than before
>
> On Intel Macs, I'm not sure that's true. While it does saturate the CPUs 
> noticeably more with Utility than it does with Background, it will also be 
> finished much quicker, so I guess the total power consumption will probably 
> be roughly the same.

Yes, the issue is with workloads where it doesn't finish during the editor 
session, e.g. because indexing the full project takes hours.




Comment at: clang/tools/libclang/CIndex.cpp:9028
 #if LLVM_ENABLE_THREADS
-  llvm::set_thread_priority(llvm::ThreadPriority::Background);
+  llvm::set_thread_priority(llvm::ThreadPriority::Low);
 #endif

There's a mismatch between name and behavior here.

Could you add a comment explaining that setThreadBackgroundPriority name is for 
historical reasons, but Low is more appropriate?



Comment at: llvm/include/llvm/Support/Threading.h:236
   enum class ThreadPriority {
+/// Try to lower current thread's priority as much as possible. Can be used
+/// for long-running tasks that are not time critical; more 
energy-efficient

nit: I'd drop "try to" from each of these. 
The failure modes are to do with set_thread_priority rather than the enum, so 
the comment belongs there if at all (I think the return type covers it though).



Comment at: llvm/lib/Support/Unix/Threading.inc:259
   // SCHED_IDLEfor running very low priority background jobs.
   // SCHED_OTHER   the standard round-robin time-sharing policy;
   return !pthread_setschedparam(

Maybe add a FIXME: consider SCHED_BATCH for Low?



Comment at: llvm/lib/Support/Windows/Threading.inc:122
   // priorities of the thread as they were before the thread entered background
   // processing mode.
   return SetThreadPriority(GetCurrentThread(),

maybe add a FIXME: consider THREAD_PRIORITY_BELOW_NORMAL for Low?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

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


[PATCH] D125081: [FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR.

2022-05-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

This looks a reasonable split to me!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125081

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


[PATCH] D124091: [clang][AArch64][SVE] Implement conditional operator for SVE vectors

2022-05-06 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added a comment.

> I appreciate that I'm pulling your change out of a list of 80 without that 
> much evidence so if it's clearly not the issue just let me know.

My guess was incorrect, I've tracked this down to a different change. Sorry for 
the noise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124091

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


[PATCH] D124715: Use QoS class Utility for ThreadPriority::Low on Mac

2022-05-06 Thread Stefan Haller via Phabricator via cfe-commits
stefanhaller updated this revision to Diff 427577.
stefanhaller added a comment.

- Added a comment to setThreadBackgroundPriority
- Improved comments for ThreadPriority enum
- Add FIXME comments for Windows and Linux


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124715

Files:
  clang-tools-extra/clangd/index/Background.h
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/Support/Threading.h
  llvm/lib/Support/Unix/Threading.inc
  llvm/lib/Support/Windows/Threading.inc

Index: llvm/lib/Support/Windows/Threading.inc
===
--- llvm/lib/Support/Windows/Threading.inc
+++ llvm/lib/Support/Windows/Threading.inc
@@ -120,8 +120,10 @@
   // End background processing mode. The system restores the resource scheduling
   // priorities of the thread as they were before the thread entered background
   // processing mode.
+  //
+  // FIXME: consider THREAD_PRIORITY_BELOW_NORMAL for Low
   return SetThreadPriority(GetCurrentThread(),
-   Priority == ThreadPriority::Background
+   Priority != ThreadPriority::Default
? THREAD_MODE_BACKGROUND_BEGIN
: THREAD_MODE_BACKGROUND_END)
  ? SetThreadPriorityResult::SUCCESS
Index: llvm/lib/Support/Unix/Threading.inc
===
--- llvm/lib/Support/Unix/Threading.inc
+++ llvm/lib/Support/Unix/Threading.inc
@@ -18,6 +18,7 @@
 #if defined(__APPLE__)
 #include 
 #include 
+#include 
 #endif
 
 #include 
@@ -258,27 +259,29 @@
   // SCHED_OTHER   the standard round-robin time-sharing policy;
   return !pthread_setschedparam(
  pthread_self(),
- Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER,
+ // FIXME: consider SCHED_BATCH for Low
+ Priority == ThreadPriority::Default ? SCHED_OTHER : SCHED_IDLE,
  &priority)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #elif defined(__APPLE__)
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html
-  // When setting a thread into background state the scheduling priority is set
-  // to lowest value, disk and network IO are throttled. Network IO will be
-  // throttled for any sockets the thread opens after going into background
-  // state. Any previously opened sockets are not affected.
-
-  // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getiopolicy_np.3.html
-  // I/Os with THROTTLE policy are called THROTTLE I/Os. If a THROTTLE I/O
-  // request occurs within a small time window (usually a fraction of a second)
-  // of another NORMAL I/O request, the thread that issues the THROTTLE I/O is
-  // forced to sleep for a certain interval. This slows down the thread that
-  // issues the THROTTLE I/O so that NORMAL I/Os can utilize most of the disk
-  // I/O bandwidth.
-  return !setpriority(PRIO_DARWIN_THREAD, 0,
-  Priority == ThreadPriority::Background ? PRIO_DARWIN_BG
- : 0)
+  // https://developer.apple.com/documentation/apple-silicon/tuning-your-code-s-performance-for-apple-silicon
+  //
+  // Background - Applies to work that isn’t visible to the user and may take significant
+  // time to complete. Examples include indexing, backing up, or synchronizing data. This
+  // class emphasizes energy efficiency.
+  //
+  // Utility - Applies to work that takes anywhere from a few seconds to a few minutes to
+  // complete. Examples include downloading a document or importing data. This class
+  // offers a balance between responsiveness, performance, and energy efficiency.
+  const auto qosClass = [&](){
+switch (Priority) {
+  case ThreadPriority::Background: return QOS_CLASS_BACKGROUND;
+  case ThreadPriority::Low: return QOS_CLASS_UTILITY;
+  case ThreadPriority::Default: return QOS_CLASS_DEFAULT;
+}
+  }();
+  return !pthread_set_qos_class_self_np(qosClass, 0)
  ? SetThreadPriorityResult::SUCCESS
  : SetThreadPriorityResult::FAILURE;
 #endif
Index: llvm/include/llvm/Support/Threading.h
===
--- llvm/include/llvm/Support/Threading.h
+++ llvm/include/llvm/Support/Threading.h
@@ -233,15 +233,20 @@
   unsigned get_cpus();
 
   enum class ThreadPriority {
+/// Lower the current thread's priority as much as possible. Can be used
+/// for long-running tasks that are not time critical; more energy-
+/// efficient than Low.
 Background = 0,
-Default = 1,
+
+/// Lower the current thread's priority such that it does not affect
+/// foreground tasks significantly. This 

[PATCH] D123243: [pseudo] Strip directives from a token stream

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/lib/DirectiveTree.cpp:373
+case DirectiveTree::Chunk::K_Empty:
+  break;
+}

hokein wrote:
> return, otherwise we we hit the unreachable code below.
That's deliberate, K_Empty is invalid.



Comment at: clang-tools-extra/pseudo/tool/ClangPseudo.cpp:40
+static opt
+Preprocess("preprocess",
+   desc("Strip directives and select conditional sections"));

hokein wrote:
> `preprocess` seems a little confusing (the name reminds me of the traditional 
> preprocessor process where comments are stripped, but not in our case here). 
> may be `strip-directives` but it doesn't reflect the conditional-#if token 
> work, but I think it is fine.
> 
> This flag is a feature-control flag for `print-source` and `print-tokens`, 
> can we group three of them together?
> may be strip-directives but it doesn't reflect the conditional-#if token 
> work, but I think it is fine

Agreed, renamed it.

> This flag is a feature-control flag for print-source and print-tokens, can we 
> group three of them together?

It's not really, it also affects the GLR parser etc.
Generally I think we should try to make the flags in this tool more orthogonal 
rather than clustering them by effects. Thematically it's more closely related 
to -print-directive-tree.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123243

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


[PATCH] D123243: [pseudo] Strip directives from a token stream

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 427581.
sammccall marked an inline comment as done.
sammccall added a comment.

rebase
add include to testcase
rename preprocess => strip-includes, and testcase
move print directivetree test to strip-includes.c
fix tests to not cook before parsing directivetree


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123243

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
  clang-tools-extra/pseudo/lib/DirectiveTree.cpp
  clang-tools-extra/pseudo/test/lex.c
  clang-tools-extra/pseudo/test/strip-directives.c
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp

Index: clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
===
--- clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
+++ clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
@@ -27,14 +27,23 @@
 using testing::StrEq;
 using Chunk = DirectiveTree::Chunk;
 
-MATCHER_P2(tokensAre, TS, Tokens, "tokens are " + std::string(Tokens)) {
+// Matches text of a list of tokens against a string (joined with spaces).
+// e.g. EXPECT_THAT(Stream.tokens(), tokens("int main ( ) { }"));
+MATCHER_P(tokens, Tokens, "") {
   std::vector Texts;
-  for (const Token &Tok : TS.tokens(arg.Tokens))
+  for (const Token &Tok : arg)
 Texts.push_back(Tok.text());
   return Matcher(StrEq(Tokens))
   .MatchAndExplain(llvm::join(Texts, " "), result_listener);
 }
 
+// Matches tokens covered a directive chunk (with a Tokens property) against a
+// string, similar to tokens() above.
+// e.g. EXPECT_THAT(SomeDirective, tokensAre(Stream, "# include < vector >"));
+MATCHER_P2(tokensAre, TS, Tokens, "tokens are " + std::string(Tokens)) {
+  return testing::Matches(tokens(Tokens))(TS.tokens(arg.Tokens));
+}
+
 MATCHER_P(chunkKind, K, "") { return arg.kind() == K; }
 
 TEST(DirectiveTree, Parse) {
@@ -301,6 +310,45 @@
   }
 }
 
+TEST(DirectiveTree, StripDirectives) {
+  LangOptions Opts;
+  std::string Code = R"cpp(
+#include 
+a a a
+#warning AAA
+b b b
+#if 1
+  c c c
+  #warning BBB
+  #if 0
+d d d
+#warning CC
+  #else
+e e e
+  #endif
+  f f f
+  #if 0
+g g g
+  #endif
+  h h h
+#else
+  i i i
+#endif
+j j j
+  )cpp";
+  TokenStream S = lex(Code, Opts);
+
+  DirectiveTree Tree = DirectiveTree::parse(S);
+  chooseConditionalBranches(Tree, S);
+  EXPECT_THAT(Tree.stripDirectives(S).tokens(),
+  tokens("a a a b b b c c c e e e f f f h h h j j j"));
+
+  const DirectiveTree &Part =
+  ((const DirectiveTree::Conditional &)Tree.Chunks[4]).Branches[0].second;
+  EXPECT_THAT(Part.stripDirectives(S).tokens(),
+  tokens("c c c e e e f f f h h h"));
+}
+
 } // namespace
 } // namespace pseudo
 } // namespace clang
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
+using clang::pseudo::TokenStream;
 using llvm::cl::desc;
 using llvm::cl::init;
 using llvm::cl::opt;
@@ -37,6 +38,9 @@
 static opt
 PrintDirectiveTree("print-directive-tree",
   desc("Print directive structure of source code"));
+static opt
+StripDirectives("strip-directives",
+desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
 
@@ -58,22 +62,30 @@
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
   llvm::Optional RawStream;
-  llvm::Optional DirectiveStructure;
+  llvm::Optional PreprocessedStream;
   llvm::Optional ParseableStream;
   if (Source.getNumOccurrences()) {
 SourceText = readOrDie(Source);
 RawStream = clang::pseudo::lex(SourceText, LangOpts);
-DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
-clang::pseudo::chooseConditionalBranches(*DirectiveStructure, *RawStream);
+TokenStream *Stream = RawStream.getPointer();
+
+auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
+clang::pseudo::chooseConditionalBranches(DirectiveStructure, *RawStream);
+
+llvm::Optional Preprocessed;
+if (StripDirectives) {
+  Preprocessed = DirectiveStructure.stripDirectives(*Stream);
+  Stream = Preprocessed.getPointer();
+}
 
-if (PrintDirectiveTree)
-  llvm::outs() << DirectiveStructure;
 if (PrintSource)
-  RawStream->print(llvm::outs());
+  Stream->print(llvm::outs());
 if (PrintTokens)
-  llvm::outs() << RawStream;
+  

[clang] da5b5ae - Revert "[analyzer] Canonicalize SymIntExpr so the RHS is positive when possible"

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

Author: Balazs Benics
Date: 2022-05-06T12:13:51+02:00
New Revision: da5b5ae852c45236620e1dd8d498b2c49fa5c855

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

LOG: Revert "[analyzer] Canonicalize SymIntExpr so the RHS is positive when 
possible"

It seems like multiple users are affected by a crash introduced by this
commit, thus I'm reverting it for the time being.
Read more about the found reproducers at Phabricator.

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

This reverts commit f0d6cb4a5cf5723d7ddab2c7dab74f2f62116a6d.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
clang/test/Analysis/expr-inspection.c

Removed: 
clang/test/Analysis/additive-op-on-sym-int-expr.c



diff  --git a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp 
b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
index 27e474866c297..65c2564637c18 100644
--- a/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ b/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -197,27 +197,8 @@ SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
   if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
 }
-  } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
-// Change a+(-N) into a-N, and a-(-N) into a+N
-// Adjust addition/subtraction of negative value, to
-// subtraction/addition of the negated value.
-APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
-assert(resultIntTy.getBitWidth() >= RHS.getBitWidth() &&
-   "The result operation type must have at least the same "
-   "number of bits as its operands.");
-
-llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
-// Check if the negation of the RHS is representable:
-// * if resultIntTy is unsigned, then negation is always representable
-// * if resultIntTy is signed, and RHS is not the lowest representable
-//   signed value
-if (resultIntTy.isUnsigned() || !ConvertedRHSValue.isMinSignedValue()) {
-  ConvertedRHS = &BasicVals.getValue(-ConvertedRHSValue);
-  op = (op == BO_Add) ? BO_Sub : BO_Add;
-}
-  } else {
+  } else
 ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
-  }
 
   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
 }
@@ -655,27 +636,16 @@ SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
   const llvm::APSInt &first = 
IntType.convert(symIntExpr->getRHS());
   const llvm::APSInt &second = IntType.convert(*RHSValue);
 
-  // If the op and lop agrees, then we just need to
-  // sum the constants. Otherwise, we change to operation
-  // type if substraction would produce negative value
-  // (and cause overflow for unsigned integers),
-  // as consequence x+1U-10 produces x-9U, instead
-  // of x+4294967287U, that would be produced without this
-  // additional check.
   const llvm::APSInt *newRHS;
-  if (lop == op) {
+  if (lop == op)
 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
-  } else if (first >= second) {
+  else
 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
-op = lop;
-  } else {
-newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
-  }
 
   assert(newRHS && "Invalid operation despite common type!");
   rhs = nonloc::ConcreteInt(*newRHS);
   lhs = nonloc::SymbolVal(symIntExpr->getLHS());
-
+  op = lop;
   continue;
 }
   }

diff  --git a/clang/test/Analysis/additive-op-on-sym-int-expr.c 
b/clang/test/Analysis/additive-op-on-sym-int-expr.c
deleted file mode 100644
index c9385f58c980f..0
--- a/clang/test/Analysis/additive-op-on-sym-int-expr.c
+++ /dev/null
@@ -1,58 +0,0 @@
-// RUN: %clang_analyze_cc1 -triple=x86_64-unknown-linux 
-analyzer-checker=core,debug.ExprInspection -analyzer-config 
eagerly-assume=false -verify %s
-
-void clang_analyzer_dump(int);
-void clang_analyzer_dumpL(long);
-void clang_analyzer_warnIfReached();
-
-void testInspect(int x) {
-  if ((x < 10) || (x > 100)) {
-return;
-  }
-  // x: [10, 100]
-
-  int i = x + 1;
-  long l = i - 10U;
-  clang_analyzer_dump(i);   // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }}
-  clang_analyzer_dumpL(l);  // expected-warning-re {{(reg_${{[0-9]+}}) - 9U }} instead of + 4294967287U
-  clang_analyzer_dumpL(l + 0L); // expected-warning-re {{(reg_${{[0-9]+}}) - 9 }}  instead of + 4294967287
-
-  if ((l - 1000) > 0) {
-clang_analyzer_warnIfReached(); // n

[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-05-06 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGda5b5ae852c4: Revert "[analyzer] Canonicalize 
SymIntExpr so the RHS is positive when possible" (authored by steakhal).

Changed prior to commit:
  https://reviews.llvm.org/D124658?vs=427340&id=427582#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

Files:
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
  clang/test/Analysis/additive-op-on-sym-int-expr.c
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -11,7 +11,7 @@
 
 void foo(int x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
-  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) - 1}}
+  clang_analyzer_dump(x + (-1)); // expected-warning{{(reg_$0) + -1}}
   int y = 1;
   for (; y < 3; ++y) {
 clang_analyzer_numTimesReached(); // expected-warning{{2}}
Index: clang/test/Analysis/additive-op-on-sym-int-expr.c
===
--- clang/test/Analysis/additive-op-on-sym-int-expr.c
+++ /dev/null
@@ -1,58 +0,0 @@
-// RUN: %clang_analyze_cc1 -triple=x86_64-unknown-linux -analyzer-checker=core,debug.ExprInspection -analyzer-config eagerly-assume=false -verify %s
-
-void clang_analyzer_dump(int);
-void clang_analyzer_dumpL(long);
-void clang_analyzer_warnIfReached();
-
-void testInspect(int x) {
-  if ((x < 10) || (x > 100)) {
-return;
-  }
-  // x: [10, 100]
-
-  int i = x + 1;
-  long l = i - 10U;
-  clang_analyzer_dump(i);   // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }}
-  clang_analyzer_dumpL(l);  // expected-warning-re {{(reg_${{[0-9]+}}) - 9U }} instead of + 4294967287U
-  clang_analyzer_dumpL(l + 0L); // expected-warning-re {{(reg_${{[0-9]+}}) - 9 }}  instead of + 4294967287
-
-  if ((l - 1000) > 0) {
-clang_analyzer_warnIfReached(); // no-warning
-  }
-  if (l > 1000) {
-clang_analyzer_warnIfReached(); // no-warning
-  }
-  if (l > 1000L) {
-clang_analyzer_warnIfReached(); // no-warning
-  }
-  if ((l + 0L) > 1000) {
-clang_analyzer_warnIfReached(); // no-warning
-  }
-
-  i = x - 1;
-  l = i + 10U;
-  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) + 9U }} instead of - 4294967287U
-
-  i = x + (-1);
-  l = i - 10U;
-  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) - 11U }} instead of + 4294967285U
-
-  i = x + 1U;
-  l = i - 10U;
-  clang_analyzer_dumpL(l); // expected-warning-re {{(reg_${{[0-9]+}}) - 9U }} instead of + 4294967287U
-}
-
-void testMin(int i, long l) {
-  clang_analyzer_dump(i + (-1));  // expected-warning-re {{(reg_${{[0-9]+}}) - 1 }} instead of + -1
-  clang_analyzer_dump(i - (-1));  // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }} instead of - -1
-  clang_analyzer_dumpL(l + (-1)); // expected-warning-re {{(reg_${{[0-9]+}}) - 1 }} instead of + -1
-  clang_analyzer_dumpL(l - (-1)); // expected-warning-re {{(reg_${{[0-9]+}}) + 1 }} instead of - -1
-
-  int intMin = 1 << (sizeof(int) * 8 - 1); // INT_MIN, negative value is not representable
-  // Do not normalize representation if negation would not be representable
-  clang_analyzer_dump(i + intMin); // expected-warning-re {{(reg_${{[0-9]+}}) + -2147483648 }}
-  clang_analyzer_dump(i - intMin); // expected-warning-re {{(reg_${{[0-9]+}}) - -2147483648 }}
-  // Produced value has higher bit with (long) so negation if representable
-  clang_analyzer_dumpL(l + intMin); // expected-warning-re {{(reg_${{[0-9]+}}) - 2147483648 }} instead of + -2147483648
-  clang_analyzer_dumpL(l - intMin); // expected-warning-re {{(reg_${{[0-9]+}}) + 2147483648 }} instead of - -2147483648
-}
Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -197,27 +197,8 @@
   if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
 }
-  } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
-// Change a+(-N) into a-N, and a-(-N) into a+N
-// Adjust addition/subtraction of negative value, to
-// subtraction/addition of the negated value.
-APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
-assert(resultIntTy.getBitWidth() >= RHS.getBitWidth() &&
-   "The result operation type must have at least the same "
-   "number of bits as its operands.");
-
-llvm::APSInt ConvertedRHSValue = resultIntTy.convert(RHS);
-// Check if the negation of the RHS is representable:
-// * if resultIntTy is unsigned, then negation is always representable
-// * if resultIntTy is s

[clang-tools-extra] 7dc3c61 - [pseudo] Strip directives from a token stream

2022-05-06 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-05-06T12:15:08+02:00
New Revision: 7dc3c6190ec7191dd104fa5158fe0ee32e9b0c49

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

LOG: [pseudo] Strip directives from a token stream

This includes only the taken branch of conditional sections.
The API allows for producing a stream for a particular PP branch, which
will be used later for the secondary GLR parses of not-taken branches.

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

Added: 
clang-tools-extra/pseudo/test/strip-directives.c

Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
clang-tools-extra/pseudo/lib/DirectiveTree.cpp
clang-tools-extra/pseudo/test/lex.c
clang-tools-extra/pseudo/tool/ClangPseudo.cpp
clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
index 5cd41efcb2ace..e8220537649f9 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
@@ -92,7 +92,11 @@ struct DirectiveTree {
   /// Extract preprocessor structure by examining the raw tokens.
   static DirectiveTree parse(const TokenStream &);
 
-  // FIXME: allow deriving a preprocessed stream
+  /// Produce a parseable token stream by stripping all directive tokens.
+  ///
+  /// Conditional sections are replaced by the taken branch, if any.
+  /// This tree must describe the provided token stream.
+  TokenStream stripDirectives(const TokenStream &) const;
 };
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DirectiveTree &);
 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DirectiveTree::Chunk 
&);

diff  --git a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp 
b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
index f464e3bc3ba66..82843125329b8 100644
--- a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
+++ b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp
@@ -347,5 +347,53 @@ void chooseConditionalBranches(DirectiveTree &Tree, const 
TokenStream &Code) {
   BranchChooser{Code}.choose(Tree);
 }
 
+namespace {
+class Preprocessor {
+  const TokenStream &In;
+  TokenStream &Out;
+
+public:
+  Preprocessor(const TokenStream &In, TokenStream &Out) : In(In), Out(Out) {}
+  ~Preprocessor() { Out.finalize(); }
+
+  void walk(const DirectiveTree &T) {
+for (const auto &C : T.Chunks)
+  walk(C);
+  }
+
+  void walk(const DirectiveTree::Chunk &C) {
+switch (C.kind()) {
+case DirectiveTree::Chunk::K_Code:
+  return walk((const DirectiveTree::Code &)C);
+case DirectiveTree::Chunk::K_Directive:
+  return walk((const DirectiveTree::Directive &)C);
+case DirectiveTree::Chunk::K_Conditional:
+  return walk((const DirectiveTree::Conditional &)C);
+case DirectiveTree::Chunk::K_Empty:
+  break;
+}
+llvm_unreachable("bad chunk kind");
+  }
+
+  void walk(const DirectiveTree::Code &C) {
+for (const auto &Tok : In.tokens(C.Tokens))
+  Out.push(Tok);
+  }
+
+  void walk(const DirectiveTree::Directive &) {}
+
+  void walk(const DirectiveTree::Conditional &C) {
+if (C.Taken)
+  walk(C.Branches[*C.Taken].second);
+  }
+};
+} // namespace
+
+TokenStream DirectiveTree::stripDirectives(const TokenStream &In) const {
+  TokenStream Out;
+  Preprocessor(In, Out).walk(*this);
+  return Out;
+}
+
 } // namespace pseudo
 } // namespace clang

diff  --git a/clang-tools-extra/pseudo/test/lex.c 
b/clang-tools-extra/pseudo/test/lex.c
index c1bf9296a8cce..ebebd2e0fb72f 100644
--- a/clang-tools-extra/pseudo/test/lex.c
+++ b/clang-tools-extra/pseudo/test/lex.c
@@ -18,7 +18,7 @@ SOURCE-NEXT: #end
 SOURCE-NEXT: }
 
 RUN: clang-pseudo -source %s -print-tokens | FileCheck %s -check-prefix=TOKEN
- TOKEN:   0: raw_identifier   0:0 "int" flags=1
+ TOKEN: 0: raw_identifier 0:0 "int" flags=1
 TOKEN-NEXT: raw_identifier   0:0 "is_debug"
 TOKEN-NEXT: l_paren  0:0 "("
 TOKEN-NEXT: r_paren  0:0 ")"
@@ -39,14 +39,4 @@ TOKEN-NEXT: hash 5:0 "#" flags=1
 TOKEN-NEXT: raw_identifier   5:0 "endif"
 TOKEN-NEXT: r_brace  6:0 "}" flags=1
 
-RUN: clang-pseudo -source %s -print-directive-tree | FileCheck %s 
-check-prefix=PPT --strict-whitespace
- PPT: code (5 tokens)
-PPT-NEXT: #ifndef (3 tokens) TAKEN
-PPT-NEXT:   code (4 tokens)
-PPT-NEXT: #else (2 tokens)
-PPT-NEXT:   code (3 tokens)
-PPT-NEXT: #endif (2 tokens)
-PPT-NEXT: code (2 tokens)
-^ including this block comment
-
 
***/

diff  --git a/clang-tools-extra/pseudo/test/strip-directives.c 
b/clang-tools-extra/pseudo/test/strip-dir

[PATCH] D123243: [pseudo] Strip directives from a token stream

2022-05-06 Thread Sam McCall 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 rG7dc3c6190ec7: [pseudo] Strip directives from a token stream 
(authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123243

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h
  clang-tools-extra/pseudo/lib/DirectiveTree.cpp
  clang-tools-extra/pseudo/test/lex.c
  clang-tools-extra/pseudo/test/strip-directives.c
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp
  clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp

Index: clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
===
--- clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
+++ clang-tools-extra/pseudo/unittests/DirectiveTreeTest.cpp
@@ -27,14 +27,23 @@
 using testing::StrEq;
 using Chunk = DirectiveTree::Chunk;
 
-MATCHER_P2(tokensAre, TS, Tokens, "tokens are " + std::string(Tokens)) {
+// Matches text of a list of tokens against a string (joined with spaces).
+// e.g. EXPECT_THAT(Stream.tokens(), tokens("int main ( ) { }"));
+MATCHER_P(tokens, Tokens, "") {
   std::vector Texts;
-  for (const Token &Tok : TS.tokens(arg.Tokens))
+  for (const Token &Tok : arg)
 Texts.push_back(Tok.text());
   return Matcher(StrEq(Tokens))
   .MatchAndExplain(llvm::join(Texts, " "), result_listener);
 }
 
+// Matches tokens covered a directive chunk (with a Tokens property) against a
+// string, similar to tokens() above.
+// e.g. EXPECT_THAT(SomeDirective, tokensAre(Stream, "# include < vector >"));
+MATCHER_P2(tokensAre, TS, Tokens, "tokens are " + std::string(Tokens)) {
+  return testing::Matches(tokens(Tokens))(TS.tokens(arg.Tokens));
+}
+
 MATCHER_P(chunkKind, K, "") { return arg.kind() == K; }
 
 TEST(DirectiveTree, Parse) {
@@ -301,6 +310,45 @@
   }
 }
 
+TEST(DirectiveTree, StripDirectives) {
+  LangOptions Opts;
+  std::string Code = R"cpp(
+#include 
+a a a
+#warning AAA
+b b b
+#if 1
+  c c c
+  #warning BBB
+  #if 0
+d d d
+#warning CC
+  #else
+e e e
+  #endif
+  f f f
+  #if 0
+g g g
+  #endif
+  h h h
+#else
+  i i i
+#endif
+j j j
+  )cpp";
+  TokenStream S = lex(Code, Opts);
+
+  DirectiveTree Tree = DirectiveTree::parse(S);
+  chooseConditionalBranches(Tree, S);
+  EXPECT_THAT(Tree.stripDirectives(S).tokens(),
+  tokens("a a a b b b c c c e e e f f f h h h j j j"));
+
+  const DirectiveTree &Part =
+  ((const DirectiveTree::Conditional &)Tree.Chunks[4]).Branches[0].second;
+  EXPECT_THAT(Part.stripDirectives(S).tokens(),
+  tokens("c c c e e e f f f h h h"));
+}
+
 } // namespace
 } // namespace pseudo
 } // namespace clang
Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
+using clang::pseudo::TokenStream;
 using llvm::cl::desc;
 using llvm::cl::init;
 using llvm::cl::opt;
@@ -37,6 +38,9 @@
 static opt
 PrintDirectiveTree("print-directive-tree",
   desc("Print directive structure of source code"));
+static opt
+StripDirectives("strip-directives",
+desc("Strip directives and select conditional sections"));
 static opt PrintStatistics("print-statistics", desc("Print GLR parser statistics"));
 static opt PrintForest("print-forest", desc("Print parse forest"));
 
@@ -58,22 +62,30 @@
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
   llvm::Optional RawStream;
-  llvm::Optional DirectiveStructure;
+  llvm::Optional PreprocessedStream;
   llvm::Optional ParseableStream;
   if (Source.getNumOccurrences()) {
 SourceText = readOrDie(Source);
 RawStream = clang::pseudo::lex(SourceText, LangOpts);
-DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
-clang::pseudo::chooseConditionalBranches(*DirectiveStructure, *RawStream);
+TokenStream *Stream = RawStream.getPointer();
+
+auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
+clang::pseudo::chooseConditionalBranches(DirectiveStructure, *RawStream);
+
+llvm::Optional Preprocessed;
+if (StripDirectives) {
+  Preprocessed = DirectiveStructure.stripDirectives(*Stream);
+  Stream = Preprocessed.getPointer();
+}
 
-if (PrintDirectiveTree)
-  llvm::outs() << DirectiveStructure;
 if (PrintSource)
-  RawStream->print(llvm::outs());
+  Stream->print(llvm::outs());
 if (PrintTokens)
-  llvm::outs() << RawStream;
+  llvm::outs() << *Stream;
+if (PrintDirectiveTree)
+  llv

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

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a subscriber: ldionne.
sammccall added a comment.

In D121838#3470478 , @ldionne wrote:

> I think @phosek is the right person to look at this. I looked at it and it 
> seems fine, but I don't know how the runtimes tests are setup well enough to 
> spot an issue if there were one.
>
> Nit: I'd suggest rebasing and re-uploading the patch so that the runtimes CI 
> can run again (and hopefully pass -- there was a flake last time).

OK. I was requesting extra reviews because of the libc++ herald policy.
But since the changes are mechanical/cross-cutting, phosek isn't a libc++ 
approver, and there hasn't been more activity here I'm going to try to get this 
landed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

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


[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

2022-05-06 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

Looks good to me.

Will it work with `-fno-openmp`? Sometimes `-fno-openmp` is used by the 
end-user to override system provided `-fopenmp` flag for some translation units.

Please have a look at following examples:

  // RUN: %clang -### -target x86_64-linux-gnu \
  // RUN:   --offload-arch=gfx906 \
  // RUN:   %s 2>&1 | FileCheck -check-prefix=OFFLOAD %s
  // OFFLOAD: warning: argument unused during compilation: 
'--offload-arch=gfx906'
  
  // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
  // RUN:   --offload-arch=gfx906 \
  // RUN:   -fno-openmp \
  // RUN:   %s 2>&1 | FileCheck -check-prefix=OFFLOAD1 %s
  // OFFLOAD1: warning: argument unused during compilation: 
'--offload-arch=gfx906'
  
  // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
  // RUN:   -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa \
  // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 \
  // RUN:   -fno-openmp \
  // RUN:   %s 2>&1 | FileCheck -check-prefix=LEGACY %s
  // LEGACY: warning: '-fopenmp-targets' must be used in conjunction with a 
'-fopenmp' option compatible with offloading; e.g., '-fopenmp=libomp' or 
'-fopenmp=libiomp5'
  // LEGACY-NEXT: warning: argument unused during compilation: 
'-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906'
  
  // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
  // RUN:   --offload-arch=gfx906 \
  // RUN:   --offload-arch=gfx908 \
  // RUN:   -fno-openmp \
  // RUN:   %s 2>&1 | FileCheck -check-prefix=MOFFLOAD %s
  // MOFFLOAD: warning: argument unused during compilation: 
'--offload-arch=gfx906'
  // MOFFLOAD-NEXT: warning: argument unused during compilation: 
'--offload-arch=gfx908'
  
  // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
  // RUN:   -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa \
  // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 \
  // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx908 \
  // RUN:   -fno-openmp \
  // RUN:   %s 2>&1 | FileCheck -check-prefix=MLEGACY %s
  // MLEGACY: warning: '-fopenmp-targets' must be used in conjunction with a 
'-fopenmp' option compatible with offloading; e.g., '-fopenmp=libomp' or 
'-fopenmp=libiomp5'
  // MLEGACY: warning: argument unused during compilation: 
'-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906'
  // MLEGACY: warning: argument unused during compilation: 
'-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx908'


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

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


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

2022-05-06 Thread Sam McCall via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7cc8377f2c57: Generalize "check-all" umbrella 
targets, use for check-clang-tools (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121838

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/test/CMakeLists.txt
  clang/CMakeLists.txt
  clang/bindings/python/tests/CMakeLists.txt
  clang/runtime/CMakeLists.txt
  compiler-rt/test/CMakeLists.txt
  llvm/CMakeLists.txt
  llvm/cmake/modules/AddLLVM.cmake
  llvm/runtimes/CMakeLists.txt
  runtimes/CMakeLists.txt
  runtimes/Tests.cmake.in

Index: runtimes/Tests.cmake.in
===
--- runtimes/Tests.cmake.in
+++ runtimes/Tests.cmake.in
@@ -1,3 +1,3 @@
-set(SUB_LIT_TESTSUITES @RUNTIMES_LIT_TESTSUITES@)
-set(SUB_LIT_PARAMS @RUNTIMES_LIT_PARAMS@)
-set(SUB_LIT_EXTRA_ARGS @RUNTIMES_LIT_EXTRA_ARGS@)
+set(SUB_LIT_TESTSUITES @LLVM_RUNTIMES_LIT_TESTSUITES@)
+set(SUB_LIT_PARAMS @LLVM_RUNTIMES_LIT_PARAMS@)
+set(SUB_LIT_EXTRA_ARGS @LLVM_RUNTIMES_LIT_EXTRA_ARGS@)
Index: runtimes/CMakeLists.txt
===
--- runtimes/CMakeLists.txt
+++ runtimes/CMakeLists.txt
@@ -176,6 +176,8 @@
 set(LIT_ARGS_DEFAULT "${LIT_ARGS_DEFAULT} --no-progress-bar")
   endif()
   set(LLVM_LIT_ARGS "${LIT_ARGS_DEFAULT}" CACHE STRING "Default options for lit")
+
+  umbrella_lit_testsuite_begin(check-runtimes)
 endif()
 
 # llvm-libgcc incorporates both compiler-rt and libunwind as subprojects with very
@@ -200,36 +202,13 @@
 foreach(entry ${runtimes})
   get_filename_component(projName ${entry} NAME)
 
-  # Between each sub-project we want to cache and clear the LIT properties
-  set_property(GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
-  set_property(GLOBAL PROPERTY LLVM_LIT_PARAMS)
-  set_property(GLOBAL PROPERTY LLVM_LIT_DEPENDS)
-  set_property(GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
-
   add_subdirectory(${entry} ${projName})
-
-  get_property(LLVM_LIT_TESTSUITES GLOBAL PROPERTY LLVM_LIT_TESTSUITES)
-  get_property(LLVM_LIT_PARAMS GLOBAL PROPERTY LLVM_LIT_PARAMS)
-  get_property(LLVM_LIT_DEPENDS GLOBAL PROPERTY LLVM_LIT_DEPENDS)
-  get_property(LLVM_LIT_EXTRA_ARGS GLOBAL PROPERTY LLVM_LIT_EXTRA_ARGS)
-
-  list(APPEND RUNTIMES_LIT_TESTSUITES ${LLVM_LIT_TESTSUITES})
-  list(APPEND RUNTIMES_LIT_PARAMS ${LLVM_LIT_PARAMS})
-  list(APPEND RUNTIMES_LIT_DEPENDS ${LLVM_LIT_DEPENDS})
-  list(APPEND RUNTIMES_LIT_EXTRA_ARGS ${LLVM_LIT_EXTRA_ARGS})
 endforeach()
 
 if(LLVM_INCLUDE_TESTS)
   # Add a global check rule now that all subdirectories have been traversed
   # and we know the total set of lit testsuites.
-  add_lit_target(check-runtimes
-"Running all regression tests"
-${RUNTIMES_LIT_TESTSUITES}
-PARAMS ${RUNTIMES_LIT_PARAMS}
-DEPENDS ${RUNTIMES_LIT_DEPENDS}
-ARGS ${RUNTIMES_LIT_EXTRA_ARGS}
-)
-  add_custom_target(runtimes-test-depends DEPENDS ${RUNTIMES_LIT_DEPENDS})
+  umbrella_lit_testsuite_end(check-runtimes)
 
   if (NOT HAVE_LLVM_LIT)
 # If built by manually invoking cmake on this directory, we don't have
Index: llvm/runtimes/CMakeLists.txt
===
--- llvm/runtimes/CMakeLists.txt
+++ llvm/runtimes/CMakeLists.txt
@@ -222,9 +222,9 @@
   if(LLVM_INCLUDE_TESTS)
 include(${LLVM_BINARY_DIR}/runtimes/Tests.cmake OPTIONAL)
 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${LLVM_BINARY_DIR}/runtimes/Tests.cmake)
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${SUB_LIT_PARAMS})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_PARAMS ${SUB_LIT_PARAMS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
 list(APPEND test_targets runtimes-test-depends check-runtimes)
   endif()
 
@@ -304,9 +304,9 @@
   if(LLVM_INCLUDE_TESTS)
 include(${LLVM_BINARY_DIR}/runtimes/${name}/Tests.cmake OPTIONAL)
 set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${LLVM_BINARY_DIR}/runtimes/${name}/Tests.cmake)
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_PARAMS ${SUB_LIT_PARAMS})
-set_property(GLOBAL APPEND PROPERTY LLVM_LIT_EXTRA_ARGS ${SUB_LIT_EXTRA_ARGS})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_TESTSUITES ${SUB_LIT_TESTSUITES})
+set_property(GLOBAL APPEND PROPERTY LLVM_ALL_LIT_PARAMS ${SUB_LIT_PARAMS})
+set_property(GLOBAL APPEND PR

[PATCH] D124525: [OpenMP][ClangLinkerWrapper] Extending linker wrapper to embed metadata for multi-arch fat binaries

2022-05-06 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

In D124525#3491170 , @jhuber6 wrote:

> I'm suggesting instead we define a new `__tgt_device_image` and a new 
> `__tgt_register_lib` function to support this. This new `__tgt_device_image` 
> will simply contain a pointer to an optional information struct.
>
>   struct __tgt_device_image_v2 {
> void* ImageStart;
> void* ImageEnd;
> __tgt_offload_entry*  EntriesBegin;
> __tgt_offload_entry*  EntriesEnd;
> __tgt_image_into*  ImageInfo;
>   };
>
> This new struct breaks the ABI with the old `__tgt_device_image` because 
> these are put into an array and we change the size, but we should be able to 
> provide backwards compatibility by copying from the old format to the new 
> format and creating a new array. We can detect the new vs. old ABI by 
> expecting that existing applications will call the `__tgt_register_image` 
> function. We will create a new `__tgt_register_image_v2` function for example 
> that all new programs will call. In `libomptarget` we then change 
> `__tgt_register_image` to do the necessary translation.
>
>   struct __tgt_bin_desc { 
>   
>
> int32_t NumDeviceImages;   // Number of device types supported
>   
>  
> __tgt_device_image *DeviceImages;  // Array of device images (1 per dev. 
> type)
> __tgt_offload_entry *HostEntriesBegin; // Begin of table with all host 
> entries   
> __tgt_offload_entry *HostEntriesEnd;   // End of table (non inclusive)
>   
>  
>   };
>   
>   EXTERN void __tgt_register_lib(__tgt_bin_desc *desc) {
> __tgt_device_image_v2 *new_image = alloc_new_version(desc);
> desc->DeviceImages = new_Image;
> __tgt_register_lib_v2(desc);
>   }
>   
>   EXTERN void __tgt_unregister_lib(__tgt_bin_desc *desc) {
> __tgt_unregister_lib_v2(desc);
> dealloc(desc->DeviceImages);
>   }
>
> Now the rest of `libomptarget` solely uses the new format, and we check if 
> information is available by seeing that the `ImageInfo` field is non-null.

Thanks for the input. I am going to try it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124525

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


[PATCH] D124658: [analyzer] Canonicalize SymIntExpr so the RHS is positive when possible

2022-05-06 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource added a comment.

I am looking into the crashes. The simplest solution is to not apply 
normalization in such a situation, and I am slowly converting to that solution. 
But, want to understand better how such values are produced in the first case, 
and if performing normalization would make sense in such case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124658

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


[PATCH] D125012: [clang] createInvocationFromCommandLine -> createInvocation, delete former. NFC

2022-05-06 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125012

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-06 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added a comment.

In D124674#3491710 , @NoQ wrote:

> Yes, we've discussed this before, and I'm very much in favor of this change. 
> This is assertion removal, and the assertion has been really useful back in 
> the day, but the assertion doesn't seem to be realistic to maintain with all 
> the new logic in the constraint solver coming in in recent years.

Thanks for your review and support!




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:88
   GenericDataMap   GDM;  // Custom data stored by a client of this class.
+  bool Infeasible = false;
   unsigned refCount;

NoQ wrote:
> The reader deserves a massive amount of explanation here. Normally infeasible 
> states are just null states. We need to explain how these new infeasible 
> states are different.
> 
> Maybe a longer name? `IsPostOverconstrained` or something like that.
Okay, I've added an essay that explains these differences.

> Maybe a longer name? IsPostOverconstrained or something like that.
Yeah, I agree a longer name could reflect that this is something that requires 
special handling. I chose `PosteriorlyOverconstrained`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-06 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 427594.
martong marked an inline comment as done.
martong added a comment.

- Add explanatory comment, rename to PosteriorlyOverconstrained


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/test/Analysis/infeasible-sink.c

Index: clang/test/Analysis/infeasible-sink.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-sink.c
@@ -0,0 +1,80 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test that if it turns out that the parent state is infeasible then
+// both children States (more precisely the ExplodedNodes) are marked as a
+// Sink.
+// We rely on existing defects of the underlying constraint solver. However,
+// in the future we might strengthen the solver to discover the infeasibility
+// right when we create the parent state. At that point some of these tests
+// will fail, and either we shall find another solver weakness to have the test
+// case functioning, or we shall simply remove that.
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+void test1(int x) {
+  if (x * x != 4)
+return;
+  if (x < 0 || x > 1)
+return;
+
+  // { x^2 == 4 and x:[0,1] }
+  // This state is already infeasible.
+
+  // Perfectly constraining 'x' will trigger constant folding,
+  // when we realize we were already infeasible.
+  // The same happens for the 'else' branch.
+  if (x == 0) {
+clang_analyzer_warnIfReached(); // no-warning
+  } else {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+  (void)x;
+}
+
+int a, b, c, d, e;
+void test2() {
+
+  if (a == 0)
+return;
+
+  if (e != c)
+return;
+
+  d = e - c;
+  b = d;
+  a -= d;
+
+  if (a != 0)
+return;
+
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK
+return;
+  }
+  // Should not be reachable.
+  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
+  */
+
+  // The parent state is already infeasible, but we realize that only if b is
+  // constrained.
+  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -55,7 +55,7 @@
 
 ProgramState::ProgramState(const ProgramState &RHS)
 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
-  refCount(0) {
+  PosteriorlyOverconstrained(RHS.PosteriorlyOverconstrained), refCount(0) {
   stateMgr->getStoreManager().incrementReferenceCount(store);
 }
 
@@ -429,6 +429,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
+ProgramStateRef ProgramState::cloneAsPosteriorlyOverconstrained() const {
+  ProgramState NewSt(*this);
+  NewSt.PosteriorlyOverconstrained = true;
+  return getStateManager().getPersistentState(NewSt);
+}
+
 void ProgramState::setStore(const StoreRef &newStore) {
   Store newStoreStore = newStore.getStore();
   if (newStoreStore)
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -41,3 +41,32 @@
 return ConditionTruthVal(true);
   return {};
 }
+
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  ProgramStateRef StTrue = assume(State, Cond, true);
+
+  if (!StTrue) {
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
+  ProgramStateRef StInfeasible = State->cloneAsPosteriorlyOverconstrained();
+  assert(StInfeasible->isPosteriorlyO

[PATCH] D125085: [clang-format] Correctly handle SpaceBeforeParens for builtins.

2022-05-06 Thread Nathan Sidwell via Phabricator via cfe-commits
urnathan added a comment.

cool


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125085

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


[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

2022-05-06 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 marked an inline comment as done.
jhuber6 added a comment.

In D125050#3496289 , @saiislam wrote:

> Looks good to me.
>
> Will it work with `-fno-openmp`? Sometimes `-fno-openmp` is used by the 
> end-user to override system provided `-fopenmp` flag for some translation 
> units.
>
> Please have a look at following examples:
>
>   // RUN: %clang -### -target x86_64-linux-gnu \
>   // RUN:   --offload-arch=gfx906 \
>   // RUN:   %s 2>&1 | FileCheck -check-prefix=OFFLOAD %s
>   // OFFLOAD: warning: argument unused during compilation: 
> '--offload-arch=gfx906'
>   
>   // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
>   // RUN:   --offload-arch=gfx906 \
>   // RUN:   -fno-openmp \
>   // RUN:   %s 2>&1 | FileCheck -check-prefix=OFFLOAD1 %s
>   // OFFLOAD1: warning: argument unused during compilation: 
> '--offload-arch=gfx906'
>   
>   // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
>   // RUN:   -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa \
>   // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 \
>   // RUN:   -fno-openmp \
>   // RUN:   %s 2>&1 | FileCheck -check-prefix=LEGACY %s
>   // LEGACY: warning: '-fopenmp-targets' must be used in conjunction with a 
> '-fopenmp' option compatible with offloading; e.g., '-fopenmp=libomp' or 
> '-fopenmp=libiomp5'
>   // LEGACY-NEXT: warning: argument unused during compilation: 
> '-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906'
>   
>   // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
>   // RUN:   --offload-arch=gfx906 \
>   // RUN:   --offload-arch=gfx908 \
>   // RUN:   -fno-openmp \
>   // RUN:   %s 2>&1 | FileCheck -check-prefix=MOFFLOAD %s
>   // MOFFLOAD: warning: argument unused during compilation: 
> '--offload-arch=gfx906'
>   // MOFFLOAD-NEXT: warning: argument unused during compilation: 
> '--offload-arch=gfx908'
>   
>   // RUN: %clang -### -target x86_64-linux-gnu -fopenmp\
>   // RUN:   -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa \
>   // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 \
>   // RUN:   -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx908 \
>   // RUN:   -fno-openmp \
>   // RUN:   %s 2>&1 | FileCheck -check-prefix=MLEGACY %s
>   // MLEGACY: warning: '-fopenmp-targets' must be used in conjunction with a 
> '-fopenmp' option compatible with offloading; e.g., '-fopenmp=libomp' or 
> '-fopenmp=libiomp5'
>   // MLEGACY: warning: argument unused during compilation: 
> '-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906'
>   // MLEGACY: warning: argument unused during compilation: 
> '-Xopenmp-target=amdgcn-amd-amdhsa -march=gfx908'

It should, I could add a simple test for that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

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


[PATCH] D124977: [NFC][Clang] Modify expect of fail test or XFAIL because CSKY align is different

2022-05-06 Thread Renato Golin via Phabricator via cfe-commits
rengolin added inline comments.



Comment at: clang/test/Sema/builtin-alloca-with-align.c:32
 void test8(void) {
+#if defined(__csky__)
   __builtin_alloca_with_align(sizeof(__INT64_TYPE__), 
__alignof__(__INT64_TYPE__)); // expected-warning {{second argument to 
__builtin_alloca_with_align is supposed to be in bits}}

This test is platform agnostic, perhaps the extra error could be in a new test, 
exclusively for csky?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124977

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


[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

2022-05-06 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 427599.
jhuber6 added a comment.

Add test for disabling openmp with `-fno-openmp`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-infer.c

Index: clang/test/Driver/openmp-offload-infer.c
===
--- /dev/null
+++ clang/test/Driver/openmp-offload-infer.c
@@ -0,0 +1,50 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN:  --offload-arch=sm_52 --offload-arch=gfx803 \
+// RUN:  --libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgpu-gfx803.bc \
+// RUN:  --libomptarget-nvptx-bc-path=%S/Inputs/libomptarget/libomptarget-nvptx-test.bc %s 2>&1 \
+// RUN:   | FileCheck %s
+
+// verify the tools invocations
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-llvm-bc"{{.*}}"-x" "c"
+// CHECK: "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "gfx803"
+// CHECK: "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "sm_52"
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-obj"
+// CHECK: clang-linker-wrapper{{.*}}"--"{{.*}} "-o" "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908:sramecc+:xnack- \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-NVIDIA-AMDGPU
+
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[HOST_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "amdgcn-amd-amdhsa" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[AMD_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[NVIDIA_PTX:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[NVIDIA_PTX]]"], output: "[[NVIDIA_CUBIN:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[AMD_BC]]", "[[NVIDIA_CUBIN]]"], output: "[[HOST_OBJ:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-ARCH-BINDINGS
+
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_52]]"], output: "[[DEVICE_OBJ_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_70]]"], output: "[[DEVICE_OBJ_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[DEVICE_OBJ_SM_52]]", "[[DEVICE_OBJ_SM_70]]"], output: "[[HOST_OBJ:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908 --offload-arch=native \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-FAILED
+
+// CHECK-FAILED: error: failed to deduce triple for target architecture 'native'; specify the triple using '-fopenmp-targets' and '-Xopenmp-target' instead.
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908 -fno-openmp \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-DISABLED
+
+// CHECK-DISABLED-NOT: "nvptx64-nvidia-cuda" - "clang",
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7003,20 +7003,13 @@
   // For all the host OpenMP offloading compile jobs we need to pass the targets
   // information using -fopenmp-targets= option.
   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
-SmallString<128> TargetInfo("-fopenmp-targets=");
-
-Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
-  

[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

It looks like there's still something not quite right because it's warning on 
some instances but not others and I'm not certain why. Can you investigate?




Comment at: clang/test/Preprocessor/line-directive.c:33-34
 # 42 "foo" 2 // expected-error {{invalid line marker flag '2': cannot pop 
empty include stack}}
 # 42 "foo" 1 3  // enter
 # 42 "foo" 2 3  // exit
 # 42 "foo" 2 3 4 // expected-error {{invalid line marker flag '2': cannot pop 
empty include stack}}

Something is still not quite correct -- these should also be diagnosed as an 
extension (it's the same feature just with flags).



Comment at: clang/test/Preprocessor/line-directive.c:61
 
 # 192 "glomp.h" 3 // System header.
 typedef int y;  // ok

This should also be diagnosed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[PATCH] D124382: [Clang] Recognize target address space in superset calculation

2022-05-06 Thread Jakub Chlanda via Phabricator via cfe-commits
jchlanda added a comment.

@Anastasia @tra apologies for a late reply, I'm catching up with the thread 
after holidays.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124382

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


[PATCH] D124382: [Clang] Recognize target address space in superset calculation

2022-05-06 Thread Jakub Chlanda via Phabricator via cfe-commits
jchlanda added a comment.

In D124382#3480600 , @Anastasia wrote:

> 



> And I think we could add this feature in a very light way for example by 
> reserving the numbers from the clang `LangAS` enum to be used with the 
> language address spaces in the prototypes of builtins.

I'm not sure I understand how that would look, could you please elaborate?

> Just to understand further - do you need the builtins to have a specific 
> address space prototype? And do you need this to improve error handling in 
> libclc code base?

With the wrappers suggested we could declare all the pointers to be in generic 
AS and that would get us around the target vs language AS problem. I don't 
think that would improve the situation, as from llvm perspective/use case all 
those builtins would be incorrect and there would be no way for users to tell 
that there is a specific AS requirement on them, nor would the compiler be able 
to warn/error. Then the only thing making it work would be those wrappers, 
embedded deeply in the source of libclc, which at the moment is not even 
shipped with upstream llvm.
The builtins in question are not exclusively OpenCL/SYCL related, say 
`TARGET_BUILTIN(__nvvm_cp_async_ca_shared_global_16, "vv*3vC*1", "", 
AND(SM_80,PTX70))` would need to take both pointer in a generic address space 
here. It feels like explicitly providing AS in the prototype is needed.

> this for example won’t work for builtins that are shared between targets.

While I agree in principle, I'm not sure if there are any target agnostic and 
AS specific builtins, sounds like a dangerous thing to introduce. And in any 
case, it's the target that provides the AS map.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124382

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


[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

2022-05-06 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

only a few typos




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:89-114
+  // A state is infeasible if there is a contradiction among the constraints.
+  // An infeasible state is represented by a nullptr.
+  // In the sense of `assumeDual`, a state can have two children by adding a
+  // new constraint and the negation of that new constraint. A parent state is
+  // over-constrained if both of its children are infeasible. In the
+  // mathematical sense it means that the parent is infeasible and we should
+  // have realised that at the moment when we have created it. However, we




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124382: [Clang] Recognize target address space in superset calculation

2022-05-06 Thread Jakub Chlanda via Phabricator via cfe-commits
jchlanda added inline comments.



Comment at: clang/include/clang/AST/Type.h:486
+   bool IsSYCLOrOpenCL = false) {
+if (ASMap) {
+  bool IsATargetAS = false;

tra wrote:
> If A and B are both target AS, we fall through to the code which is dealing 
> with language AS, which would not do us any good. If that's not expected to 
> happen, we should have an assert to ensure it.
> 
> Next, I'm not particularly fond of `IsSYCLOrOpenCL`. Do we need it at all. If 
> we do know that AS maps to OpenCL `Constant` or `Generic`, I would assume 
> that those AS would follow the same semantics. Besides, will we ever see 
> OpenCL language AS in non-OpenCL code?
> 
> Next, the function *is* OpenCL specific and would not work for CUDA or HIP. I 
> think it needs to be generalized to provide language-specific AS mapping 
> rules.
I would only like to handle the mixed AS case, it feels like trying to walk 
back from both HW AS and potentially do the logic of global and constant would 
be against the intention of users. Asserting on only one HW AS could backfire, 
as I think it should be allowed to assign between different HW AS.

The reason I added `IsSYCLOrOpenCL` is because this code is also exercised by 
`checkPointerTypesForAssignment` which is not OpenCL specific, so I had to have 
a way of conditionally enabling the conversion to generic AS.

I agree, it is too restrictive now, especially that the AS map provides values 
for SYCL, OpenCL and CUDA, so perhaps I should extend `IsSYCLOrOpenCL` to be an 
enum specifying which language the function deals with and act accordingly?




Comment at: clang/include/clang/AST/Type.h:489
+  bool IsBTargetAS = false;
+  if (A > LangAS::FirstTargetAddressSpace)
+IsATargetAS = true;

tra wrote:
> Is the check intended to tell if A is a target AS? If so, we do have 
> `isTargetAddressSpace()` for that (and it uses '>= 
> LangAS::FirstTargetAddressSpace', which suggests that `>` may be incorrect, 
> too).
Yeap, will update to `isTargetAddressSpace`.




Comment at: clang/include/clang/AST/Type.h:498-499
+LangAS Constant = static_cast(
+(*ASMap)[static_cast(LangAS::opencl_constant)] +
+static_cast(LangAS::FirstTargetAddressSpace));
+if (IsATargetAS)

tra wrote:
> `getLangASFromTargetAS((*ASMap)[static_cast(LangAS::opencl_constant)])`
>  
OK.



Comment at: clang/include/clang/AST/Type.h:500
+static_cast(LangAS::FirstTargetAddressSpace));
+if (IsATargetAS)
+  B = static_cast(

tra wrote:
> `if (!IsBTargetAS)` would be more directly related to what we're doing here.
You are right, will update.



Comment at: clang/include/clang/AST/Type.h:508
+  static_cast(LangAS::FirstTargetAddressSpace));
+// When dealing with target AS return true if:
+// * A is equal to B, or

tra wrote:
> Is the code above intended to ensure that both A and B are target AS at this 
> point?
> If so, then it could be simplified to something like this:
> ```
> if (ASMap) {
>   if (!isTargetAddressSpace(A))
> A = getLangASFromTargetAS((*ASMap)[static_cast(A)]);
>   if (!isTargetAddressSpace(B))
> B = getLangASFromTargetAS((*ASMap)[static_cast(B)]);
> 
>   Generic = 
> getLangASFromTargetAS((*ASMap)[static_cast(LangAS::opencl_generic)])
>   Constant = 
> getLangASFromTargetAS((*ASMap)[static_cast(LangAS::opencl_constant)]);
> 
>   // ... proceed inferring whether A is superset of B in target AS.
>   return;
> }
> assert (isTargetAddressSpace(A) && isTargetAddressSpace(B));
> ```
Yes at the end of AS map accesses all address spaces have to be expressed in 
therms of HW values, but I want it to happen only in the case of mixed AS 
(Language and HW). I will add assert and use helpers, like you suggested in the 
snippet, but would like to keep the `^` condition.



Comment at: clang/lib/Sema/SemaExpr.cpp:9204
+  const LangASMap &ASMap = S.Context.getTargetInfo().getAddressSpaceMap();
+  if (!lhq.compatiblyIncludes(rhq, &ASMap)) {
+const bool AddressSpaceSuperset = Qualifiers::isAddressSpaceSupersetOf(

tra wrote:
> Should you pass `IsSYCLOrOpenCL` to it too? The way 
> `isAddressSpaceSupersetOf` is implemented now it may give you a different 
> result without it. 
> 
> Also, it may make sense to plumb ASMap into `lhq.isAddressSpaceSupersetOf`, 
> too, and just use the old code + couple of new arguments.
Yes, will add.

I thought it would introduce much bigger diff, and there was already a handy 
`static` version of it, don't mind modifying the member if you'd prefer.



Comment at: clang/lib/Sema/SemaExpr.cpp:9219
 // and from void*.
-else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
-.compatiblyIncludes(
-   

[PATCH] D124726: Suggest typoed directives in preprocessor conditionals

2022-05-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: cjdb.
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticLexKinds.td:362-365
 
+def warn_pp_typo_directive : Warning<
+  "'#%0' directive not found, did you mean '#%1'?">,
+  InGroup;

ken-matsui wrote:
> aaron.ballman wrote:
> > Rather than adding a warning over the top of an existing error, I think we 
> > should modify `err_pp_invalid_directive` to have an optional "did you 
> > mean?" when we find a plausible typo to correct.
> > 
> > However, we do not issue that diagnostic when it's inside of a skipped 
> > conditional block, and that's what the crux of 
> > https://github.com/llvm/llvm-project/issues/51598 is about. As @rsmith 
> > pointed out in that issue (and I agree), compilers are free to support 
> > custom directives and those will validly appear inside of a conditional 
> > block that is skipped. We need to be careful not to diagnose those kinds of 
> > situations as an error. However, we still want to diagnose when the unknown 
> > directive is "sufficiently close" to another one which can control the 
> > conditional chain. e.g.,
> > ```
> > #fi FOO // error unknown directive, did you mean #if?
> > #endfi // error unknown directive, did you mean #endif?
> > 
> > #if FOO
> > #esle // diag: unknown directive, did you mean #else?
> > #elfi // diag: unknown directive, did you mean #elif?
> > #elfidef // diag: unknown directive, did you mean #elifdef
> > #elinfdef // diag: unknown directive, did you mean #elifndef
> > 
> > #frobble // No diagnostic, not close enough to a conditional directive to 
> > warrant diagnosing
> > #eerp // No diagnostic, not close enough to a conditional directive to 
> > warrant diagnosing
> > 
> > #endif
> > ```
> > Today, if `FOO` is defined to a nonzero value, you'll get diagnostics for 
> > all of those, but if `FOO` is not defined or is defined to 0, then there's 
> > no diagnostics. I think we want to consider directives that are *very 
> > likely* to be a typo (edit distance of 1, maybe 2?) for a conditional 
> > directive as a special case.
> > 
> > Currently, we only diagnose unknown directives as an error. I think for 
> > these special cased conditional directive diagnostics, we'll want to use a 
> > warning rather than an error in this circumstance (just in case it turns 
> > out to be a valid directive in a skipped conditional block). If we do go 
> > that route and make it a warning, I think the warning group should be 
> > `-Wunknown-directives` to mirror `-Wunknown-pragmas`, 
> > `-Wunknown-attributes`, etc and it should be defined to have the same text 
> > as the error case. e.g., 
> > ```
> > def err_pp_invalid_directive : Error<
> >   "invalid preprocessing directive%select{|; did you mean '#%1'?}0"
> > >;
> > def warn_pp_invalid_directive : Warning<
> >   err_pp_invalid_directive.Text>, InGroup>;
> > ```
> > WDYT?
> > 
> > (These were my thoughts before seeing the rest of the patch. After reading 
> > the patch, it looks like we have pretty similar ideas here, which is great, 
> > but leaving the comment anyway in case you have further opinions.)
> > Currently, we only diagnose unknown directives as an error. I think for 
> > these special cased conditional directive diagnostics, we'll want to use a 
> > warning rather than an error in this circumstance (just in case it turns 
> > out to be a valid directive in a skipped conditional block). If we do go 
> > that route and make it a warning, I think the warning group should be 
> > `-Wunknown-directives` to mirror `-Wunknown-pragmas`, 
> > `-Wunknown-attributes`, etc and it should be defined to have the same text 
> > as the error case. e.g., 
> > ```
> > def err_pp_invalid_directive : Error<
> >   "invalid preprocessing directive%select{|; did you mean '#%1'?}0"
> > >;
> > def warn_pp_invalid_directive : Warning<
> >   err_pp_invalid_directive.Text>, InGroup>;
> > ```
> > WDYT?
> > 
> > (These were my thoughts before seeing the rest of the patch. After reading 
> > the patch, it looks like we have pretty similar ideas here, which is great, 
> > but leaving the comment anyway in case you have further opinions.)
> 
> For now, I totally agree with deriving a new warning from 
> `err_pp_invalid_directive`.
> 
> However, for future scalability, I think it would be great if we could split 
> those diagnostics into Error & Warning and Help, for example. Rustc does 
> split the diagnostics like the following, and I think this is quite clear. 
> So, a bit apart from this patch, I speculate creating a diagnostic system 
> that can split them would bring Clang diagnostics much more readable.
> 
> https://github.com/rust-lang/rust/blob/598d89bf142823b5d84e2eb0f0f9e418ee966a4b/src/test/ui/suggestions/suggest-trait-items.stderr
> 
> However, for future scalability, I think it would be great if we could split 
> those diagnostics into Error & Warning and Help, for example. Rustc does 
> split the diagnostics li

[PATCH] D121465: WIP: [clang][modules] Do not report declarations without linkage as ambiguous

2022-05-06 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 marked 2 inline comments as done.
jansvoboda11 added a comment.

In D121465#3384825 , @vsapsai wrote:

> My concern with this approach is I'm not sure if 
> `isEquivalentInternalLinkageDeclaration` is a desired long-term solution for 
> anonymous C++ enums.

Is there anything suggesting it's not?




Comment at: clang/test/Modules/ambiguous-anonymous-enum-lookup.m.cpp:38
+
+int testReferencingAnonymousEnumConstant() {
+  return kAnonymousEnumValue; // expected-no-diagnostics

vsapsai wrote:
> Should we test also non-equivalent enums or is it tested somewhere else?
I believe that's tested in `redefinition-c-tagtypes.m`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121465

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


[PATCH] D121465: WIP: [clang][modules] Do not report declarations without linkage as ambiguous

2022-05-06 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 427603.
jansvoboda11 marked an inline comment as done.
jansvoboda11 added a comment.

Refer to enum constant while defining another


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121465

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Modules/ambiguous-anonymous-enum-lookup.m.cpp

Index: clang/test/Modules/ambiguous-anonymous-enum-lookup.m.cpp
===
--- /dev/null
+++ clang/test/Modules/ambiguous-anonymous-enum-lookup.m.cpp
@@ -0,0 +1,43 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache -I %t/include %t/test.cpp -verify
+// RUN: %clang_cc1 -fsyntax-only -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache -I %t/include %t/test.m   -verify
+
+//--- include/textual.h
+#ifndef TEXTUAL_H
+#define TEXTUAL_H
+enum {
+  kAnonymousEnumValue0 = 0,
+  kAnonymousEnumValue1 = kAnonymousEnumValue0 + 1
+};
+#endif
+
+//--- include/empty.h
+//--- include/initially_hidden.h
+#include "textual.h"
+
+//--- include/module.modulemap
+module Piecewise {
+  module Empty   { header "empty.h"}
+  module InitiallyHidden { header "initially_hidden.h" }
+}
+
+//--- test.cpp
+#include "empty.h"
+#include "textual.h"
+#include "initially_hidden.h"
+
+int testReferencingAnonymousEnumConstant() {
+  return kAnonymousEnumValue1; // expected-warning {{ambiguous use of internal linkage declaration 'kAnonymousEnumValue1' defined in multiple modules}}
+   // expected-note@textual.h:5 {{declared here}}
+   // expected-note@textual.h:5 {{declared here in module 'Piecewise.InitiallyHidden'}}
+}
+
+//--- test.m
+#include "empty.h"
+#include "textual.h"
+#include "initially_hidden.h"
+
+int testReferencingAnonymousEnumConstant() {
+  return kAnonymousEnumValue1; // expected-no-diagnostics
+}
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -9973,19 +9973,19 @@
 /// declare the same entity, but we also don't want lookups with both
 /// declarations visible to be ambiguous in some cases (this happens when using
 /// a modularized libstdc++).
-bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
-  const NamedDecl *B) {
+bool Sema::isEquivalentNonExternalLinkageDeclaration(const NamedDecl *A,
+ const NamedDecl *B) {
   auto *VA = dyn_cast_or_null(A);
   auto *VB = dyn_cast_or_null(B);
   if (!VA || !VB)
 return false;
 
-  // The declarations must be declaring the same name as an internal linkage
+  // The declarations must be declaring the same name as an internal/no linkage
   // entity in different modules.
   if (!VA->getDeclContext()->getRedeclContext()->Equals(
   VB->getDeclContext()->getRedeclContext()) ||
   getOwningModule(VA) == getOwningModule(VB) ||
-  VA->isExternallyVisible() || VB->isExternallyVisible())
+  VA->hasExternalFormalLinkage() || VB->hasExternalFormalLinkage())
 return false;
 
   // Check that the declarations appear to be equivalent.
@@ -10111,8 +10111,8 @@
 PendingBest.push_back(Cand);
 Cand->Best = true;
 
-if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
- Curr->Function))
+if (S.isEquivalentNonExternalLinkageDeclaration(Cand->Function,
+Curr->Function))
   EquivalentCands.push_back(Cand->Function);
 else
   Best = end();
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -509,6 +509,7 @@
   NamedDecl *HasNonFunction = nullptr;
 
   llvm::SmallVector EquivalentNonFunctions;
+  bool ComplainOnEquivalent = false;
 
   unsigned UniqueTagIndex = 0;
 
@@ -576,11 +577,15 @@
 } else {
   if (HasNonFunction) {
 // If we're about to create an ambiguity between two declarations that
-// are equivalent, but one is an internal linkage declaration from one
-// module and the other is an internal linkage declaration from another
-// module, just skip it.
-if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
- D)) {
+// are equivalent, but one is an internal/no linkage declaration from
+// one module and the other is an internal/no linkage decl

[PATCH] D125088: [clangd] Add parsing for IgnoreHeaders config option

2022-05-06 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added reviewers: sammccall, kbobyrev.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

https://reviews.llvm.org/D125088

Files:
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp


Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -247,6 +247,20 @@
   EXPECT_EQ(Results[0].InlayHints.DeducedTypes, llvm::None);
 }
 
+TEST(ParseYAML, IncludesIgnoreHeader) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+Diagnostics:
+  Includes:
+IgnoreHeader: [foo, bar]
+  )yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].Diagnostics.Includes.IgnoreHeader,
+  ElementsAre(val("foo"), val("bar")));
+}
 } // namespace
 } // namespace config
 } // namespace clangd
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -128,6 +128,7 @@
 Dict.handle("UnusedIncludes", [&](Node &N) {
   F.UnusedIncludes = scalarValue(N, "UnusedIncludes");
 });
+Dict.handle("Includes", [&](Node &N) { parse(F.Includes, N); });
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
 Dict.parse(N);
   }
@@ -154,6 +155,15 @@
 Dict.parse(N);
   }
 
+  void parse(Fragment::DiagnosticsBlock::IncludesBlock &F, Node &N) {
+DictParser Dict("Includes", this);
+Dict.handle("IgnoreHeader", [&](Node &N) {
+  if (auto Values = scalarValues(N))
+F.IgnoreHeader = std::move(*Values);
+});
+Dict.parse(N);
+  }
+
   void parse(Fragment::IndexBlock &F, Node &N) {
 DictParser Dict("Index", this);
 Dict.handle("Background",


Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -247,6 +247,20 @@
   EXPECT_EQ(Results[0].InlayHints.DeducedTypes, llvm::None);
 }
 
+TEST(ParseYAML, IncludesIgnoreHeader) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+Diagnostics:
+  Includes:
+IgnoreHeader: [foo, bar]
+  )yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].Diagnostics.Includes.IgnoreHeader,
+  ElementsAre(val("foo"), val("bar")));
+}
 } // namespace
 } // namespace config
 } // namespace clangd
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -128,6 +128,7 @@
 Dict.handle("UnusedIncludes", [&](Node &N) {
   F.UnusedIncludes = scalarValue(N, "UnusedIncludes");
 });
+Dict.handle("Includes", [&](Node &N) { parse(F.Includes, N); });
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
 Dict.parse(N);
   }
@@ -154,6 +155,15 @@
 Dict.parse(N);
   }
 
+  void parse(Fragment::DiagnosticsBlock::IncludesBlock &F, Node &N) {
+DictParser Dict("Includes", this);
+Dict.handle("IgnoreHeader", [&](Node &N) {
+  if (auto Values = scalarValues(N))
+F.IgnoreHeader = std::move(*Values);
+});
+Dict.parse(N);
+  }
+
   void parse(Fragment::IndexBlock &F, Node &N) {
 DictParser Dict("Index", this);
 Dict.handle("Background",
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124983: [HLSL] add -fcgl option flag.

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

LGTM aside from a tiny nit.




Comment at: clang/include/clang/Driver/Options.td:6768-6769
+   "Same as -S + -emit-llvm + -disable-llvm-passes.">;
+def fcgl : DXCFlag<"fcgl">, Alias,
+  HelpText<"Emit pristine LLVM IR from the frontend by not running any LLVM 
passes at all.">;

Aliases typically skip their help text.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124983

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


[PATCH] D123009: [Sema] Enum conversion warning when one signed and other unsigned.

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

LGTM aside from some minor corrections. Btw, do you need someone to land this 
on your behalf? If so, what name and email address would you like used for 
patch attribution?




Comment at: clang/test/Sema/enum-sign-conversion.c:11-14
+// Signed enums
+enum SE1 { N1 = -1 };
+// Unsigned unums
+enum UE1 { P1 };

Then use `E1` in place of `UE1` -- it was the name `UE1` plus the comment that 
kept tripping me up.



Comment at: clang/test/Sema/enum-sign-conversion.c:6-8
+enum X { A,
+ B,
+ C };

red1bluelost wrote:
> aaron.ballman wrote:
> > Unrelated formatting change?
> Changed back.
Almost, there's still whitespace changes. :-)



Comment at: clang/test/Sema/enum-sign-conversion.c:37-43
+unsigned f5(enum UE1 E) {
+  return E; // signed-warning {{implicit conversion changes signedness: 'enum 
UE1' to 'unsigned int'}}
+}
+
+enum UE1 f6(unsigned E) {
+  return E; // signed-warning {{implicit conversion changes signedness: 
'unsigned int' to 'enum UE1'}}
+}

red1bluelost wrote:
> aaron.ballman wrote:
> > Shouldn't these not warn as well -- the underlying enum type is unsigned?
> This is the case with 'win32' for the ABI. It has enum be signed as default. 
> I changed the name of the verify to win32 to that it is easier to see that is 
> the case.
Ah, thanks, based on that, I have some other naming suggestions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123009

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


[clang] 43d8ffe - Fix underlining length; NFC

2022-05-06 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-06T08:47:45-04:00
New Revision: 43d8ffeeb1f2ba68e51652ee50da8cf5bf49fdfd

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

LOG: Fix underlining length; NFC

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9e9990fa4a9be..0a5d3a85834d3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -69,7 +69,7 @@ Major New Features
   Randomizing structure layout is a C-only feature.
 
 Bug Fixes
---
+-
 - ``CXXNewExpr::getArraySize()`` previously returned a ``llvm::Optional``
   wrapping a ``nullptr`` when the ``CXXNewExpr`` did not have an array
   size expression. This was fixed and ``::getArraySize()`` will now always



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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 10 inline comments as done.
ymandel added a comment.

Thanks for the review!




Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:39-45
+  using dataflow::ControlFlowContext;
+  using dataflow::DataflowAnalysisContext;
+  using dataflow::DataflowAnalysisState;
+  using dataflow::Environment;
+  using dataflow::UncheckedOptionalAccessModel;
+  using dataflow::WatchedLiteralsSolver;
+  using llvm::Expected;

sgatev wrote:
> Do we really need all these using declarations? There seems to be one 
> reference for each of these types. I think we can simply qualify the 
> references.
No, we don't need them, but IMO they clarify the code. We're really heavy with 
the types, given that `auto` is discouraged, so I think pulling these out 
improves readability in some critical places (lines 56 and 63). I figured I'd 
do all for consistency. I've removed those not related to lines 56 and 63, or 
used more than once. WDYT?



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

sgatev wrote:
> xazax.hun wrote:
> > ymandel wrote:
> > > xazax.hun wrote:
> > > > xazax.hun wrote:
> > > > > ymandel wrote:
> > > > > > xazax.hun wrote:
> > > > > > > xazax.hun wrote:
> > > > > > > > Could the size of the vector ever be wrong? Should this be an 
> > > > > > > > assert instead?
> > > > > > > Whoops, after the update this comment is out of place, now it 
> > > > > > > supposed to be on line 60. 
> > > > > > Based on my reading, it is a rare, but possible condition. 
> > > > > > Basically, we need code where the exit block is unreachable, which 
> > > > > > I believe can happen in weird cases like:
> > > > > > 
> > > > > > ```
> > > > > > while(true) {...}
> > > > > > ```
> > > > > > https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors 
> > > > > > for the exit block.
> > > > > > 
> > > > > > See the code here, which follows the ordering of the blocks and 
> > > > > > doesn't force blocks to be processed:
> > > > > > 
> > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
> > > > > Interesting. Since we already have optionals in the vector, I assumed 
> > > > > we will always have matching size. I think we might want to change 
> > > > > this so there is only one way for the analysis to not provide a state 
> > > > > for a basic block to make this a bit less confusing, 
> > > > Actually, in the linked code I see ` 
> > > > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would 
> > > > expect the size to be always right with possibly some `None`s for the 
> > > > nodes that were not processed.
> > > > Actually, in the linked code I see ` 
> > > > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would 
> > > > expect the size to be always right with possibly some `None`s for the 
> > > > nodes that were not processed.
> > > Ah, my mistake! I thought `resize` only allocated the space. #TIL
> > > 
> > > Changed to an assert. Thanks.
> > > 
> > But this discussion shed light on an interesting detail. If the exit block 
> > is unreachable, we will not diagnose the unsafe accesses. I wonder if this 
> > worth a FIXME. 
> The documentation of `runDataflowAnalysis` already hints that the size of the 
> vector matches the size of the CFG. Do you think we should make this more 
> clear?
> But this discussion shed light on an interesting detail. If the exit block is 
> unreachable, we will not diagnose the unsafe accesses. I wonder if this worth 
> a FIXME. 

> The documentation of runDataflowAnalysis already hints that the size of the 
> vector matches the size of the CFG. Do you think we should make this more 
> clear?

Yes to both. I'll send a separate patch on that header with the doc changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427607.
ymandel added a comment.

address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -32,10 +33,9 @@
 namespace {
 
 using namespace ::clang::ast_matchers;
-
 using LatticeTransferState = TransferState;
 
-auto optionalClass() {
+DeclarationMatcher optionalClass() {
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -230,6 +230,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier interpretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
@@ -550,6 +552,11 @@
 
 } // namespace
 
+ast_matchers::DeclarationMatcher
+UncheckedOptionalAccessModel::optionalClassDecl() {
+  return optionalClass();
+}
+
 UncheckedOptionalAccessModel::UncheckedOptionalAccessModel(
 ASTContext &Ctx, UncheckedOptionalAccessModelOptions Options)
 : DataflowAnalysis(
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -49,6 +49,9 @@
   UncheckedOptionalAccessModel(
   ASTContext &AstContext, UncheckedOptionalAccessModelOptions Options = {});
 
+  /// Returns a matcher for the optional classes covered by this model.
+  static ast_matchers::DeclarationMatcher optionalClassDecl();
+
   static SourceLocationsLattice initialElement() {
 return SourceLocationsLattice();
   }
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional &opt) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional &opt) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional &opt) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void checked_access(const absl::optional &opt) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional &opt) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional &opt) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional &opt) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional &opt) {
+  opt.value(); // no-warning
+}
+
+template <>
+void function_template_with_specialization(
+const ab

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:99
+  // recognise that a parent is infeasible only *after* a new and more specific
+  // constraint and its negation is evaluated.
+  //

Yeah, thx, I've also found one more typo. That's the problem with long comments 
:D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

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


[PATCH] D124702: [MSVC] Add support for pragma function

2022-05-06 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

It needs tests for the warnings about badly formed pragmas, and for pragmas 
outside file/namespace scope.




Comment at: clang/lib/Parse/ParsePragma.cpp:3561
 << "intrinsic";
 return;
   }

steplong wrote:
> hans wrote:
> > since the above is just a warning, we should probably still call the 
> > ActOn.. method?
> Hmm, I'm not sure because all the msgs above are also warnings (diag::warn_)
Yes, but for those, (missing left paren, or unknown intrinsic) it makes sense 
to do nothing. If it's just the right paren missing, I don't think it makes 
sense to ignore the intrinsic? Can you check how we handle similar situations 
with other intrinsics?



Comment at: clang/lib/Sema/SemaAttr.cpp:1079
+  MSFunctionNoBuiltins.insert(MSFunctionNoBuiltins.end(),
+  NoBuiltins.begin(), NoBuiltins.end());
+}

steplong wrote:
> hans wrote:
> > Do we want to avoid duplicates in MSFunctionNoBuiltins? Or maybe it doesn't 
> > matter?
> Yea, I didn't think it really mattered. I originally wanted to use a set, but 
> I needed the strings to be stored in contiguous memory for 
> NoBuitinAttr::CreateImplicit() in Sema::AddRangeBasedNoBuiltin()
A set would be nicer conceptually of course.

How about using an llvm::SmallSetVector. That will solve the problem of 
duplicates, it will be deterministic, and you can use getArrayRef() to get the 
values in contiguous memory, or maybe being() and end() will work too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124702

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427610.
ymandel added a comment.

add fixme


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -32,10 +33,9 @@
 namespace {
 
 using namespace ::clang::ast_matchers;
-
 using LatticeTransferState = TransferState;
 
-auto optionalClass() {
+DeclarationMatcher optionalClass() {
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -230,6 +230,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier interpretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
@@ -550,6 +552,11 @@
 
 } // namespace
 
+ast_matchers::DeclarationMatcher
+UncheckedOptionalAccessModel::optionalClassDecl() {
+  return optionalClass();
+}
+
 UncheckedOptionalAccessModel::UncheckedOptionalAccessModel(
 ASTContext &Ctx, UncheckedOptionalAccessModelOptions Options)
 : DataflowAnalysis(
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -49,6 +49,9 @@
   UncheckedOptionalAccessModel(
   ASTContext &AstContext, UncheckedOptionalAccessModelOptions Options = {});
 
+  /// Returns a matcher for the optional classes covered by this model.
+  static ast_matchers::DeclarationMatcher optionalClassDecl();
+
   static SourceLocationsLattice initialElement() {
 return SourceLocationsLattice();
   }
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional &opt) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional &opt) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional &opt) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void checked_access(const absl::optional &opt) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional &opt) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional &opt) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional &opt) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional &opt) {
+  opt.value(); // no-warning
+}
+
+template <>
+void function_template_with_specialization(
+const absl::optional &

[PATCH] D54943: [clang-tidy] implement new check 'misc-const-correctness' to add 'const' to unmodified variables

2022-05-06 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.h:24
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-const.html
+class ConstCorrectnessCheck : public ClangTidyCheck {

missing change to new docs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

ymandel wrote:
> sgatev wrote:
> > xazax.hun wrote:
> > > ymandel wrote:
> > > > xazax.hun wrote:
> > > > > xazax.hun wrote:
> > > > > > ymandel wrote:
> > > > > > > xazax.hun wrote:
> > > > > > > > xazax.hun wrote:
> > > > > > > > > Could the size of the vector ever be wrong? Should this be an 
> > > > > > > > > assert instead?
> > > > > > > > Whoops, after the update this comment is out of place, now it 
> > > > > > > > supposed to be on line 60. 
> > > > > > > Based on my reading, it is a rare, but possible condition. 
> > > > > > > Basically, we need code where the exit block is unreachable, 
> > > > > > > which I believe can happen in weird cases like:
> > > > > > > 
> > > > > > > ```
> > > > > > > while(true) {...}
> > > > > > > ```
> > > > > > > https://godbolt.org/z/rfEnfaWTv -- notice the lack of 
> > > > > > > predecessors for the exit block.
> > > > > > > 
> > > > > > > See the code here, which follows the ordering of the blocks and 
> > > > > > > doesn't force blocks to be processed:
> > > > > > > 
> > > > > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
> > > > > > Interesting. Since we already have optionals in the vector, I 
> > > > > > assumed we will always have matching size. I think we might want to 
> > > > > > change this so there is only one way for the analysis to not 
> > > > > > provide a state for a basic block to make this a bit less 
> > > > > > confusing, 
> > > > > Actually, in the linked code I see ` 
> > > > > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would 
> > > > > expect the size to be always right with possibly some `None`s for the 
> > > > > nodes that were not processed.
> > > > > Actually, in the linked code I see ` 
> > > > > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would 
> > > > > expect the size to be always right with possibly some `None`s for the 
> > > > > nodes that were not processed.
> > > > Ah, my mistake! I thought `resize` only allocated the space. #TIL
> > > > 
> > > > Changed to an assert. Thanks.
> > > > 
> > > But this discussion shed light on an interesting detail. If the exit 
> > > block is unreachable, we will not diagnose the unsafe accesses. I wonder 
> > > if this worth a FIXME. 
> > The documentation of `runDataflowAnalysis` already hints that the size of 
> > the vector matches the size of the CFG. Do you think we should make this 
> > more clear?
> > But this discussion shed light on an interesting detail. If the exit block 
> > is unreachable, we will not diagnose the unsafe accesses. I wonder if this 
> > worth a FIXME. 
> 
> > The documentation of runDataflowAnalysis already hints that the size of the 
> > vector matches the size of the CFG. Do you think we should make this more 
> > clear?
> 
> Yes to both. I'll send a separate patch on that header with the doc changes.
On second thought, the FIXME is for the check, not the framework, so I've added 
it here. I'll still send the comment tweak separately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D125091: [clang][dataflow][NFC] Clarify guarantees on returned vector size for `runDataflowAnalysis`.

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

Adjusts the comment to specify that the output vector's size matches the number 
of CFG blocks.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125091

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h


Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -106,8 +106,9 @@
 };
 
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. Indices
-/// of the returned vector correspond to basic block IDs. Returns an error if
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully.
 template 
 llvm::ExpectedIndex: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -106,8 +106,9 @@
 };
 
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. Indices
-/// of the returned vector correspond to basic block IDs. Returns an error if
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully.
 template 
 llvm::Expected___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124866: [CUDA][HIP] support __noinline__ as keyword

2022-05-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I don't know how language extensions come about in CUDA or HIP -- is there an 
appropriate standards body (or something similar) that's aware of this 
extension and supports it?

The changes should likely come with a release note entry about the new 
functionality, and some documentation changes as well.




Comment at: clang/include/clang/Basic/Attr.td:1778-1779
 def NoInline : DeclOrStmtAttr {
-  let Spellings = [GCC<"noinline">, CXX11<"clang", "noinline">,
+  let Spellings = [Keyword<"__noinline__">, GCC<"noinline">, CXX11<"clang", 
"noinline">,
C2x<"clang", "noinline">, Declspec<"noinline">];
   let Accessors = [Accessor<"isClangNoInline", [CXX11<"clang", "noinline">,





Comment at: clang/include/clang/Basic/Features.def:274
+// CUDA/HIP Features
+FEATURE(cuda_noinline_keyword, true)
+

Do the CUDA or HIP specs define `__noinline__` as a keyword specifically? If 
not, this isn't a `FEATURE`, it's an `EXTENSION` because it's specific to 
Clang, not the language standard.



Comment at: clang/lib/Parse/ParseDecl.cpp:902
+  while (Tok.is(tok::kw___noinline__)) {
+IdentifierInfo *AttrName = Tok.getIdentifierInfo();
+SourceLocation AttrNameLoc = ConsumeToken();

I think we should we be issuing a pedantic "this is a clang extension" warning 
here, WDYT?



Comment at: clang/test/SemaCUDA/noinline.cu:8
+__attribute__((noinline)) void fun2() { }
+__attribute__((__noinline__)) void fun3() { }

I think there should also be a test like:
```
[[gnu::__noinline__]] void fun4() {}
```
to verify that the double square bracket syntax also correctly handles this 
being a keyword now (I expect the test to pass).


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

https://reviews.llvm.org/D124866

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


[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-06 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:2441
+well as aggregate structures, ``void*`` (printed with ``%p``), and ``const
+char*`` (printed with ``%s``). A ``*%p`` specifier will be used for a field
+that Clang doesn't know how to format, and the corresopnding argument will be a

For post-commit: perhaps the string quoting and limit should be documented?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D123812: [CUDA] Add wrapper code generation for registering CUDA images

2022-05-06 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123812

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev accepted this revision.
sgatev added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:39-45
+  using dataflow::ControlFlowContext;
+  using dataflow::DataflowAnalysisContext;
+  using dataflow::DataflowAnalysisState;
+  using dataflow::Environment;
+  using dataflow::UncheckedOptionalAccessModel;
+  using dataflow::WatchedLiteralsSolver;
+  using llvm::Expected;

ymandel wrote:
> sgatev wrote:
> > Do we really need all these using declarations? There seems to be one 
> > reference for each of these types. I think we can simply qualify the 
> > references.
> No, we don't need them, but IMO they clarify the code. We're really heavy 
> with the types, given that `auto` is discouraged, so I think pulling these 
> out improves readability in some critical places (lines 56 and 63). I figured 
> I'd do all for consistency. I've removed those not related to lines 56 and 
> 63, or used more than once. WDYT?
Ah, I see, we're using all of these types in a single line :D Perhaps 
`std::vector>>` could be encapsulated in a 
`DataflowResult` type or something like that. I suggest we keep the patch as 
it currently is and consider such a change separately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D124996: [clang][preprocessor] Fix unsigned-ness of utf8 char literals

2022-05-06 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 427614.
tbaeder marked 2 inline comments as done.

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

https://reviews.llvm.org/D124996

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Lex/PPExpressions.cpp
  clang/test/Lexer/utf8-char-literal.cpp

Index: clang/test/Lexer/utf8-char-literal.cpp
===
--- clang/test/Lexer/utf8-char-literal.cpp
+++ clang/test/Lexer/utf8-char-literal.cpp
@@ -1,7 +1,12 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c11 -x c -fsyntax-only -verify %s
 // RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c2x -x c -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++1z -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c2x -x c -fsyntax-only -fchar8_t -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c2x -x c -fsyntax-only -fno-char8_t -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++17 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++17 -fsyntax-only -fchar8_t -DCHAR8_T -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++20 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++20 -fsyntax-only -fno-char8_t -DNO_CHAR8_T -verify %s
 
 int array0[u'ñ' == u'\xf1'? 1 : -1];
 int array1['\xF1' !=  u'\xf1'? 1 : -1];
@@ -13,7 +18,7 @@
 char d = u8'\u1234'; // expected-error {{character too large for enclosing character literal type}}
 char e = u8'ሴ'; // expected-error {{character too large for enclosing character literal type}}
 char f = u8'ab'; // expected-error {{Unicode character literals may not contain multiple characters}}
-#elif __STDC_VERSION__ > 202000L
+#elif __STDC_VERSION__ >= 202000L
 char a = u8'ñ';  // expected-error {{character too large for enclosing character literal type}}
 char b = u8'\x80';   // ok
 char c = u8'\u0080'; // expected-error {{universal character name refers to a control character}}
@@ -26,3 +31,40 @@
  unsigned char : 1),
 "Surprise!");
 #endif
+
+
+/// In C++17, the behavior depends on -fchar8_t
+#if __cplusplus == 201703L
+#  if defined(CHAR8_T)
+#if u8'\xff' == '\xff' // expected-warning {{right side of operator converted from negative value to unsigned}}
+#  error Something's not right.
+#endif
+#  else
+#if u8'\xff' != '\xff'
+#  error Something's not right.
+#endif
+#  endif
+#endif
+
+
+/// In C++20 and up, u8 char literals are unsigned by default,
+/// unless -fno-char8_t is specified.
+#if __cplusplus > 201703L
+#  if defined(NO_CHAR8_T)
+#if u8'\xff' == 0xff
+#  error u8 char literal is unsigned
+#endif
+#  else
+#if u8'\xff' != 0xff
+#  error u8 char literal is not unsigned
+#endif
+#  endif
+#endif
+
+
+/// In C2x, 8u char literals are always unsigned
+#if __STDC_VERSION__ >= 202000L
+#  if u8'\xff' != 0xff
+#error u8 char literal is not unsigned
+#  endif
+#endif
Index: clang/lib/Lex/PPExpressions.cpp
===
--- clang/lib/Lex/PPExpressions.cpp
+++ clang/lib/Lex/PPExpressions.cpp
@@ -408,9 +408,15 @@
 // Set the value.
 Val = Literal.getValue();
 // Set the signedness. UTF-16 and UTF-32 are always unsigned
+// UTF-8 is unsigned if -fchar8_t is specified
 if (Literal.isWide())
   Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
-else if (!Literal.isUTF16() && !Literal.isUTF32())
+else if (Literal.isUTF16() || Literal.isUTF32())
+  Val.setIsUnsigned(true);
+else if (Literal.isUTF8())
+  Val.setIsUnsigned(PP.getLangOpts().CPlusPlus ? PP.getLangOpts().Char8
+   : true);
+else
   Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
 
 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -315,6 +315,8 @@
   template parameter, to conform to the Itanium C++ ABI and be compatible with
   GCC. This breaks binary compatibility with code compiled with earlier versions
   of clang; use the ``-fclang-abi-compat=14`` option to get the old mangling.
+- Preprocessor character literals with a ``u8`` prefix are now correctly treated as
+  unsigned character literals. This fixes `Issue 54886 `_.
 
 C++20 Feature Support
 ^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124996: [clang][preprocessor] Fix unsigned-ness of utf8 char literals

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



Comment at: clang/test/Lexer/utf8-char-literal.cpp:39
+#  if defined(CHAR8_T)
+#if u8'\xff' == '\xff' // expected-warning {{right side of operator 
converted from negative value to unsigned}}
+#  error Something's not right.

I'm a little confused with the amount of combinations at this point, so please 
tell me if the emitted warning here looks wrong.



Comment at: clang/test/Lexer/utf8-char-literal.cpp:70
+#  endif
+#endif

I know indenting the preprocessor directives here isn't according to coding 
style, but it helps a lot with readability.


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

https://reviews.llvm.org/D124996

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


[PATCH] D113779: [Clang] Add mfp16, mfp16fml and mdotprod flags for ARM target features.

2022-05-06 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.
Herald added a subscriber: MaskRay.
Herald added a project: All.

In D113779#3207936 , @SjoerdMeijer 
wrote:

>> If anybody has contacts to GCC that would be very helpful. Unfortunately I 
>> don't think I will be able to drive this.
>
> Ok, I will bring this up internally first with some folks that work on GCC 
> and see what happens. To be continued...

Hi, did you get an update by any chance?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113779

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D121120#3494137 , @ymandel wrote:

> In D121120#3494085 , @xazax.hun 
> wrote:
>
>> Most checks in Clang Tidy will run relatively quickly as they usually can do 
>> most/all of their work in a single traversal. I wonder whether flow 
>> sensitive checks will prove to be a bit slower. I think adding slower checks 
>> to Tidy is fine, but it would be nice to properly set the expectations to 
>> the user (e.g. if an IDE is running Tidy in the background it might want to 
>> opt out from flow sensitive checks if they turn out to be slow). In case the 
>> performance is good, I think it should be fine as is. Otherwise I wonder if 
>> we want to add something like a tag to mark flow sensitive checks and give 
>> an option to turn them off.
>
> Excellent point. @aaron.ballman is there a mechanism for this?
>
> I can check on the current performance, but I think this would be good to 
> know regardless of the outcome, given that performance is subject to change 
> and we expect to develop other flow-sensitive checks.

Just realized we left this open. How about a disclaimer at the top of the doc 
(.rst) file noting the potential cost?  Anyone using clang-tidy should be 
explicitly configuring which checks to run, so that may be sufficient. If we 
want to allow users to enable/disable flow-sensitive checks across the board, 
though, it seems like we would need to add a new option to `ClangTidyOptions` 
(https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clang-tidy/ClangTidyOptions.h#L50).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[clang] a45647d - [clang][dataflow][NFC] Clarify guarantees on returned vector size for `runDataflowAnalysis`.

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

Author: Yitzhak Mandelbaum
Date: 2022-05-06T13:30:01Z
New Revision: a45647d82b728a7ccdfe28338bb8a115dee7a735

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

LOG: [clang][dataflow][NFC] Clarify guarantees on returned vector size for 
`runDataflowAnalysis`.

Adjusts the comment to specify that the output vector's size matches the number 
of CFG blocks.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index 40bace44ffbd5..f4d6a221abecc 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -106,8 +106,9 @@ template  struct DataflowAnalysisState {
 };
 
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. Indices
-/// of the returned vector correspond to basic block IDs. Returns an error if
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully.
 template 
 llvm::Expectedhttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125091: [clang][dataflow][NFC] Clarify guarantees on returned vector size for `runDataflowAnalysis`.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa45647d82b72: [clang][dataflow][NFC] Clarify guarantees on 
returned vector size for… (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125091

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h


Index: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -106,8 +106,9 @@
 };
 
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. Indices
-/// of the returned vector correspond to basic block IDs. Returns an error if
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully.
 template 
 llvm::ExpectedIndex: clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -106,8 +106,9 @@
 };
 
 /// Performs dataflow analysis and returns a mapping from basic block IDs to
-/// dataflow analysis states that model the respective basic blocks. Indices
-/// of the returned vector correspond to basic block IDs. Returns an error if
+/// dataflow analysis states that model the respective basic blocks. The
+/// returned vector, if any, will have the same size as the number of CFG
+/// blocks, with indices corresponding to basic block IDs. Returns an error if
 /// the dataflow analysis cannot be performed successfully.
 template 
 llvm::Expected___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123032: [clang][dataflow] Exclude protobuf types from modeling in the environment.

2022-05-06 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 2 inline comments as done.
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:513
+  const RecordDecl *RD = BaseTy->getDecl();
+  if (RD->getIdentifier() == nullptr || RD->getName() != "Message")
+return false;

xazax.hun wrote:
> xazax.hun wrote:
> > ymandel wrote:
> > > xazax.hun wrote:
> > > > Not sure how often is this invoked but we could reduce the number of 
> > > > string comparisons by caching the identifier ptr and do a pointer 
> > > > comparison.
> > > Good question. It means an extra comparison for each type until the 
> > > pointer is cached (to check if the cache is set) and then, afterwards, 2 
> > > comparisons vs ~10 for the common case where the class name is doesn't 
> > > match. In the matching case, though, it is clearly saving much more.
> > > 
> > > For proto-heavy code, it seems a win, and a loss otherwise.  But, the 
> > > question is where to put the cache. It seems to me best to move this to 
> > > be a method on DataflowAnalysisContext (since it is a global, not local 
> > > env, property) and make the cached pointer a private member of DAC.
> > > 
> > > Thoughts?
> > I think it might be nice to have a context that is scoped to the 
> > translation unit rather than a function. We might have other stuff that we 
> > want to cache here.
> > 
> > An example how the static analyzer is dealing with this: 
> > https://github.com/llvm/llvm-project/blob/main/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp#L960
> > 
> > In case we do not want to be lazy and willing to populate the cache eagerly 
> > at the beginning of the analysis, we would not pay for the extra checks to 
> > see if the cache is populated.
> I'm also fine with not doing caching for now and having a note to consider 
> this in the future if it becomes measurable in the profiles. It is probably 
> fine for now when we only have a couple of short strings to compare. But I 
> guess the number of special cases we handle this way will only increase in 
> the future. 
> I'm also fine with not doing caching for now and having a note to consider 
> this in the future if it becomes measurable in the profiles. It is probably 
> fine for now when we only have a couple of short strings to compare. But I 
> guess the number of special cases we handle this way will only increase in 
> the future. 

(sorry for the very long delay in responding).  I think holding off on the 
cache may be best for now, pending performance analysis. I'm hesitant to put 
too much effort in to optimizing this, because ultimately we want to move to a 
lazy-initialization model which would obviate the need for this kind of 
optimization, because we would only model the fields that are used, making the 
size of the underlying struct irrelevant.

I've added a FIXME to this effect.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123032

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


[PATCH] D124966: Thread safety analysis: Handle compound assignment and ->* overloads

2022-05-06 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert marked 2 inline comments as done.
aaronpuchert added inline comments.



Comment at: clang/lib/Analysis/ThreadSafety.cpp:1994
+  case OO_Equal:
+  case OO_PlusEqual:
+  case OO_MinusEqual:

aaron.ballman wrote:
> If we're going to be handling these, should we also be handling overloads of 
> `++` and `--`?
Yes, in some sense these are also compound assignment operators despite their 
looks. I'll add them as well.

Sadly streams use `<<` and `>>` instead of `<<=` and `>>=`, and we can't really 
assume the former to write.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124966

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


[PATCH] D124966: Thread safety analysis: Handle compound assignment and ->* overloads

2022-05-06 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert updated this revision to Diff 427617.
aaronpuchert marked an inline comment as done.
aaronpuchert added a comment.

Also consider `++` and `--` as writing, test all operators.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124966

Files:
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -82,6 +82,9 @@
   T* ptr_;
 };
 
+template
+U& operator->*(const SmartPtr& ptr, U T::*p) { return ptr->*p; }
+
 
 // For testing destructor calls and cleanup.
 class MyString {
@@ -4338,6 +4341,21 @@
 
   void operator()() { }
 
+  Data& operator+=(int);
+  Data& operator-=(int);
+  Data& operator*=(int);
+  Data& operator/=(int);
+  Data& operator%=(int);
+  Data& operator^=(int);
+  Data& operator&=(int);
+  Data& operator|=(int);
+  Data& operator<<=(int);
+  Data& operator>>=(int);
+  Data& operator++();
+  Data& operator++(int);
+  Data& operator--();
+  Data& operator--(int);
+
 private:
   int dat;
 };
@@ -4404,6 +4422,20 @@
   // expected-warning {{reading variable 'datap1_' requires holding mutex 'mu_'}}
 data_ = *datap2_; // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}} \
   // expected-warning {{reading the value pointed to by 'datap2_' requires holding mutex 'mu_'}}
+data_ += 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ -= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ *= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ /= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ %= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ ^= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ &= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ |= 0;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ <<= 0;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ >>= 0;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+++data_;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_++;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+--data_;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_--;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
 
 data_[0] = 0; // expected-warning {{reading variable 'data_' requires holding mutex 'mu_'}}
 (*datap2_)[0] = 0;// expected-warning {{reading the value pointed to by 'datap2_' requires holding mutex 'mu_'}}
@@ -4923,6 +4955,8 @@
   SmartPtr  sp GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
   SmartPtr sq GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
 
+  static constexpr int Cell::*pa = &Cell::a;
+
   void test1() {
 mu1.ReaderLock();
 mu2.Lock();
@@ -4931,6 +4965,7 @@
 if (*sp == 0) doSomething();
 *sp = 0;
 sq->a = 0;
+sq->*pa = 0;
 
 if (sp[0] == 0) doSomething();
 sp[0] = 0;
@@ -4946,6 +4981,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 *sp = 0;   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 sq->a = 0; // expected-warning {{reading variable 'sq' requires holding mutex 'mu1'}}
+sq->*pa = 0;   // expected-warning {{reading variable 'sq' requires holding mutex 'mu1'}}
 
 if (sp[0] == 0) doSomething();   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 sp[0] = 0;   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
@@ -4962,6 +4998,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading the value pointed to by 'sp' requires holding mutex 'mu2'}}
 *sp = 0;   // expected-warning {{reading the value pointed to by 'sp' requires holding mutex 'mu2'}}
 sq->a = 0; // expected-warning {{reading the value pointed to by 'sq' requires holding mute

[PATCH] D125092: [OpenMP] Add basic support for properly handling static libraries

2022-05-06 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, JonChesterfield, tianshilei1992.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

Currently we handle static libraries like any other object in the
linker wrapper. However, this does not preserve the sematnics that
dictate static libraries should be lazily loaded as the symbols are
needed. This allows us to ignore linking in architectures that are not
used by the main application being compiled. This patch adds the basic
support for detecting if a file came from a static library, and only
including it in the link job if it's used by other object files.

This patch only adds the basic support, to be more correct we should
check the symbols and only inclue the library if the link job contains
symbols that are needed. Ideally we could just put this on the linker
itself, but nvlink doesn't seem to support `.a` files.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125092

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -167,13 +167,15 @@
 /// Information for a device offloading file extracted from the host.
 struct DeviceFile {
   DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
- StringRef Filename)
-  : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename) {}
+ StringRef Filename, bool IsLibrary = false)
+  : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename),
+IsLibrary(IsLibrary) {}
 
   std::string Kind;
   std::string TheTriple;
   std::string Arch;
   std::string Filename;
+  bool IsLibrary;
 };
 
 namespace llvm {
@@ -208,7 +210,8 @@
 
 Expected>
 extractFromBuffer(std::unique_ptr Buffer,
-  SmallVectorImpl &DeviceFiles);
+  SmallVectorImpl &DeviceFiles,
+  bool IsLibrary = false);
 
 void printCommands(ArrayRef CmdArgs) {
   if (CmdArgs.empty())
@@ -324,7 +327,8 @@
 /// buffer \p Contents. The buffer is expected to contain a valid offloading
 /// binary format.
 Error extractOffloadFiles(StringRef Contents, StringRef Prefix,
-  SmallVectorImpl &DeviceFiles) {
+  SmallVectorImpl &DeviceFiles,
+  bool IsLibrary = false) {
   uint64_t Offset = 0;
   // There could be multiple offloading binaries stored at this section.
   while (Offset < Contents.size()) {
@@ -361,7 +365,7 @@
   return E;
 
 DeviceFiles.emplace_back(Kind, Binary.getTriple(), Binary.getArch(),
- TempFile);
+ TempFile, IsLibrary);
 
 Offset += Binary.getSize();
   }
@@ -371,7 +375,8 @@
 
 Expected>
 extractFromBinary(const ObjectFile &Obj,
-  SmallVectorImpl &DeviceFiles) {
+  SmallVectorImpl &DeviceFiles,
+  bool IsLibrary = false) {
   StringRef Extension = sys::path::extension(Obj.getFileName()).drop_front();
   StringRef Prefix = sys::path::stem(Obj.getFileName());
   SmallVector ToBeStripped;
@@ -386,7 +391,8 @@
 if (!Contents)
   return Contents.takeError();
 
-if (Error Err = extractOffloadFiles(*Contents, Prefix, DeviceFiles))
+if (Error Err =
+extractOffloadFiles(*Contents, Prefix, DeviceFiles, IsLibrary))
   return std::move(Err);
 
 ToBeStripped.push_back(*Name);
@@ -447,7 +453,8 @@
 
 Expected>
 extractFromBitcode(std::unique_ptr Buffer,
-   SmallVectorImpl &DeviceFiles) {
+   SmallVectorImpl &DeviceFiles,
+   bool IsLibrary = false) {
   LLVMContext Context;
   SMDiagnostic Err;
   std::unique_ptr M = getLazyIRModule(std::move(Buffer), Err, Context);
@@ -473,7 +480,8 @@
 
 StringRef Contents = CDS->getAsString();
 
-if (Error Err = extractOffloadFiles(Contents, Prefix, DeviceFiles))
+if (Error Err =
+extractOffloadFiles(Contents, Prefix, DeviceFiles, IsLibrary))
   return std::move(Err);
 
 ToBeDeleted.push_back(&GV);
@@ -521,7 +529,8 @@
 std::unique_ptr ChildBuffer =
 MemoryBuffer::getMemBuffer(*ChildBufferRefOrErr, false);
 
-auto FileOrErr = extractFromBuffer(std::move(ChildBuffer), DeviceFiles);
+auto FileOrErr = extractFromBuffer(std::move(ChildBuffer), DeviceFiles,
+   /*IsLibrary*/ true);
 if (!FileOrErr)
   return FileOrErr.takeError();
 
@@ -573,11 +582,11 @@
 /// device code stripped from the buffer will be returned.
 Expected>
 extractFromBuffer(std::unique_ptr Buffer,
-  SmallVect

[clang] 3902ebd - [compiler-rt][builtins] Fix wrong ABI of AVR __mulqi3 & __mulhi3

2022-05-06 Thread Ben Shi via cfe-commits

Author: Ben Shi
Date: 2022-05-06T13:46:49Z
New Revision: 3902ebdd5793763431264259dfdca871ef453017

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

LOG: [compiler-rt][builtins] Fix wrong ABI of AVR __mulqi3 & __mulhi3

Reviewed By: aykevl, dylanmckay

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

Added: 


Modified: 
clang/lib/Basic/Targets/AVR.cpp
clang/test/Preprocessor/avr-common.c
compiler-rt/lib/builtins/avr/mulhi3.S
compiler-rt/lib/builtins/avr/mulqi3.S

Removed: 




diff  --git a/clang/lib/Basic/Targets/AVR.cpp b/clang/lib/Basic/Targets/AVR.cpp
index 7be33d4424f4d..67e27ebd58def 100644
--- a/clang/lib/Basic/Targets/AVR.cpp
+++ b/clang/lib/Basic/Targets/AVR.cpp
@@ -380,13 +380,13 @@ void AVRTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   Builder.defineMacro("__AVR__");
   Builder.defineMacro("__ELF__");
 
+  if (ABI == "avrtiny")
+Builder.defineMacro("__AVR_TINY__", "1");
+
   if (!this->CPU.empty()) {
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
-if (It->IsTiny)
-  Builder.defineMacro("__AVR_TINY__", "1");
-
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)

diff  --git a/clang/test/Preprocessor/avr-common.c 
b/clang/test/Preprocessor/avr-common.c
index 979dc52e67a10..70daf3fbee23e 100644
--- a/clang/test/Preprocessor/avr-common.c
+++ b/clang/test/Preprocessor/avr-common.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny13 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu avr25 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
 // RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,TINY %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu avrtiny 
/dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,TINY %s
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1

diff  --git a/compiler-rt/lib/builtins/avr/mulhi3.S 
b/compiler-rt/lib/builtins/avr/mulhi3.S
index 97e9bd1a7b56a..d65f52ff27b56 100644
--- a/compiler-rt/lib/builtins/avr/mulhi3.S
+++ b/compiler-rt/lib/builtins/avr/mulhi3.S
@@ -19,40 +19,53 @@
 //   return S;
 // }
 //
+// __mulhi3 has special ABI, as the implementation of libgcc, R25:R24 is used
+// to return result, while Rtmp/R21/R22/R23 are clobbered.
+//
 
//===--===//
 
.text
.align 2
 
+#ifdef __AVR_TINY__
+   .set __tmp_reg__, 16
+   .set __zero_reg__, 17
+#else
+   .set __tmp_reg__, 0
+   .set __zero_reg__, 1
+#endif
+
.globl __mulhi3
.type  __mulhi3, @function
 
 __mulhi3:
-   eorr28, r28
-   eorr20, r20
-   eorr21, r21 ; Initialize the result to 0: `S = 0;`.
+   ; Use Rzero:Rtmp to store the result.
+   clr   __tmp_reg__
+   clr   __zero_reg__ ; S = 0;
 
 __mulhi3_loop:
-   cp r24, r28
-   cpcr25, r28 ; `while (A != 0) { ... }`
-   breq   __mulhi3_end ; End the loop if A is 0.
+   clr   r21
+   cpr24, r21
+   cpc   r25, r21
+   breq  __mulhi3_end ; while (A != 0) {
 
-   movr29, r24
-   andi   r29, 1   ; `if (A & 1) { ... }`
-   breq   __mulhi3_loop_a  ; Omit the accumulation (`S += B;`) if  A's LSB 
is 0.
-
-   addr20, r22
-   adcr21, r23 ; Do the accumulation: `S += B;`.
+   mov   r21, r24
+   andi  r21, 1
+   breq  __mulhi3_loop_a  ;   if (A & 1)
+   add   __tmp_reg__, r22
+   adc   __zero_reg__, r23; S += B;
 
 __mulhi3_loop_a:
-   lsrr25
-   rorr24  ; `A = ((unsigned int) A) >> 1;`.
-   lslr22
-   rolr23  ; `B <<= 1;`
-
-   rjmp   __mulhi3_loop
+   lsr   r25
+   ror   r24  ;   A = ((unsigned int) A) >> 1;
+   lsl   r22
+   rol   r23  ;   B <<= 1;
+   rjmp  __mulhi3_loop; }
 
 __mulhi3_end:
-   movr24, r20
-   movr25, r21
-   ret
+   ; Return the result via R25:R24.
+   mov   r24, __tmp_reg__
+   mov   r25, __zero_reg__
+   ; Restore __zero_reg__ to 0.
+   clr   __zero_reg__
+   ret; return S;

diff  --git a/compiler-rt/lib/builtins/avr/mulqi3.S 
b/compiler-rt/lib/builtins/avr/mulqi3.S
index be0fa77ca7add..914735cc6458d 100644
--- a/compiler-rt/lib/builtins/avr/mulqi3.S
+

[PATCH] D124996: [clang][preprocessor] Fix unsigned-ness of utf8 char literals

2022-05-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/Lexer/utf8-char-literal.cpp:37-47
+#if __cplusplus == 201703L
+#  if defined(CHAR8_T)
+#if u8'\xff' == '\xff' // expected-warning {{right side of operator 
converted from negative value to unsigned}}
+#  error Something's not right.
+#endif
+#  else
+#if u8'\xff' != '\xff'

The equality operators seem backwards to what @tahonermann was saying -- I read 
his comment as:

C++17/14/11: u8'\xff' == '\xff'
C++17/14/11, -fchar8_t: u8'\xff' != '\xff'
C++20 and up: u8'\xff' != '\xff'
C++20 and up, -fno-char8_t: u8'\xff' == '\xff'

Hopefully Tom can clarify if I misunderstood.



Comment at: clang/test/Lexer/utf8-char-literal.cpp:65
+
+/// In C2x, 8u char literals are always unsigned
+#if __STDC_VERSION__ >= 202000L





Comment at: clang/test/Lexer/utf8-char-literal.cpp:70
+#  endif
+#endif

tbaeder wrote:
> I know indenting the preprocessor directives here isn't according to coding 
> style, but it helps a lot with readability.
I'm fine with the formatting -- it helps readability, and we don't require our 
tests to be correctly formatted anyway.


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

https://reviews.llvm.org/D124996

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


[PATCH] D125077: [compiler-rt][builtins] Fix wrong ABI of AVR __mulqi3 & __mulhi3

2022-05-06 Thread Ben Shi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
benshi001 marked an inline comment as done.
Closed by commit rG3902ebdd5793: [compiler-rt][builtins] Fix wrong ABI of AVR 
__mulqi3 & __mulhi3 (authored by benshi001).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D125077?vs=427601&id=427620#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125077

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/test/Preprocessor/avr-common.c
  compiler-rt/lib/builtins/avr/mulhi3.S
  compiler-rt/lib/builtins/avr/mulqi3.S

Index: compiler-rt/lib/builtins/avr/mulqi3.S
===
--- compiler-rt/lib/builtins/avr/mulqi3.S
+++ compiler-rt/lib/builtins/avr/mulqi3.S
@@ -8,24 +8,46 @@
 //
 // The corresponding C code is something like:
 //
-// int __mulqi3(char A, char B) {
-//   return __mulhi3((int) A, (int) B);
+// char __mulqi3(char A, char B) {
+//   int S = 0;
+//   while (A != 0) {
+// if (A & 1)
+//   S += B;
+// B <<= 1;
+// A = ((unsigned char) A) >> 1;
+//   }
+//   return S;
 // }
 //
+// __mulqi3 has special ABI, as the implementation of libgcc, the result is
+// returned via R24, while Rtmp and R22 are clobbered.
+//
 //===--===//
 
 	.text
 	.align 2
 
+#ifdef __AVR_TINY__
+	.set __tmp_reg__, 16
+#else
+	.set __tmp_reg__, 0
+#endif
+
 	.globl __mulqi3
 	.type  __mulqi3, @function
 
 __mulqi3:
-	movr25, r24
-	lslr25
-	sbcr25, r25 ; Promote A from char to int: `(int) A`.
-	movr23, r22
-	lslr23
-	sbcr23, r23 ; Promote B from char to int: `(int) B`.
-	rcall  __mulhi3 ; `__mulhi3((int) A, (int) B);`.
-	ret
+	clr   __tmp_reg__  ; S = 0;
+
+__mulqi3_loop:
+	cpi   r24, 0
+	breq  __mulqi3_end ; while (A != 0) {
+	sbrc  r24, 0   ;   if (A & 1)
+	add   __tmp_reg__, r22 ; S += B;
+	add   r22, r22 ;   B <<= 1;
+	lsr   r24  ;   A = ((unsigned char) A) >> 1;
+	rjmp  __mulqi3_loop; }
+
+__mulqi3_end:
+	mov   r24, __tmp_reg__
+	ret; return S;
Index: compiler-rt/lib/builtins/avr/mulhi3.S
===
--- compiler-rt/lib/builtins/avr/mulhi3.S
+++ compiler-rt/lib/builtins/avr/mulhi3.S
@@ -19,40 +19,53 @@
 //   return S;
 // }
 //
+// __mulhi3 has special ABI, as the implementation of libgcc, R25:R24 is used
+// to return result, while Rtmp/R21/R22/R23 are clobbered.
+//
 //===--===//
 
 	.text
 	.align 2
 
+#ifdef __AVR_TINY__
+	.set __tmp_reg__, 16
+	.set __zero_reg__, 17
+#else
+	.set __tmp_reg__, 0
+	.set __zero_reg__, 1
+#endif
+
 	.globl __mulhi3
 	.type  __mulhi3, @function
 
 __mulhi3:
-	eorr28, r28
-	eorr20, r20
-	eorr21, r21 ; Initialize the result to 0: `S = 0;`.
+	; Use Rzero:Rtmp to store the result.
+	clr   __tmp_reg__
+	clr   __zero_reg__ ; S = 0;
 
 __mulhi3_loop:
-	cp r24, r28
-	cpcr25, r28 ; `while (A != 0) { ... }`
-	breq   __mulhi3_end ; End the loop if A is 0.
+	clr   r21
+	cpr24, r21
+	cpc   r25, r21
+	breq  __mulhi3_end ; while (A != 0) {
 
-	movr29, r24
-	andi   r29, 1   ; `if (A & 1) { ... }`
-	breq   __mulhi3_loop_a  ; Omit the accumulation (`S += B;`) if  A's LSB is 0.
-
-	addr20, r22
-	adcr21, r23 ; Do the accumulation: `S += B;`.
+	mov   r21, r24
+	andi  r21, 1
+	breq  __mulhi3_loop_a  ;   if (A & 1)
+	add   __tmp_reg__, r22
+	adc   __zero_reg__, r23; S += B;
 
 __mulhi3_loop_a:
-	lsrr25
-	rorr24  ; `A = ((unsigned int) A) >> 1;`.
-	lslr22
-	rolr23  ; `B <<= 1;`
-
-	rjmp   __mulhi3_loop
+	lsr   r25
+	ror   r24  ;   A = ((unsigned int) A) >> 1;
+	lsl   r22
+	rol   r23  ;   B <<= 1;
+	rjmp  __mulhi3_loop; }
 
 __mulhi3_end:
-	movr24, r20
-	movr25, r21
-	ret
+	; Return the result via R25:R24.
+	mov   r24, __tmp_reg__
+	mov   r25, __zero_reg__
+	; Restore __zero_reg__ to 0.
+	clr   __zero_reg__
+	ret; return S;
Index: clang/test/Preprocessor/avr-common.c
===
--- clang/test/Preprocessor/avr-common.c
+++ clang/test/Preprocessor/avr-common.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny13 /dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu avr25 /dev/null | FileCheck -match-full-lines --check-prefixes=CHECK,AVR %s
 // RUN: %clang_cc1 -E -

[PATCH] D117229: [Analyzer] Produce SymbolCast for pointer to integer cast

2022-05-06 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 3 inline comments as done.
martong added a comment.
Herald added a project: All.

Thanks for the review Denys, and sorry for the long delay with the update. I 
hope that this patch is going to complement nicely the rest of the cast patches.




Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1088
 }
+
+SVal clang::ento::SValBuilder::simplifySymbolCast(nonloc::SymbolVal V,

ASDenysPetrov wrote:
> ASDenysPetrov wrote:
> > Notify the user about the contract.
> Mistake. `CastTy`, not `SafeTy`
Okay, I've added an assertion for this check.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:1095-1097
+auto SV = makeSymbolVal(SE);
+assert(SV == V);
+return SV;

ASDenysPetrov wrote:
> Explain please, why do you need to create a new `SymbolVal` here, but not 
> just returning `V` as long as you know that the type is the same?
> And `assert` also seems weird for me. If there's smth obscure that you're 
> trying to handle, please add some explaination comment.
You're right, we can just simply return `V`, I've updated like so. (I just 
wanted to make sure that the `makeSymbolVal` is consistent, but that has 
nothing to do with this patch.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117229

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


[PATCH] D117229: [Analyzer] Produce SymbolCast for pointer to integer cast

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

- add new assert for canonical type
- remove superflous assert about makeSymbolVal


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117229

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/produce-ptr-to-integer-symbolcast.cpp
  clang/test/Analysis/symbol-simplification-mem-region-to-int-cast.cpp

Index: clang/test/Analysis/symbol-simplification-mem-region-to-int-cast.cpp
===
--- /dev/null
+++ clang/test/Analysis/symbol-simplification-mem-region-to-int-cast.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -verify
+
+template 
+void clang_analyzer_dump(T);
+
+void clang_analyzer_eval(bool);
+
+void test_memory_region_to_integer_cast_and_symbol_simplification(int *p) {
+  long p_as_integer = (long)p;
+  if (42 - p_as_integer < 42)
+return;
+  // 42 - p_as_integer >= 42
+  // p_as_integer <= 0
+
+  if (p)
+return;
+  clang_analyzer_eval(p == 0);// expected-warning{{TRUE}}
+  clang_analyzer_eval(p_as_integer == 0); // expected-warning{{UNKNOWN}}
+
+  if (p_as_integer)
+return;
+  clang_analyzer_eval(p == 0);// expected-warning{{TRUE}}
+  clang_analyzer_eval(p_as_integer == 0); // expected-warning{{TRUE}}
+
+  (void)p_as_integer;
+  (void)p;
+}
Index: clang/test/Analysis/produce-ptr-to-integer-symbolcast.cpp
===
--- /dev/null
+++ clang/test/Analysis/produce-ptr-to-integer-symbolcast.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -analyzer-config support-symbolic-integer-casts=true \
+// RUN:   -triple x86_64-pc-linux-gnu \
+// RUN:   -verify
+
+template 
+void clang_analyzer_dump(T);
+
+void test_memory_region_to_integer_cast(int *p) {
+  long p_int = (long)p;
+  clang_analyzer_dump(p); // expected-warning{{&SymRegion{reg_$0}}}
+  clang_analyzer_dump(p_int); // expected-warning{{(long) (reg_$0)}}
+}
+
+void test_label_to_integer_cast(bool coin) {
+  int x = 0;
+p: ++x;
+  if (coin)
+goto p;
+
+  // FIXME, below we should produce a SymbolCast instead of the LocAsInteger.
+  // However, for that we'd need to be able to store a loc::GotoLabel SVal
+  // inside the SymbolCast. But currently we can put only another SymExpr
+  // inside a SymbolCast.
+
+  // Use of GNU address-of-label extension.
+  clang_analyzer_dump((long)&&p); // expected-warning{{&&p [as 64 bit integer]}}
+}
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -773,6 +773,16 @@
   //QualType elemTy = cast(originalTy)->getElementType();
   //QualType pointerTy = C.getPointerType(elemTy);
 }
+
+AnalyzerOptions &Opts =
+StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
+if (Opts.ShouldSupportSymbolicIntegerCasts) {
+  const MemRegion *R = V.getRegion();
+  if (R && !OriginalTy.isNull())
+if (const auto *SR = dyn_cast(R))
+  return simplifySymbolCast(SR->getSymbol(), CastTy);
+}
+
 const unsigned BitWidth = Context.getIntWidth(CastTy);
 return makeLocAsInteger(Val.castAs(), BitWidth);
   }
@@ -1009,8 +1019,12 @@
   return V;
 }
 
-SVal clang::ento::SValBuilder::simplifySymbolCast(nonloc::SymbolVal V,
+SVal clang::ento::SValBuilder::simplifySymbolCast(SymbolRef SE,
   QualType CastTy) {
+  QualType T = Context.getCanonicalType(SE->getType());
+  if (!isa(SE))
+return makeNonLoc(SE, T, CastTy);
+
   // We use seven conditions to recognize a simplification case.
   // For the clarity let `CastTy` be `C`, SE->getType() - `T`, root type - `R`,
   // prefix `u` for unsigned, `s` for signed, no prefix - any sign:
@@ -1044,15 +1058,6 @@
   //  (uint)(ushort)(ushort x) -> (uint)(ushort x)
   //  (llong)(ulong)(uint x) -> (llong)(uint x) (sizeof(ulong) == sizeof(uint))
 
-  SymbolRef SE = V.getSymbol();
-  QualType T = Context.getCanonicalType(SE->getType());
-
-  if (T == CastTy)
-return V;
-
-  if (!isa(SE))
-return makeNonLoc(SE, T, CastTy);
-
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
@@ -1080,3 +1085,14 @@
 
   return makeNonLoc(SE, T, CastTy);
 

[clang] 102824f - [clang][X86] Rename some intrinsics tests to use the *-builtins.c naming convention

2022-05-06 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2022-05-06T14:49:46+01:00
New Revision: 102824f04893452b6d1602a8d57949844b07bef9

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

LOG: [clang][X86] Rename some intrinsics tests to use the *-builtins.c naming 
convention

Added: 
clang/test/CodeGen/X86/avx512cd-builtins.c
clang/test/CodeGen/X86/avx512vlvp2intersect-builtins.c
clang/test/CodeGen/X86/avx512vp2intersect-builtins.c
clang/test/CodeGen/X86/cet-builtins.c
clang/test/CodeGen/X86/cldemote-builtins.c

Modified: 


Removed: 
clang/test/CodeGen/X86/avx512cdintrin.c
clang/test/CodeGen/X86/cetintrin.c
clang/test/CodeGen/X86/cldemote.c
clang/test/CodeGen/X86/intel-avx512vlvp2intersect.c
clang/test/CodeGen/X86/intel-avx512vp2intersect.c



diff  --git a/clang/test/CodeGen/X86/avx512cdintrin.c 
b/clang/test/CodeGen/X86/avx512cd-builtins.c
similarity index 100%
rename from clang/test/CodeGen/X86/avx512cdintrin.c
rename to clang/test/CodeGen/X86/avx512cd-builtins.c

diff  --git a/clang/test/CodeGen/X86/intel-avx512vlvp2intersect.c 
b/clang/test/CodeGen/X86/avx512vlvp2intersect-builtins.c
similarity index 100%
rename from clang/test/CodeGen/X86/intel-avx512vlvp2intersect.c
rename to clang/test/CodeGen/X86/avx512vlvp2intersect-builtins.c

diff  --git a/clang/test/CodeGen/X86/intel-avx512vp2intersect.c 
b/clang/test/CodeGen/X86/avx512vp2intersect-builtins.c
similarity index 100%
rename from clang/test/CodeGen/X86/intel-avx512vp2intersect.c
rename to clang/test/CodeGen/X86/avx512vp2intersect-builtins.c

diff  --git a/clang/test/CodeGen/X86/cetintrin.c 
b/clang/test/CodeGen/X86/cet-builtins.c
similarity index 100%
rename from clang/test/CodeGen/X86/cetintrin.c
rename to clang/test/CodeGen/X86/cet-builtins.c

diff  --git a/clang/test/CodeGen/X86/cldemote.c 
b/clang/test/CodeGen/X86/cldemote-builtins.c
similarity index 100%
rename from clang/test/CodeGen/X86/cldemote.c
rename to clang/test/CodeGen/X86/cldemote-builtins.c



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


[PATCH] D124966: Thread safety analysis: Handle compound assignment and ->* overloads

2022-05-06 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert updated this revision to Diff 427623.
aaronpuchert added a comment.

Use 1 instead of 0 just to be sure. We don't want to trigger warnings about 
division by zero.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124966

Files:
  clang/lib/Analysis/ThreadSafety.cpp
  clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Index: clang/test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- clang/test/SemaCXX/warn-thread-safety-analysis.cpp
+++ clang/test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -82,6 +82,9 @@
   T* ptr_;
 };
 
+template
+U& operator->*(const SmartPtr& ptr, U T::*p) { return ptr->*p; }
+
 
 // For testing destructor calls and cleanup.
 class MyString {
@@ -4338,6 +4341,21 @@
 
   void operator()() { }
 
+  Data& operator+=(int);
+  Data& operator-=(int);
+  Data& operator*=(int);
+  Data& operator/=(int);
+  Data& operator%=(int);
+  Data& operator^=(int);
+  Data& operator&=(int);
+  Data& operator|=(int);
+  Data& operator<<=(int);
+  Data& operator>>=(int);
+  Data& operator++();
+  Data& operator++(int);
+  Data& operator--();
+  Data& operator--(int);
+
 private:
   int dat;
 };
@@ -4404,6 +4422,20 @@
   // expected-warning {{reading variable 'datap1_' requires holding mutex 'mu_'}}
 data_ = *datap2_; // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}} \
   // expected-warning {{reading the value pointed to by 'datap2_' requires holding mutex 'mu_'}}
+data_ += 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ -= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ *= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ /= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ %= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ ^= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ &= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ |= 1;   // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ <<= 1;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_ >>= 1;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+++data_;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_++;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+--data_;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
+data_--;  // expected-warning {{writing variable 'data_' requires holding mutex 'mu_' exclusively}}
 
 data_[0] = 0; // expected-warning {{reading variable 'data_' requires holding mutex 'mu_'}}
 (*datap2_)[0] = 0;// expected-warning {{reading the value pointed to by 'datap2_' requires holding mutex 'mu_'}}
@@ -4923,6 +4955,8 @@
   SmartPtr  sp GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
   SmartPtr sq GUARDED_BY(mu1) PT_GUARDED_BY(mu2);
 
+  static constexpr int Cell::*pa = &Cell::a;
+
   void test1() {
 mu1.ReaderLock();
 mu2.Lock();
@@ -4931,6 +4965,7 @@
 if (*sp == 0) doSomething();
 *sp = 0;
 sq->a = 0;
+sq->*pa = 0;
 
 if (sp[0] == 0) doSomething();
 sp[0] = 0;
@@ -4946,6 +4981,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 *sp = 0;   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 sq->a = 0; // expected-warning {{reading variable 'sq' requires holding mutex 'mu1'}}
+sq->*pa = 0;   // expected-warning {{reading variable 'sq' requires holding mutex 'mu1'}}
 
 if (sp[0] == 0) doSomething();   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
 sp[0] = 0;   // expected-warning {{reading variable 'sp' requires holding mutex 'mu1'}}
@@ -4962,6 +4998,7 @@
 if (*sp == 0) doSomething();   // expected-warning {{reading the value pointed to by 'sp' requires holding mutex 'mu2'}}
 *sp = 0;   // expected-warning {{reading the value pointed to by 'sp' requires holding mutex 'mu2'}}
 sq->a = 0; // expected-warning {{reading the value pointed to by 'sq' requires holding mutex 'mu2'}}
+ 

[PATCH] D124674: [analyzer] Indicate if a parent state is infeasible

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

- Fix typos in essay


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124674

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp
  clang/test/Analysis/infeasible-sink.c

Index: clang/test/Analysis/infeasible-sink.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-sink.c
@@ -0,0 +1,80 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// Here we test that if it turns out that the parent state is infeasible then
+// both children States (more precisely the ExplodedNodes) are marked as a
+// Sink.
+// We rely on existing defects of the underlying constraint solver. However,
+// in the future we might strengthen the solver to discover the infeasibility
+// right when we create the parent state. At that point some of these tests
+// will fail, and either we shall find another solver weakness to have the test
+// case functioning, or we shall simply remove that.
+
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(int);
+
+void test1(int x) {
+  if (x * x != 4)
+return;
+  if (x < 0 || x > 1)
+return;
+
+  // { x^2 == 4 and x:[0,1] }
+  // This state is already infeasible.
+
+  // Perfectly constraining 'x' will trigger constant folding,
+  // when we realize we were already infeasible.
+  // The same happens for the 'else' branch.
+  if (x == 0) {
+clang_analyzer_warnIfReached(); // no-warning
+  } else {
+clang_analyzer_warnIfReached(); // no-warning
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+  (void)x;
+}
+
+int a, b, c, d, e;
+void test2() {
+
+  if (a == 0)
+return;
+
+  if (e != c)
+return;
+
+  d = e - c;
+  b = d;
+  a -= d;
+
+  if (a != 0)
+return;
+
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+
+  /* The BASELINE passes these checks ('wrning' is used to avoid lit to match)
+  // The parent state is already infeasible, look at this contradiction:
+  clang_analyzer_eval(b > 0);  // expected-wrning{{FALSE}}
+  clang_analyzer_eval(b <= 0); // expected-wrning{{FALSE}}
+  // Crashes with expensive checks.
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning, OK
+return;
+  }
+  // Should not be reachable.
+  clang_analyzer_warnIfReached(); // expected-wrning{{REACHABLE}}
+  */
+
+  // The parent state is already infeasible, but we realize that only if b is
+  // constrained.
+  clang_analyzer_eval(b > 0);  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b <= 0); // expected-warning{{UNKNOWN}}
+  if (b > 0) {
+clang_analyzer_warnIfReached(); // no-warning
+return;
+  }
+  clang_analyzer_warnIfReached(); // no-warning
+}
Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -55,7 +55,7 @@
 
 ProgramState::ProgramState(const ProgramState &RHS)
 : stateMgr(RHS.stateMgr), Env(RHS.Env), store(RHS.store), GDM(RHS.GDM),
-  refCount(0) {
+  PosteriorlyOverconstrained(RHS.PosteriorlyOverconstrained), refCount(0) {
   stateMgr->getStoreManager().incrementReferenceCount(store);
 }
 
@@ -429,6 +429,12 @@
   return getStateManager().getPersistentState(NewSt);
 }
 
+ProgramStateRef ProgramState::cloneAsPosteriorlyOverconstrained() const {
+  ProgramState NewSt(*this);
+  NewSt.PosteriorlyOverconstrained = true;
+  return getStateManager().getPersistentState(NewSt);
+}
+
 void ProgramState::setStore(const StoreRef &newStore) {
   Store newStoreStore = newStore.getStore();
   if (newStoreStore)
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -41,3 +41,32 @@
 return ConditionTruthVal(true);
   return {};
 }
+
+ConstraintManager::ProgramStatePair
+ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
+  ProgramStateRef StTrue = assume(State, Cond, true);
+
+  if (!StTrue) {
+ProgramStateRef StFalse = assume(State, Cond, false);
+if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
+  ProgramStateRef StInfeasible = State->cloneAsPosteriorlyOverconstrained();
+  assert(StInfeasible->isPosteriorlyOverconstrained());
+  // Checkers might

[PATCH] D123009: [Sema] Enum conversion warning when one signed and other unsigned.

2022-05-06 Thread Micah Weston via Phabricator via cfe-commits
red1bluelost updated this revision to Diff 427627.
red1bluelost marked 2 inline comments as done.
red1bluelost added a comment.

Addresses the last couple comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123009

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/enum-enum-conversion.c
  clang/test/Sema/enum-sign-conversion.c

Index: clang/test/Sema/enum-sign-conversion.c
===
--- clang/test/Sema/enum-sign-conversion.c
+++ clang/test/Sema/enum-sign-conversion.c
@@ -1,13 +1,45 @@
-// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -fsyntax-only -verify -DUNSIGNED -Wsign-conversion %s
-// RUN: %clang_cc1 -triple=x86_64-pc-win32 -fsyntax-only -verify -Wsign-conversion %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -fsyntax-only -Wsign-conversion -verify=unsigned,both %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -fsyntax-only -Wconversion -verify=unsigned,both %s
+// RUN: %clang_cc1 -triple=x86_64-pc-win32 -fsyntax-only -verify -Wsign-conversion -verify=win32,both %s
 
 // PR35200
 enum X { A,B,C};
 int f(enum X x) {
-#ifdef UNSIGNED
-  return x; // expected-warning {{implicit conversion changes signedness: 'enum X' to 'int'}}
-#else
-  // expected-no-diagnostics
-  return x;
-#endif
+  return x; // unsigned-warning {{implicit conversion changes signedness: 'enum X' to 'int'}}
+}
+
+enum SE1 { N1 = -1 }; // Always a signed underlying type.
+enum E1 { P1 };   // Unsigned underlying type except on Windows.
+
+// ensure no regression with enum to sign (related to enum-enum-conversion.c)
+int f1(enum E1 E) {
+  return E; // unsigned-warning {{implicit conversion changes signedness: 'enum E1' to 'int'}}
+}
+
+enum E1 f2(int E) {
+  return E; // unsigned-warning {{implicit conversion changes signedness: 'int' to 'enum E1'}}
+}
+
+int f3(enum SE1 E) {
+  return E; // shouldn't warn
+}
+
+enum SE1 f4(int E) {
+  return E; // shouldn't warn
+}
+
+unsigned f5(enum E1 E) {
+  return E; // win32-warning {{implicit conversion changes signedness: 'enum E1' to 'unsigned int'}}
+}
+
+enum E1 f6(unsigned E) {
+  return E; // win32-warning {{implicit conversion changes signedness: 'unsigned int' to 'enum E1'}}
+}
+
+unsigned f7(enum SE1 E) {
+  return E; // both-warning {{implicit conversion changes signedness: 'enum SE1' to 'unsigned int'}}
+}
+
+enum SE1 f8(unsigned E) {
+  return E; // both-warning {{implicit conversion changes signedness: 'unsigned int' to 'enum SE1'}}
 }
Index: clang/test/Sema/enum-enum-conversion.c
===
--- /dev/null
+++ clang/test/Sema/enum-enum-conversion.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -fsyntax-only -Wenum-conversion -verify %s
+// RUN: %clang_cc1 -triple=x86_64-pc-linux-gnu -fsyntax-only -Wconversion -verify %s
+
+// Signed enums
+enum SE1 { N1 = -1 };
+enum SE2 { N2 = -2 };
+// Unsigned unums
+enum UE1 { P1 };
+enum UE2 { P2 };
+
+enum UE2 f1(enum UE1 E) {
+  return E; // expected-warning {{implicit conversion from enumeration type 'enum UE1' to different enumeration type 'enum UE2'}}
+}
+
+enum SE1 f2(enum UE1 E) {
+  return E; // expected-warning {{implicit conversion from enumeration type 'enum UE1' to different enumeration type 'enum SE1'}}
+}
+
+enum UE1 f3(enum SE1 E) {
+  return E; // expected-warning {{implicit conversion from enumeration type 'enum SE1' to different enumeration type 'enum UE1'}}
+}
+
+enum SE2 f4(enum SE1 E) {
+  return E; // expected-warning {{implicit conversion from enumeration type 'enum SE1' to different enumeration type 'enum SE2'}}
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13534,9 +13534,10 @@
 // Fall through for non-constants to give a sign conversion warning.
   }
 
-  if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
-  (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
-   LikelySourceRange.Width == TargetRange.Width)) {
+  if ((!isa(Target) || !isa(Source)) &&
+  ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
+   (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
+LikelySourceRange.Width == TargetRange.Width))) {
 if (S.SourceMgr.isInSystemMacro(CC))
   return;
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -110,6 +110,9 @@
   `_.
 - ``-Wunused-but-set-variable`` now also warns if the variable is only used
   by unary operators.
+- ``-Wenum-conversion`` now warns on converting a signed enum of one type to an
+  unsigned enum of a different type (or vice versa) 

[PATCH] D123009: [Sema] Enum conversion warning when one signed and other unsigned.

2022-05-06 Thread Micah Weston via Phabricator via cfe-commits
red1bluelost marked an inline comment as done.
red1bluelost added a comment.

If that's all good, could you commit on my behalf. Here is name and email: 
Micah Weston (micahswes...@gmail.com)

Thanks for the great reviews! It was really helpful with learning the frontend 
stuff.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123009

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


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

2022-05-06 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas created this revision.
Herald added subscribers: hiraditya, kristof.beyls.
Herald added a project: All.
pratlucas requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, MaskRay.
Herald added projects: clang, LLVM.

Currently the a AAPCS compliant frame record is not always created for
functions when it should. Although a consistent frame record might not
be required in some cases, there are still scenarios where applications
may want to make use of the call hierarchy made available trough it.

In order to enable the use of AAPCS compliant frame records whilst keep
backwards compatibility, this patch introduces a new command-line option
(`-mframe-chain=[none|aapcs|aapcs+leaf]`) for Aarch32 and Thumb backends.
The option allows users to explicitly select when to use it, and is also
useful to ensure the extra overhead introduced by the frame records is
only introduced when necessary, in particular for Thumb targets.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125094

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMFrameLowering.cpp
  llvm/lib/Target/ARM/ARMSubtarget.h
  llvm/lib/Target/ARM/Thumb1FrameLowering.cpp
  llvm/test/CodeGen/ARM/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/ARM/frame-chain.ll
  llvm/test/CodeGen/Thumb/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/Thumb/frame-chain.ll

Index: llvm/test/CodeGen/Thumb/frame-chain.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Thumb/frame-chain.ll
@@ -0,0 +1,301 @@
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all | FileCheck %s --check-prefixes=FP,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf | FileCheck %s --check-prefixes=FP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none | FileCheck %s --check-prefixes=NOFP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP-AAPCS
+
+define dso_local noundef i32 @leaf(i32 noundef %0) {
+; LEAF-FP-LABEL: leaf:
+; LEAF-FP:   @ %bb.0:
+; LEAF-FP-NEXT:.pad #4
+; LEAF-FP-NEXT:sub sp, #4
+; LEAF-FP-NEXT:str r0, [sp]
+; LEAF-FP-NEXT:adds r0, r0, #4
+; LEAF-FP-NEXT:add sp, #4
+; LEAF-FP-NEXT:bx lr
+;
+; LEAF-FP-AAPCS-LABEL: leaf:
+; LEAF-FP-AAPCS:   @ %bb.0:
+; LEAF-FP-AAPCS-NEXT:.save {lr}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:mov lr, r11
+; LEAF-FP-AAPCS-NEXT:.save {r11}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-FP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-FP-AAPCS-NEXT:.pad #4
+; LEAF-FP-AAPCS-NEXT:sub sp, #4
+; LEAF-FP-AAPCS-NEXT:str r0, [sp]
+; LEAF-FP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-FP-AAPCS-NEXT:add sp, #4
+; LEAF-FP-AAPCS-NEXT:pop {lr}
+; LEAF-FP-AAPCS-NEXT:mov r11, lr
+; LEAF-FP-AAPCS-NEXT:pop {r1}
+; LEAF-FP-AAPCS-NEXT:bx r1
+;
+; LEAF-NOFP-LABEL: leaf:
+; LEAF-NOFP:   @ %bb.0:
+; LEAF-NOFP-NEXT:.pad #4
+; LEAF-NOFP-NEXT:sub sp, #4
+; LEAF-NOFP-NEXT:str r0, [sp]
+; LEAF-NOFP-NEXT:adds r0, r0, #4
+; LEAF-NOFP-NEXT:add sp, #4
+; LEAF-NOFP-NEXT:bx lr
+;
+; LEAF-NOFP-AAPCS-LABEL: leaf:
+; LEAF-NOFP-AAPCS:   @ %bb.0:
+; LEAF-NOFP-AAPCS-NEXT:.save {lr}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov lr, r11
+; LEAF-NOFP-AAPCS-NEXT:.save {r11}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-NOFP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-NOFP-AAPCS-NEXT:.pad #4
+; LEAF-NOFP-AAPCS-NEXT:sub sp, #4
+; LEAF-NOFP-AAPCS-NEXT:str r0, [sp]
+; LEAF-NOFP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-NOFP-AAPCS-NEXT:add sp, #4
+; LEAF-NOFP-AAPCS-NEXT:pop {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov r11, lr
+; LEAF-NOFP-AAPCS-NEXT:pop {r1}
+; LEAF-NOFP-AAPCS-NEXT:bx r1
+  %2 = alloca i32, align 4
+  store i32

[PATCH] D125088: [clangd] Add parsing for IgnoreHeaders config option

2022-05-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp:259
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);

A



Comment at: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp:261
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].Diagnostics.Includes.IgnoreHeader,
+  ElementsAre(val("foo"), val("bar")));

nit: maybe `Results.front()` but up to you


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

https://reviews.llvm.org/D125088

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


[PATCH] D54943: [clang-tidy] implement new check 'misc-const-correctness' to add 'const' to unmodified variables

2022-05-06 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 427629.
JonasToth added a comment.

- fix documentation reference


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-const-correctness.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-cxx17.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-pointer-as-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-templates.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-transform-pointer-as-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-transform-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-unaligned.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -1251,13 +1251,13 @@
   AST =
   buildASTFromCode("void f() { int* x[2]; for (int* e : x) e = nullptr; }");
   Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
-  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_TRUE(isMutated(Results, AST.get()));
 
   AST = buildASTFromCode(
   "typedef int* IntPtr;"
   "void f() { int* x[2]; for (IntPtr e : x) e = nullptr; }");
   Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
-  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
 TEST(ExprMutationAnalyzerTest, RangeForArrayByConstRef) {
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -445,14 +445,16 @@
   // array is considered modified if the loop-variable is a non-const reference.
   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
   hasUnqualifiedDesugaredType(referenceType(pointee(arrayType(;
-  const auto RefToArrayRefToElements = match(
-  findAll(stmt(cxxForRangeStmt(
-   hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
-   .bind(NodeID::value)),
-   hasRangeStmt(DeclStmtToNonRefToArray),
-   hasRangeInit(canResolveToExpr(equalsNode(Exp)
-  .bind("stmt")),
-  Stm, Context);
+  const auto RefToArrayRefToElements =
+  match(findAll(stmt(cxxForRangeStmt(
+ hasLoopVariable(
+ varDecl(anyOf(hasType(nonConstReferenceType()),
+   hasType(nonConstPointerType(
+ .bind(NodeID::value)),
+ hasRangeStmt(DeclStmtToNonRefToArray),
+ hasRangeInit(canResolveToExpr(equalsNode(Exp)
+.bind("stmt")),
+Stm, Context);
 
   if (const auto *BadRangeInitFromArray =
   selectFirst("stmt", RefToArrayRefToElements))
Index: clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
@@ -0,0 +1,958 @@
+// RUN: %check_clang_tidy %s misc-const-correctness %t -- \
+// RUN:   -config="{CheckOptions: [\
+// RUN:   {key: 'misc-const-correctness.TransformValues', value: true}, \
+// RUN:   {key: 'misc-const-correctness.WarnPointersAsValues', value: false}, \
+// RUN:   {key: 'misc-const-correctness.TransformPointersAsValues', value: false}, \
+// RUN:   ]}" -- -fno-delayed-template-parsing
+
+// --- Provide test samples for primitive builtins -
+// - every 'p_*' variable is a 'potential_const_*' variable
+// - every 'np_*' variable is a 'non_potential_const_*' variable
+
+bool global;
+char np_global = 0; // globals can't be known to be const
+
+// FIXME: 'static' globals are not matched right now. They could be analyzed but aren't right now.
+static int p_static_global = 42;
+
+namespace foo {
+int scoped;
+float np_scoped = 1; // namespace variables are like globals
+} // namespa

[PATCH] D125088: [clangd] Add parsing for IgnoreHeaders config option

2022-05-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp:259
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);

kbobyrev wrote:
> A
(sorry, the UI is laggy; please disregard this one)


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

https://reviews.llvm.org/D125088

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


[clang-tools-extra] 9fe89a1 - [clangd] Add parsing for IgnoreHeaders config option

2022-05-06 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-05-06T16:11:37+02:00
New Revision: 9fe89a1f0fa6d88aa4786580b89e81dc906fcc52

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

LOG: [clangd] Add parsing for IgnoreHeaders config option

Added: 


Modified: 
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 9e4a4e0792df2..ec39bb9686640 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -128,6 +128,7 @@ class Parser {
 Dict.handle("UnusedIncludes", [&](Node &N) {
   F.UnusedIncludes = scalarValue(N, "UnusedIncludes");
 });
+Dict.handle("Includes", [&](Node &N) { parse(F.Includes, N); });
 Dict.handle("ClangTidy", [&](Node &N) { parse(F.ClangTidy, N); });
 Dict.parse(N);
   }
@@ -154,6 +155,15 @@ class Parser {
 Dict.parse(N);
   }
 
+  void parse(Fragment::DiagnosticsBlock::IncludesBlock &F, Node &N) {
+DictParser Dict("Includes", this);
+Dict.handle("IgnoreHeader", [&](Node &N) {
+  if (auto Values = scalarValues(N))
+F.IgnoreHeader = std::move(*Values);
+});
+Dict.parse(N);
+  }
+
   void parse(Fragment::IndexBlock &F, Node &N) {
 DictParser Dict("Index", this);
 Dict.handle("Background",

diff  --git a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp 
b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
index d4be2e9ad4eb0..143bcf99fc547 100644
--- a/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -247,6 +247,20 @@ TEST(ParseYAML, InlayHints) {
   EXPECT_EQ(Results[0].InlayHints.DeducedTypes, llvm::None);
 }
 
+TEST(ParseYAML, IncludesIgnoreHeader) {
+  CapturedDiags Diags;
+  Annotations YAML(R"yaml(
+Diagnostics:
+  Includes:
+IgnoreHeader: [foo, bar]
+  )yaml");
+  auto Results =
+  Fragment::parseYAML(YAML.code(), "config.yaml", Diags.callback());
+  ASSERT_THAT(Diags.Diagnostics, IsEmpty());
+  ASSERT_EQ(Results.size(), 1u);
+  EXPECT_THAT(Results[0].Diagnostics.Includes.IgnoreHeader,
+  ElementsAre(val("foo"), val("bar")));
+}
 } // namespace
 } // namespace config
 } // namespace clangd



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


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

2022-05-06 Thread Lucas Prates via Phabricator via cfe-commits
pratlucas updated this revision to Diff 427632.
pratlucas added a comment.

Addressing linting messages.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125094

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMFrameLowering.cpp
  llvm/lib/Target/ARM/ARMSubtarget.h
  llvm/lib/Target/ARM/Thumb1FrameLowering.cpp
  llvm/test/CodeGen/ARM/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/ARM/frame-chain.ll
  llvm/test/CodeGen/Thumb/frame-chain-reserved-fp.ll
  llvm/test/CodeGen/Thumb/frame-chain.ll

Index: llvm/test/CodeGen/Thumb/frame-chain.ll
===
--- /dev/null
+++ llvm/test/CodeGen/Thumb/frame-chain.ll
@@ -0,0 +1,301 @@
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all | FileCheck %s --check-prefixes=FP,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=all -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-FP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf | FileCheck %s --check-prefixes=FP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=non-leaf -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=FP-AAPCS,LEAF-NOFP-AAPCS
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none | FileCheck %s --check-prefixes=NOFP,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP
+; RUN: llc -mtriple thumb-arm-none-eabi -filetype asm -o - %s -frame-pointer=none -mattr=+aapcs-frame-chain-leaf | FileCheck %s --check-prefixes=NOFP-AAPCS,LEAF-NOFP-AAPCS
+
+define dso_local noundef i32 @leaf(i32 noundef %0) {
+; LEAF-FP-LABEL: leaf:
+; LEAF-FP:   @ %bb.0:
+; LEAF-FP-NEXT:.pad #4
+; LEAF-FP-NEXT:sub sp, #4
+; LEAF-FP-NEXT:str r0, [sp]
+; LEAF-FP-NEXT:adds r0, r0, #4
+; LEAF-FP-NEXT:add sp, #4
+; LEAF-FP-NEXT:bx lr
+;
+; LEAF-FP-AAPCS-LABEL: leaf:
+; LEAF-FP-AAPCS:   @ %bb.0:
+; LEAF-FP-AAPCS-NEXT:.save {lr}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:mov lr, r11
+; LEAF-FP-AAPCS-NEXT:.save {r11}
+; LEAF-FP-AAPCS-NEXT:push {lr}
+; LEAF-FP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-FP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-FP-AAPCS-NEXT:.pad #4
+; LEAF-FP-AAPCS-NEXT:sub sp, #4
+; LEAF-FP-AAPCS-NEXT:str r0, [sp]
+; LEAF-FP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-FP-AAPCS-NEXT:add sp, #4
+; LEAF-FP-AAPCS-NEXT:pop {lr}
+; LEAF-FP-AAPCS-NEXT:mov r11, lr
+; LEAF-FP-AAPCS-NEXT:pop {r1}
+; LEAF-FP-AAPCS-NEXT:bx r1
+;
+; LEAF-NOFP-LABEL: leaf:
+; LEAF-NOFP:   @ %bb.0:
+; LEAF-NOFP-NEXT:.pad #4
+; LEAF-NOFP-NEXT:sub sp, #4
+; LEAF-NOFP-NEXT:str r0, [sp]
+; LEAF-NOFP-NEXT:adds r0, r0, #4
+; LEAF-NOFP-NEXT:add sp, #4
+; LEAF-NOFP-NEXT:bx lr
+;
+; LEAF-NOFP-AAPCS-LABEL: leaf:
+; LEAF-NOFP-AAPCS:   @ %bb.0:
+; LEAF-NOFP-AAPCS-NEXT:.save {lr}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov lr, r11
+; LEAF-NOFP-AAPCS-NEXT:.save {r11}
+; LEAF-NOFP-AAPCS-NEXT:push {lr}
+; LEAF-NOFP-AAPCS-NEXT:.setfp r11, sp
+; LEAF-NOFP-AAPCS-NEXT:add r11, sp, #0
+; LEAF-NOFP-AAPCS-NEXT:.pad #4
+; LEAF-NOFP-AAPCS-NEXT:sub sp, #4
+; LEAF-NOFP-AAPCS-NEXT:str r0, [sp]
+; LEAF-NOFP-AAPCS-NEXT:adds r0, r0, #4
+; LEAF-NOFP-AAPCS-NEXT:add sp, #4
+; LEAF-NOFP-AAPCS-NEXT:pop {lr}
+; LEAF-NOFP-AAPCS-NEXT:mov r11, lr
+; LEAF-NOFP-AAPCS-NEXT:pop {r1}
+; LEAF-NOFP-AAPCS-NEXT:bx r1
+  %2 = alloca i32, align 4
+  store i32 %0, i32* %2, align 4
+  %3 = load i32, i32* %2, align 4
+  %4 = add nsw i32 %3, 4
+  ret i32 %4
+}
+
+define dso_local noundef i32 @non_leaf(i32 noundef %0) {
+; FP-LABEL: non_leaf:
+; FP:   @ %bb.0:
+; FP-NEXT:.save {r7, lr}
+; FP-NEXT:push {r7, lr}
+; FP-NEXT:.setfp r7, sp
+; FP-NEXT:add r7, sp, #0
+; FP-NEXT:.pad #8
+; FP-NEXT:sub sp, #8
+; FP-NEXT:str r0, [sp, #4]
+; FP-NEXT:bl leaf
+; FP-NEXT:adds r0, r0, #1
+; FP-NEXT:add sp, #8
+; FP-NEXT:pop {r7}
+; FP-NEXT:pop {r1}
+; FP-NEXT:bx r1
+;
+; FP-AAPCS-LABEL: non_leaf:
+; FP-AAPCS:   @ %bb.0:
+; FP-AAPCS-NEXT:.save {lr}
+; FP-AAPCS-NEXT:push {lr}
+; FP-AAPCS-NEXT:mov lr, r11
+; FP-AAPCS-NEXT:.save {r11}
+; FP-AAPCS-NEXT:push {lr}
+; FP-AAPCS-NEXT:.set

[clang] 499d0b9 - [clang] createInvocationFromCommandLine -> createInvocation, delete former. NFC

2022-05-06 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-05-06T16:21:48+02:00
New Revision: 499d0b96cb52c828e7fc4d58825b5e8b3f9931c5

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

LOG: [clang] createInvocationFromCommandLine -> createInvocation, delete 
former. NFC

(Followup from 40c13720a4b977d4347bbde53c52a4d0703823c2)

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

Added: 


Modified: 
clang/include/clang/Frontend/Utils.h
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
clang/tools/c-index-test/core_main.cpp
clang/tools/diagtool/ShowEnabledWarnings.cpp
clang/tools/libclang/Indexing.cpp
clang/unittests/Frontend/ASTUnitTest.cpp
clang/unittests/Frontend/CompilerInstanceTest.cpp
clang/unittests/Serialization/ModuleCacheTest.cpp
clang/unittests/Tooling/Syntax/TokensTest.cpp
clang/unittests/Tooling/Syntax/TreeTestBase.cpp
lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/Utils.h 
b/clang/include/clang/Frontend/Utils.h
index 47f795b388f7..1e8841429ffa 100644
--- a/clang/include/clang/Frontend/Utils.h
+++ b/clang/include/clang/Frontend/Utils.h
@@ -234,15 +234,6 @@ std::unique_ptr
 createInvocation(ArrayRef Args,
  CreateInvocationOptions Opts = {});
 
-/// Deprecated version of createInvocation with individual optional args.
-std::unique_ptr createInvocationFromCommandLine(
-ArrayRef Args,
-IntrusiveRefCntPtr Diags =
-IntrusiveRefCntPtr(),
-IntrusiveRefCntPtr VFS = nullptr,
-bool ShouldRecoverOnErrors = false,
-std::vector *CC1Args = nullptr, bool ProbePrecompiled = true);
-
 } // namespace clang
 
 #endif // LLVM_CLANG_FRONTEND_UTILS_H

diff  --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index 5f587cc1c023..1d0f472e9c6e 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -1729,8 +1729,11 @@ ASTUnit *ASTUnit::LoadFromCommandLine(
 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
   &StoredDiagnostics, nullptr);
 
-CI = createInvocationFromCommandLine(
-llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
+CreateInvocationOptions CIOpts;
+CIOpts.VFS = VFS;
+CIOpts.Diags = Diags;
+CI = createInvocation(llvm::makeArrayRef(ArgBegin, ArgEnd),
+  std::move(CIOpts));
 if (!CI)
   return nullptr;
   }

diff  --git a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp 
b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
index 2a98aab44ccb..49e814b31b43 100644
--- a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
+++ b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
@@ -104,12 +104,3 @@ clang::createInvocation(ArrayRef ArgList,
 return nullptr;
   return CI;
 }
-
-std::unique_ptr clang::createInvocationFromCommandLine(
-ArrayRef Args, IntrusiveRefCntPtr Diags,
-IntrusiveRefCntPtr VFS, bool ShouldRecoverOnErrors,
-std::vector *CC1Args, bool ProbePrecompiled) {
-  return createInvocation(
-  Args, CreateInvocationOptions{Diags, VFS, ShouldRecoverOnErrors,
-ProbePrecompiled, CC1Args});
-}

diff  --git a/clang/tools/c-index-test/core_main.cpp 
b/clang/tools/c-index-test/core_main.cpp
index 7037252ffa0e..c5f47baa8458 100644
--- a/clang/tools/c-index-test/core_main.cpp
+++ b/clang/tools/c-index-test/core_main.cpp
@@ -13,6 +13,7 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/Utils.h"
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/USRGeneration.h"
@@ -220,7 +221,9 @@ static bool printSourceSymbols(const char *Executable,
   ArgsWithProgName.append(Args.begin(), Args.end());
   IntrusiveRefCntPtr
 Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
-  auto CInvok = createInvocationFromCommandLine(ArgsWithProgName, Diags);
+  CreateInvocationOptions CIOpts;
+  CIOpts.Diags = Diags;
+  auto CInvok = createInvocation(ArgsWithProgName, std::move(CIOpts));
   if (!CInvok)
 return true;
 

diff  --git a/clang/tools/diagtool/ShowEnabledWarnings.cpp 
b/clang/tools/diagtool/ShowEnabledWarnings.cpp
index ae2d3e37e845..e5a7b2532824 100644
--- a/clang/tools/diagtool/ShowEnabledWarnings.cpp
+++ b/clang/tools/diagtool/ShowEnabledWarnings.cpp
@@ -59,15 +59,16 @@ createDiagnostics(unsigned int argc, char **argv) {
   // Buffer diagnostics from argument parsing so that we can output them using 
a
   // well formed diagnostic object.
   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnostic

[clang] d2405e1 - Fix lifetime of DiagnosticsEngine in diagtool.

2022-05-06 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-05-06T16:21:49+02:00
New Revision: d2405e1da5b6ee8d6568469610071d86414cdc93

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

LOG: Fix lifetime of DiagnosticsEngine in diagtool.

Added: 


Modified: 
clang/tools/diagtool/ShowEnabledWarnings.cpp

Removed: 




diff  --git a/clang/tools/diagtool/ShowEnabledWarnings.cpp 
b/clang/tools/diagtool/ShowEnabledWarnings.cpp
index e5a7b2532824..285efe6ae05b 100644
--- a/clang/tools/diagtool/ShowEnabledWarnings.cpp
+++ b/clang/tools/diagtool/ShowEnabledWarnings.cpp
@@ -68,7 +68,7 @@ createDiagnostics(unsigned int argc, char **argv) {
   CIOpts.Diags =
   new DiagnosticsEngine(DiagIDs, new DiagnosticOptions(), DiagsBuffer);
   std::unique_ptr Invocation =
-  createInvocation(Args, std::move(CIOpts));
+  createInvocation(Args, CIOpts);
   if (!Invocation)
 return nullptr;
 



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


[PATCH] D125012: [clang] createInvocationFromCommandLine -> createInvocation, delete former. NFC

2022-05-06 Thread Sam McCall 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 rG499d0b96cb52: [clang] createInvocationFromCommandLine -> 
createInvocation, delete former. NFC (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D125012?vs=427314&id=427634#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125012

Files:
  clang/include/clang/Frontend/Utils.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CreateInvocationFromCommandLine.cpp
  clang/tools/c-index-test/core_main.cpp
  clang/tools/diagtool/ShowEnabledWarnings.cpp
  clang/tools/libclang/Indexing.cpp
  clang/unittests/Frontend/ASTUnitTest.cpp
  clang/unittests/Frontend/CompilerInstanceTest.cpp
  clang/unittests/Serialization/ModuleCacheTest.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp
  clang/unittests/Tooling/Syntax/TreeTestBase.cpp
  lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp

Index: lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
===
--- lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
+++ lldb/source/Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.cpp
@@ -663,9 +663,11 @@
llvm::make_range(compiler_invocation_arguments.begin(),
 compiler_invocation_arguments.end()));
 
+  CreateInvocationOptions CIOpts;
+  CIOpts.Diags = diagnostics_engine;
   std::shared_ptr invocation =
-  clang::createInvocationFromCommandLine(compiler_invocation_argument_cstrs,
- diagnostics_engine);
+  clang::createInvocation(compiler_invocation_argument_cstrs,
+  std::move(CIOpts));
 
   if (!invocation)
 return nullptr;
Index: clang/unittests/Tooling/Syntax/TreeTestBase.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTestBase.cpp
+++ clang/unittests/Tooling/Syntax/TreeTestBase.cpp
@@ -134,7 +134,10 @@
 ArgsCStr.push_back(arg.c_str());
   }
 
-  Invocation = createInvocationFromCommandLine(ArgsCStr, Diags, FS);
+  CreateInvocationOptions CIOpts;
+  CIOpts.Diags = Diags;
+  CIOpts.VFS = FS;
+  Invocation = createInvocation(ArgsCStr, std::move(CIOpts));
   assert(Invocation);
   Invocation->getFrontendOpts().DisableFree = false;
   Invocation->getPreprocessorOpts().addRemappedFile(
Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -125,7 +125,10 @@
   Diags->setClient(new IgnoringDiagConsumer);
 std::vector Args = {"tok-test", "-std=c++03", "-fsyntax-only",
   FileName};
-auto CI = createInvocationFromCommandLine(Args, Diags, FS);
+CreateInvocationOptions CIOpts;
+CIOpts.Diags = Diags;
+CIOpts.VFS = FS;
+auto CI = createInvocation(Args, std::move(CIOpts));
 assert(CI);
 CI->getFrontendOpts().DisableFree = false;
 CI->getPreprocessorOpts().addRemappedFile(
Index: clang/unittests/Serialization/ModuleCacheTest.cpp
===
--- clang/unittests/Serialization/ModuleCacheTest.cpp
+++ clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -10,6 +10,7 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendActions.h"
+#include "clang/Frontend/Utils.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/FileSystem.h"
@@ -95,13 +96,15 @@
   MCPArg.append(ModuleCachePath);
   IntrusiveRefCntPtr Diags =
   CompilerInstance::createDiagnostics(new DiagnosticOptions());
+  CreateInvocationOptions CIOpts;
+  CIOpts.Diags = Diags;
 
   // First run should pass with no errors
   const char *Args[] = {"clang","-fmodules",  "-Fframeworks",
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocationFromCommandLine(Args, Diags);
+  createInvocation(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -124,7 +127,7 @@
  "-Fframeworks",  MCPArg.c_str(), "-working-directory",
  TestDir.c_str(), "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocationFromCommandLine(Args2, Diags);
+  createInvocation(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  &Instance.getModuleCache());
@@ -142,13 +145,15 @@
   MCPArg.append(

[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

2022-05-06 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 427635.
martong added a comment.

- Rebase to parent revision


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124758

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
  clang/test/Analysis/infeasible-crash.c

Index: clang/test/Analysis/infeasible-crash.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-crash.c
@@ -0,0 +1,38 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.cstring.OutOfBounds,alpha.unix.cstring.UninitializedRead \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// expected-no-diagnostics
+
+void *memmove(void *, const void *, unsigned long);
+
+typedef struct {
+  char a[1024];
+} b;
+int c;
+b *invalidate();
+int d() {
+  b *a = invalidate();
+  if (c < 1024)
+return 0;
+  int f = c & ~3, g = f;
+  g--;
+  if (g)
+return 0;
+
+  // Parent state is already infeasible.
+  // clang_analyzer_printState();
+  // "constraints": [
+  //   { "symbol": "(derived_$3{conj_$0{int, LC1, S728, #1},c}) & -4", "range": "{ [1, 1] }" },
+  //   { "symbol": "derived_$3{conj_$0{int, LC1, S728, #1},c}", "range": "{ [1024, 2147483647] }" }
+  // ],
+
+  // This sould not crash!
+  // It crashes in baseline, since there both true and false states are nullptr!
+  memmove(a->a, &a->a[f], c - f);
+
+  return 0;
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
@@ -22,9 +22,9 @@
 
 SimpleConstraintManager::~SimpleConstraintManager() {}
 
-ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef State,
-DefinedSVal Cond,
-bool Assumption) {
+ProgramStateRef SimpleConstraintManager::assumeInternal(ProgramStateRef State,
+DefinedSVal Cond,
+bool Assumption) {
   // If we have a Loc value, cast it to a bool NonLoc first.
   if (Optional LV = Cond.getAs()) {
 SValBuilder &SVB = State->getStateManager().getSValBuilder();
@@ -86,8 +86,8 @@
   }
 
   case nonloc::LocAsIntegerKind:
-return assume(State, Cond.castAs().getLoc(),
-  Assumption);
+return assumeInternal(State, Cond.castAs().getLoc(),
+  Assumption);
   } // end switch
 }
 
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -44,10 +44,10 @@
 
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-  ProgramStateRef StTrue = assume(State, Cond, true);
+  ProgramStateRef StTrue = assumeInternal(State, Cond, true);
 
   if (!StTrue) {
-ProgramStateRef StFalse = assume(State, Cond, false);
+ProgramStateRef StFalse = assumeInternal(State, Cond, false);
 if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
   ProgramStateRef StInfeasible = State->cloneAsPosteriorlyOverconstrained();
   assert(StInfeasible->isPosteriorlyOverconstrained());
@@ -63,10 +63,16 @@
 return ProgramStatePair(nullptr, StFalse);
   }
 
-  ProgramStateRef StFalse = assume(State, Cond, false);
+  ProgramStateRef StFalse = assumeInternal(State, Cond, false);
   if (!StFalse) {
 return ProgramStatePair(StTrue, nullptr);
   }
 
   return ProgramStatePair(StTrue, StFalse);
 }
+
+ProgramStateRef ConstraintManager::assume(ProgramStateRef State,
+  DefinedSVal Cond, bool Assumption) {
+  ConstraintManager::ProgramStatePair R = assumeDual(State, Cond);
+  return Assumption ? R.first : R.second;
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
@@ -36,8 +36,8 @@
 
   /// Ensures that the DefinedSVal conditional is expressed as a NonLoc by
   /// creating boolean casts to handle Loc's.
-  ProgramStateRef assume(ProgramStateRef State, DefinedSVal Cond,
- bool Assumption) override;
+

[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

2022-05-06 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 427636.
martong marked an inline comment as done.
martong added a comment.

- Remove ExprInspection checker from the test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124758

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
  clang/test/Analysis/infeasible-crash.c

Index: clang/test/Analysis/infeasible-crash.c
===
--- /dev/null
+++ clang/test/Analysis/infeasible-crash.c
@@ -0,0 +1,37 @@
+// RUN: %clang_analyze_cc1 %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.cstring.OutOfBounds,alpha.unix.cstring.UninitializedRead \
+// RUN:   -analyzer-config eagerly-assume=false \
+// RUN:   -verify
+
+// expected-no-diagnostics
+
+void *memmove(void *, const void *, unsigned long);
+
+typedef struct {
+  char a[1024];
+} b;
+int c;
+b *invalidate();
+int d() {
+  b *a = invalidate();
+  if (c < 1024)
+return 0;
+  int f = c & ~3, g = f;
+  g--;
+  if (g)
+return 0;
+
+  // Parent state is already infeasible.
+  // clang_analyzer_printState();
+  // "constraints": [
+  //   { "symbol": "(derived_$3{conj_$0{int, LC1, S728, #1},c}) & -4", "range": "{ [1, 1] }" },
+  //   { "symbol": "derived_$3{conj_$0{int, LC1, S728, #1},c}", "range": "{ [1024, 2147483647] }" }
+  // ],
+
+  // This sould not crash!
+  // It crashes in baseline, since there both true and false states are nullptr!
+  memmove(a->a, &a->a[f], c - f);
+
+  return 0;
+}
Index: clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp
@@ -22,9 +22,9 @@
 
 SimpleConstraintManager::~SimpleConstraintManager() {}
 
-ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef State,
-DefinedSVal Cond,
-bool Assumption) {
+ProgramStateRef SimpleConstraintManager::assumeInternal(ProgramStateRef State,
+DefinedSVal Cond,
+bool Assumption) {
   // If we have a Loc value, cast it to a bool NonLoc first.
   if (Optional LV = Cond.getAs()) {
 SValBuilder &SVB = State->getStateManager().getSValBuilder();
@@ -86,8 +86,8 @@
   }
 
   case nonloc::LocAsIntegerKind:
-return assume(State, Cond.castAs().getLoc(),
-  Assumption);
+return assumeInternal(State, Cond.castAs().getLoc(),
+  Assumption);
   } // end switch
 }
 
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -44,10 +44,10 @@
 
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeDual(ProgramStateRef State, DefinedSVal Cond) {
-  ProgramStateRef StTrue = assume(State, Cond, true);
+  ProgramStateRef StTrue = assumeInternal(State, Cond, true);
 
   if (!StTrue) {
-ProgramStateRef StFalse = assume(State, Cond, false);
+ProgramStateRef StFalse = assumeInternal(State, Cond, false);
 if (LLVM_UNLIKELY(!StFalse)) { // both infeasible
   ProgramStateRef StInfeasible = State->cloneAsPosteriorlyOverconstrained();
   assert(StInfeasible->isPosteriorlyOverconstrained());
@@ -63,10 +63,16 @@
 return ProgramStatePair(nullptr, StFalse);
   }
 
-  ProgramStateRef StFalse = assume(State, Cond, false);
+  ProgramStateRef StFalse = assumeInternal(State, Cond, false);
   if (!StFalse) {
 return ProgramStatePair(StTrue, nullptr);
   }
 
   return ProgramStatePair(StTrue, StFalse);
 }
+
+ProgramStateRef ConstraintManager::assume(ProgramStateRef State,
+  DefinedSVal Cond, bool Assumption) {
+  ConstraintManager::ProgramStatePair R = assumeDual(State, Cond);
+  return Assumption ? R.first : R.second;
+}
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SimpleConstraintManager.h
@@ -36,8 +36,8 @@
 
   /// Ensures that the DefinedSVal conditional is expressed as a NonLoc by
   /// creating boolean casts to handle Loc's.
-  ProgramStateRef assume(ProgramStateRef State, DefinedSVal Cond,
- bool Assumption) ove

[PATCH] D124758: [analyzer] Implement assume in terms of assumeDual

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



Comment at: clang/test/Analysis/infeasible-crash.c:3
+// RUN:   -analyzer-checker=core \
+// RUN:   
-analyzer-checker=alpha.unix.cstring.OutOfBounds,alpha.unix.cstring.UninitializedRead
 \
+// RUN:   -analyzer-checker=debug.ExprInspection \

steakhal wrote:
> Do we really need this?
No, thx. Removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124758

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


  1   2   3   >