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

2022-08-19 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added inline comments.
This revision is now accepted and ready to land.



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

carlosgalvezp wrote:
> njames93 wrote:
> > njames93 wrote:
> > > Can you add some cases with implicit capture (using [=] and [&])
> > I should have been more clear, you need to actually use the variables 
> > inside the lambda to implicitly capture them.
> Thanks, didn't know that! 
> 
> It's actually quite interesting, implicit lambda captures never trigger an 
> error:
> https://godbolt.org/z/cErf4jv8E
> 
> But it's probably good to keep the test anyway in case the lambda 
> implementation changes.
> 
What's more interesting about that is the error message that was emitted.
```
:6:16: warning: member '' of type 'const int' is const qualified 
[cppcoreguidelines-avoid-const-or-ref-data-members]
auto y3 = [x]{};
```
However this fix should accidentally fix the issue of unnamed members.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

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


[PATCH] D132209: [Clang][OpenMP] Make copyin clause on combined and composite construct work

2022-08-19 Thread Yuichiro Utsumi via Phabricator via cfe-commits
yutsumi created this revision.
yutsumi added reviewers: ABataev, jdoerfert, cchen.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
yutsumi requested review of this revision.
Herald added subscribers: openmp-commits, cfe-commits, sstefan1.
Herald added projects: clang, OpenMP.

Make copyin clause on the following constructs work.

- parallel for
- parallel for simd
- parallel sections

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132209

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  openmp/runtime/test/parallel/omp_parallel_copyin_combined.c

Index: openmp/runtime/test/parallel/omp_parallel_copyin_combined.c
===
--- /dev/null
+++ openmp/runtime/test/parallel/omp_parallel_copyin_combined.c
@@ -0,0 +1,110 @@
+// RUN: %libomp-compile-and-run
+#include "omp_testsuite.h"
+
+#define N 100
+
+int x1, x2, x3, x4, x5;
+#pragma omp threadprivate(x1, x2, x3, x4, x5)
+
+int test_omp_parallel_copyin() {
+  int a[N];
+  x1 = 1;
+
+#pragma omp parallel copyin(x1)
+#pragma omp for
+  for (int i = 0; i < N; i++)
+a[i] = i + x1;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x1) * 100) / 2);
+}
+
+int test_omp_parallel_for_copyin() {
+  int a[N];
+  x2 = 2;
+
+#pragma omp parallel for copyin(x2)
+  for (int i = 0; i < N; i++)
+a[i] = i + x2;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x2) * 100) / 2);
+}
+
+int test_omp_parallel_for_simd_copyin() {
+  int a[N];
+  x3 = 3;
+
+#pragma omp parallel for simd copyin(x3)
+  for (int i = 0; i < N; i++)
+a[i] = i + x3;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x3) * 100) / 2);
+}
+
+int test_omp_parallel_sections_copyin() {
+  int a = 0;
+  int b = 0;
+  x4 = 4;
+
+#pragma omp parallel sections copyin(x4)
+  {
+#pragma omp section
+{ a = x4; }
+
+#pragma omp section
+{ b = x4; }
+  }
+
+  return (a + b == x4 * 2);
+}
+
+int test_omp_parallel_master_copyin() {
+  int a[N];
+  x5 = 5;
+
+#pragma omp parallel master copyin(x5)
+  for (int i = 0; i < N; i++)
+a[i] = i + x5;
+
+  int sum = 0;
+
+  for (int i = 0; i < N; i++)
+sum += a[i];
+
+  return (sum == ((99 + 2 * x5) * 100) / 2);
+}
+
+int main() {
+  int num_failed = 0;
+
+  if (!test_omp_parallel_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_for_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_for_simd_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_sections_copyin())
+num_failed++;
+
+  if (!test_omp_parallel_master_copyin())
+num_failed++;
+
+  return num_failed;
+}
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -1593,6 +1593,19 @@
  const OMPExecutableDirective &,
  llvm::SmallVectorImpl &) {}
 
+static void emitOMPCopyinClause(CodeGenFunction &CGF,
+const OMPExecutableDirective &S) {
+  bool Copyins = CGF.EmitOMPCopyinClause(S);
+  if (Copyins) {
+// Emit implicit barrier to synchronize threads and avoid data races on
+// propagation master's thread values of threadprivate variables to local
+// instances of that variables of all other implicit threads.
+CGF.CGM.getOpenMPRuntime().emitBarrierCall(
+CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
+/*ForceSimpleCall=*/true);
+  }
+}
+
 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable(
 CodeGenFunction &CGF, const VarDecl *VD) {
   CodeGenModule &CGM = CGF.CGM;
@@ -1774,16 +1787,8 @@
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
 OMPPrivateScope PrivateScope(CGF);
-bool Copyins = CGF.EmitOMPCopyinClause(S);
+emitOMPCopyinClause(CGF, S);
 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope);
-if (Copyins) {
-  // Emit implicit barrier to synchronize threads and avoid data races on
-  // propagation master's thread values of threadprivate variables to local
-  // instances of that variables of all other implicit threads.
-  CGF.CGM.getOpenMPRuntime().emitBarrierCall(
-  CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false,
-  /*ForceSimpleCall=*/true);
-}
 CGF.EmitOMPPrivateClause(S, PrivateScope);
 CGF.EmitOMPReductionClauseInit(S, PrivateScope);
 (void)PrivateScope.Privatize();
@@ -4352,6 +4357,7 @@
   // directives: 'parallel' with 'for' directive.
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
 Action.Enter(CGF);
+emitOMPCopyinClause(CGF, S);
 (void)emitWorksharingDirective(CGF, S, S.hasCancel());
   };
   {
@@ -438

[PATCH] D131687: [Clang]Replace aarch64_sve_ldN intrinsic by aarch64_sve_ldN.sret

2022-08-19 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen accepted this revision.
sdesmalen added a comment.
This revision is now accepted and ready to land.

LGTM with nit addressed, thanks @CarolineConcatto!




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:8866
+  Value *Call = Builder.CreateCall(F, {Predicate, BasePtr});
+  unsigned MinElts = VTy->getElementCount().getKnownMinValue();
+  Value *Ret = llvm::PoisonValue::get(RetTy);

nit: `s/VTy->getElementCount().getKnownMinValue()/VTy->getMinNumElements()/`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131687

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


[clang] a2dd613 - [clang][Modules] Fix a regression in handling missing framework headers.

2022-08-19 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-08-19T09:13:22+01:00
New Revision: a2dd6130d49777d63c2d1b641bd8e56f26fa0822

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

LOG: [clang][Modules] Fix a regression in handling missing framework headers.

The commit of af2d11b1d5c1508b506825df460656e0151cd3b0 missed a case where
the value of a suggested module needed to be reset to nullptr.  Fixed thus
and added a testcase to cover the circumstance.

Added: 
clang/test/Modules/missing-framework-header.cpp

Modified: 
clang/lib/Lex/PPDirectives.cpp

Removed: 




diff  --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index 08ac45710e048..97d0bba1ea2e1 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -2286,6 +2286,7 @@ Preprocessor::ImportAction 
Preprocessor::HandleHeaderIncludeOrImport(
   // actual module containing it exists (because the umbrella header is
   // incomplete).  Treat this as a textual inclusion.
   SuggestedModule = ModuleMap::KnownHeader();
+  SM = nullptr;
 } else if (Imported.isConfigMismatch()) {
   // On a configuration mismatch, enter the header textually. We still know
   // that it's part of the corresponding module.

diff  --git a/clang/test/Modules/missing-framework-header.cpp 
b/clang/test/Modules/missing-framework-header.cpp
new file mode 100644
index 0..b618451bd3214
--- /dev/null
+++ b/clang/test/Modules/missing-framework-header.cpp
@@ -0,0 +1,27 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: split-file %s %t
+
+//--- frameworks/FW.framework/Modules/module.modulemap
+framework module FW {
+   umbrella header "FW.h"
+   module * { export * }
+}
+
+//--- frameworks/FW.framework/Headers/FW.h
+#include "One.h"
+//--- frameworks/FW.framework/Headers/One.h
+//--- frameworks/FW.framework/Headers/Two.h
+
+//--- module.modulemap
+module Mod { header "Mod.h" }
+//--- Mod.h
+#include "FW/Two.h"
+//--- from_module.m
+#include "Mod.h"
+
+// RUN: %clang -fmodules -fmodules-cache-path=%t/cache \
+// RUN: -iframework %t/frameworks -c %t/from_module.m -o %t/from_module.o \
+// RUN:  2>&1 | FileCheck %s
+
+// CHECK: warning: missing submodule 'FW.Two'
+



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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

2022-08-19 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 453917.
tbaeder added a comment.

When changing the test to use `-verify=test`, I noticed that 
`static_assert(-false)` did not assert.

I had to implement integral casts (only from sint32 to bool for now) in this 
patch as well to make it work.


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

https://reviews.llvm.org/D132098

Files:
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -1,15 +1,33 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++11 -verify %s
+// RUN: %clang_cc1 -std=c++11 -verify=ref %s
 
 static_assert(true, "");
-static_assert(false, ""); // expected-error{{failed}}
+static_assert(false, ""); // expected-error{{failed}} ref-error{{failed}}
 static_assert(nullptr == nullptr, "");
 static_assert(1 == 1, "");
-static_assert(1 == 3, ""); // expected-error{{failed}}
+static_assert(1 == 3, ""); // expected-error{{failed}} ref-error{{failed}}
 
 constexpr int number = 10;
 static_assert(number == 10, "");
-static_assert(number != 10, ""); // expected-error{{failed}}
+static_assert(number != 10, ""); // expected-error{{failed}} \
+ // ref-error{{failed}} \
+ // ref-note{{evaluates to}}
 
 constexpr bool getTrue() { return true; }
 constexpr bool getFalse() { return false; }
 constexpr void* getNull() { return nullptr; }
+
+constexpr int neg(int m) { return -m; }
+constexpr bool inv(bool b) { return !b; }
+
+static_assert(12, "");
+static_assert(12 == -(-(12)), "");
+static_assert(!false, "");
+static_assert(!!true, "");
+static_assert(!!true == !false, "");
+static_assert(true == 1, "");
+static_assert(false == 0, "");
+static_assert(!5 == false, "");
+static_assert(!0, "");
+static_assert(-true, "");
+static_assert(-false, ""); //expected-error{{failed}} ref-error{{failed}}
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -73,6 +73,10 @@
   let Types = [Ptr];
 }
 
+def BoolTypeClass : TypeClass {
+  let Types = [Bool];
+}
+
 def AllTypeClass : TypeClass {
   let Types = !listconcat(AluTypeClass.Types, PtrTypeClass.Types);
 }
@@ -383,6 +387,37 @@
 def Add : AluOpcode;
 def Mul : AluOpcode;
 
+
+//===--===//
+// Unary operators.
+//===--===//
+
+// [Real] -> [Real]
+def Inv: Opcode {
+  let Types = [BoolTypeClass];
+  let HasGroup = 1;
+}
+
+// [Real] -> [Real]
+def Neg: Opcode {
+  let Types = [AluTypeClass];
+  let HasGroup = 1;
+}
+
+//===--===//
+// Cast.
+//===--===//
+// TODO: Expand this to handle casts between more types.
+
+def Sint32TypeClass : TypeClass {
+  let Types = [Sint32];
+}
+
+def Cast: Opcode {
+  let Types = [BoolTypeClass, Sint32TypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Comparison opcodes.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -154,6 +154,36 @@
   return AddSubMulHelper(S, OpPC, Bits, LHS, RHS);
 }
 
+//===--===//
+// Inv
+//===--===//
+
+template ::T>
+bool Inv(InterpState &S, CodePtr OpPC) {
+  using BoolT = PrimConv::T;
+  const T &Val = S.Stk.pop();
+  const unsigned Bits = Val.bitWidth();
+  Boolean R;
+  Boolean::inv(BoolT::from(Val, Bits), &R);
+
+  S.Stk.push(R);
+  return true;
+}
+
+//===--===//
+// Neg
+//===--===//
+
+template ::T>
+bool Neg(InterpState &S, CodePtr OpPC) {
+  const T &Val = S.Stk.pop();
+  T Result;
+  T::neg(Val, &Result);
+
+  S.Stk.push(Result);
+  return true;
+}
+
 //===--===//
 // EQ, NE, GT, GE, LT, LE
 //===--===//
Index: clang/lib/AST/Interp/Integral.h

[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

I'm a bit out of my element with the template magic here.


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

https://reviews.llvm.org/D132098

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


[clang-tools-extra] 3fd4213 - [clang-tidy] Do not trigger cppcoreguidelines-avoid-const-or-ref-data-members on lambda captures

2022-08-19 Thread Carlos Galvez via cfe-commits

Author: Carlos Galvez
Date: 2022-08-19T08:26:34Z
New Revision: 3fd4213059a4ea9453809aeccd1bfc7d115d24b2

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

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

Lambdas are implemented as regular classes internally,
and the captured variables end up as members there.
Do not diagnose those - the check should cover only
regular classes and structs.

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp

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

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
index 5f340736c8dde..aa530ff9e098c 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/AvoidConstOrRefDataMembersCheck.cpp
@@ -15,12 +15,23 @@ using namespace clang::ast_matchers;
 namespace clang {
 namespace tidy {
 namespace cppcoreguidelines {
+namespace {
+
+AST_MATCHER(FieldDecl, isMemberOfLambda) {
+  return Node.getParent()->isLambda();
+}
+
+} // namespace
 
 void AvoidConstOrRefDataMembersCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(
-  fieldDecl(hasType(hasCanonicalType(referenceType(.bind("ref"), this);
-  Finder->addMatcher(
-  fieldDecl(hasType(qualType(isConstQualified(.bind("const"), this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(hasCanonicalType(referenceType(
+ .bind("ref"),
+ this);
+  Finder->addMatcher(fieldDecl(unless(isMemberOfLambda()),
+   hasType(qualType(isConstQualified(
+ .bind("const"),
+ this);
 }
 
 void AvoidConstOrRefDataMembersCheck::check(

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
index 01aed9dfdc1e2..becc3ee8ba9d8 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/avoid-const-or-ref-data-members.cpp
@@ -167,3 +167,41 @@ TemplatedConst t2{123};
 TemplatedConstRef t3{123};
 TemplatedRefRef t4{123};
 TemplatedRef t5{t1.t};
+
+// Lambdas capturing const or ref members should not trigger warnings
+void lambdas()
+{
+  int x1{123};
+  const int x2{123};
+  const int& x3{123};
+  int&& x4{123};
+  int& x5{x1};
+
+  auto v1 = [x1]{};
+  auto v2 = [x2]{};
+  auto v3 = [x3]{};
+  auto v4 = [x4]{};
+  auto v5 = [x5]{};
+
+  auto r1 = [&x1]{};
+  auto r2 = [&x2]{};
+  auto r3 = [&x3]{};
+  auto r4 = [&x4]{};
+  auto r5 = [&x5]{};
+
+  auto iv = [=]{
+auto c1 = x1;
+auto c2 = x2;
+auto c3 = x3;
+auto c4 = x4;
+auto c5 = x5;
+  };
+
+  auto ir = [&]{
+auto c1 = x1;
+auto c2 = x2;
+auto c3 = x3;
+auto c4 = x4;
+auto c5 = x5;
+  };
+}



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


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

2022-08-19 Thread Carlos Galvez via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3fd4213059a4: [clang-tidy] Do not trigger 
cppcoreguidelines-avoid-const-or-ref-data-members… (authored by carlosgalvezp).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

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


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


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

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

2022-08-19 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

Thanks for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131780

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

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



Comment at: clang/test/Analysis/trivial-copy-struct.cpp:26
+
+  clang_analyzer_dump(n1); // expected-warning {{&SymRegion{reg_$2}}}
+  clang_analyzer_dump(n2); // expected-warning {{&HeapSymRegion{conj_$1{Node 
*, LC1, S1855, #1

and in the rest of the cases


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

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


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

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

In D128981#3728503 , @iains wrote:

> In D128981#3728070 , @jansvoboda11 
> wrote:
>
>> Hi @iains, upstream Clang crashes on the attached test case due to an 
>> assertion failure. Git bisect pointed me to this commit. Can you please take 
>> a look? Previously, the test would result in a warning of incomplete 
>> umbrella header.
>
> yes, I can repeat this - will take a look.

I landed 
https://github.com/llvm/llvm-project/commit/a2dd6130d49777d63c2d1b641bd8e56f26fa0822
 to fix this (assuming that there is no new fallout) - do you think we should 
back port to llvm-15?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128981

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


[PATCH] D128113: Clang: fix AST representation of expanded template arguments.

2022-08-19 Thread David Rector via Phabricator via cfe-commits
davrec added a comment.

In D128113#3733764 , @mizvekov wrote:

> In D128113#3733051 , @joanahalili 
> wrote:
>
>> We have a translation unit, on which we see an increase of compilation time 
>> and clang memory allocation from 11GB to 14GB. We are working on an isolated 
>> case.
>
> Thanks for looking into this!
>
> What I can imagine may be happening here is that if we instantiate a template 
> with a very large argument pack consisting of mostly the same template 
> arguments, we will create many more `SubstTemplateTypeParmType` nodes with 
> this patch, as they won't unique so much anymore, because each will have a 
> different pack index.

If this is indeed a major problem, and/or if performance is an issue for other 
of the patches in the stack, maybe the solution is along the lines of what I 
raised in 
https://discourse.llvm.org/t/rfc-improving-diagnostics-with-template-specialization-resugaring/64294/5:
 introduce an option that determines how much sugar we construct in the AST, 
and modify `ASTContext::get*Type(...)` accordingly.

For now it could have two possible values, 'medium' and 'maximum', and 
`getSubstTemplateTypeParmType(...)` could be modified so it always uses 
PackIndex=0 whenever it is only set to 'medium'.  And, for later patches, 
resugaring would only be enabled when it is set to 'maximum'.  (And maybe later 
a 'minimum' option could be experimented with which disables all sugar except 
that needed to keep tests passing.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128113

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-19 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I agree with @steakhal. Getting rid of element regions might be a lot of work 
and might have a lot of fallout that we need to deal with. I think we should 
not block a fix for something that we might not be able to land for a long 
time.  Fixing this here, and independently start working on the long-term 
solutions sounds reasonable to me. At least once we switch over, we will have 
test coverage for all of the cases that used to be problematic :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

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


[PATCH] D131808: [clang,flang] Add help text for -fsyntax-only

2022-08-19 Thread Alexander Malkov via Phabricator via cfe-commits
alexiprof added a comment.

ping
@awarzynski @MaskRay @vzakhari


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131808

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


[PATCH] D131808: [clang,flang] Add help text for -fsyntax-only

2022-08-19 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added a comment.

I can land this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131808

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


[PATCH] D131808: [clang,flang] Add help text for -fsyntax-only

2022-08-19 Thread Kiran Chandramohan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcd86a03246a2: [clang,flang] Add help text for -fsyntax-only 
(authored by alexiprof, committed by kiranchandramohan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131808

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/docs/CommandGuide/clang.rst
  clang/docs/UsersManual.rst
  clang/include/clang/Driver/Options.td
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.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: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
+! HELP-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-NEXT: -help  Display available options
 ! HELP-NEXT: -IAdd directory to the end of the list of include search paths
@@ -119,6 +120,7 @@
 ! HELP-FC1-NEXT: -fno-reformat  Dump the cooked character stream in -E mode
 ! HELP-FC1-NEXT: -fopenacc  Enable OpenACC
 ! HELP-FC1-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
+! HELP-FC1-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! HELP-FC1-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! HELP-FC1-NEXT: -help  Display available options
 ! HELP-FC1-NEXT: -init-only Only execute frontend initialization
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -44,6 +44,7 @@
 ! CHECK-NEXT: -fno-integrated-as Disable the integrated assembler
 ! CHECK-NEXT: -fopenacc  Enable OpenACC
 ! CHECK-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
+! CHECK-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! CHECK-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
 ! CHECK-NEXT: -help Display available options
 ! CHECK-NEXT: -IAdd directory to the end of the list of include search paths
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2800,7 +2800,8 @@
 def fdriver_only : Flag<["-"], "fdriver-only">, Flags<[NoXarchOption, CoreOption]>,
   Group, HelpText<"Only run the driver.">;
 def fsyntax_only : Flag<["-"], "fsyntax-only">,
-  Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option]>, Group;
+  Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option,FlangOption]>, Group,
+  HelpText<"Run the preprocessor, parser and semantic analysis stages">;
 def ftabstop_EQ : Joined<["-"], "ftabstop=">, Group;
 def ftemplate_depth_EQ : Joined<["-"], "ftemplate-depth=">, Group;
 def ftemplate_depth_ : Joined<["-"], "ftemplate-depth-">, Group;
@@ -6618,7 +6619,7 @@
 def _SLASH_Zp_flag : CLFlag<"Zp">,
   HelpText<"Set default maximum struct packing alignment to 1">,
   Alias, AliasArgs<["1"]>;
-def _SLASH_Zs : CLFlag<"Zs">, HelpText<"Syntax-check only">,
+def _SLASH_Zs : CLFlag<"Zs">, HelpText<"Run the preprocessor, parser and semantic analysis stages">,
   Alias;
 def _SLASH_openmp_ : CLFlag<"openmp-">,
   HelpText<"Disable OpenMP support">, Alias;
Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -3999,7 +3999,7 @@
   /Zl Don't mention any default libraries in the object file
   /Zp Set the default maximum struct packing alignment to 1
   /Zp  Specify the default maximum struct packing alignment
-  /Zs Syntax-check only
+  /Zs Run the preprocessor, parser and semantic analysis stages
 
 OPTIONS:
   -###Print (but do not run) the commands to run for this compilation
@@ -4130,6 +4130,7 @@
   behavior. See user manual for available checks
   -fsplit-lto-unitEnables splitting of the LTO unit.
   -fstandalone-debug  Emit full debug info for all types used by the program
+  -fsyntax-only   Run the preprocessor, parser and semantic analysis stages
   -fwhole-program-vtables Enables whole-program vtable optimization. Requires -flto
   -gcodeview-ghash

[clang] cd86a03 - [clang,flang] Add help text for -fsyntax-only

2022-08-19 Thread Kiran Chandramohan via cfe-commits

Author: Alexander Malkov
Date: 2022-08-19T09:54:29Z
New Revision: cd86a03246a2df350c2f694457f1ce946cf65663

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

LOG: [clang,flang] Add help text for -fsyntax-only

Fix for the problem with displaying options `-fsyntax-only` in clang and 
flang-new in help
Fix https://github.com/llvm/llvm-project/issues/57033

Before:
``` $ clang  -help | grep syntax
  -objcmt-migrate-property-dot-syntax
 Enable migration of setter/getter messages to property-dot syntax
```
After:
```
 $ clang -help | grep syntax
  -fsyntax-only   Run the preprocessor, parser and semantic analysis 
stages
  -objcmt-migrate-property-dot-syntax
 Enable migration of setter/getter messages to property-dot syntax
```

Reviewed By: vzakhari, awarzynski, MaskRay, alexiprof

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

Added: 


Modified: 
clang/docs/ClangCommandLineReference.rst
clang/docs/CommandGuide/clang.rst
clang/docs/UsersManual.rst
clang/include/clang/Driver/Options.td
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90

Removed: 




diff  --git a/clang/docs/ClangCommandLineReference.rst 
b/clang/docs/ClangCommandLineReference.rst
index 265a6d7beb6e9..7f9ef3783f9da 100644
--- a/clang/docs/ClangCommandLineReference.rst
+++ b/clang/docs/ClangCommandLineReference.rst
@@ -831,6 +831,8 @@ Only run the driver.
 
 .. option:: -fsyntax-only
 
+Run the preprocessor, parser and semantic analysis stages
+
 .. option:: -module-file-info
 
 Provide information about a particular module file

diff  --git a/clang/docs/CommandGuide/clang.rst 
b/clang/docs/CommandGuide/clang.rst
index af2b0df98d3dc..5e344ec702777 100644
--- a/clang/docs/CommandGuide/clang.rst
+++ b/clang/docs/CommandGuide/clang.rst
@@ -75,7 +75,7 @@ Stage Selection Options
 
 .. option:: -fsyntax-only
 
- Run the preprocessor, parser and type checking stages.
+ Run the preprocessor, parser and semantic analysis stages.
 
 .. option:: -S
 

diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f9ccca65f3889..78ccf4572ffc8 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3999,7 +3999,7 @@ Execute ``clang-cl /?`` to see a list of supported 
options:
   /Zl Don't mention any default libraries in the 
object file
   /Zp Set the default maximum struct packing alignment 
to 1
   /Zp  Specify the default maximum struct packing 
alignment
-  /Zs Syntax-check only
+  /Zs Run the preprocessor, parser and semantic 
analysis stages
 
 OPTIONS:
   -###Print (but do not run) the commands to run for 
this compilation
@@ -4130,6 +4130,7 @@ Execute ``clang-cl /?`` to see a list of supported 
options:
   behavior. See user manual for available checks
   -fsplit-lto-unitEnables splitting of the LTO unit.
   -fstandalone-debug  Emit full debug info for all types used by the 
program
+  -fsyntax-only   Run the preprocessor, parser and semantic 
analysis stages
   -fwhole-program-vtables Enables whole-program vtable optimization. 
Requires -flto
   -gcodeview-ghashEmit type record hashes in a .debug$H section
   -gcodeview  Generate CodeView debug information

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index a5dfeec4fd463..c8178c13e82e9 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2800,7 +2800,8 @@ def fstrict_overflow : Flag<["-"], "fstrict-overflow">, 
Group;
 def fdriver_only : Flag<["-"], "fdriver-only">, Flags<[NoXarchOption, 
CoreOption]>,
   Group, HelpText<"Only run the driver.">;
 def fsyntax_only : Flag<["-"], "fsyntax-only">,
-  Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option]>, Group;
+  Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option,FlangOption]>, 
Group,
+  HelpText<"Run the preprocessor, parser and semantic analysis stages">;
 def ftabstop_EQ : Joined<["-"], "ftabstop=">, Group;
 def ftemplate_depth_EQ : Joined<["-"], "ftemplate-depth=">, Group;
 def ftemplate_depth_ : Joined<["-"], "ftemplate-depth-">, Group;
@@ -6618,7 +6619,7 @@ def _SLASH_Zp : CLJoined<"Zp">,
 def _SLASH_Zp_flag : CLFlag<"Zp">,
   HelpText<"Set default maximum struct packing alignment to 1">,
   Alias, AliasArgs<["1"]>;
-def _SLASH_Zs : CLFlag<"Zs">, HelpText<"Syntax-check only">,
+def _SLASH_Zs : CLFlag<"Zs">, HelpText<"Run the preprocessor, parser and 
semantic analysis stages">,
   Alias;
 def _SLASH_openmp_ : CLFlag<"openmp-">,
   HelpText<"Disable OpenMP support">, Alias;

diff  --git

[PATCH] D131808: [clang,flang] Add help text for -fsyntax-only

2022-08-19 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added a comment.

In D131808#3722809 , @alexiprof wrote:

> Could someone land this patch please?
> Alexander Malkov 

Was landed with the email id contained in the patch (Author: Alexander Malkov 
). Hope that is OK. May be you can update to the 
gmail id if that is what you prefer in your phabricator account.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131808

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


[PATCH] D132209: [Clang][OpenMP] Make copyin clause on combined and composite construct work

2022-08-19 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Add clang unit tests, please


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132209

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


[PATCH] D132110: [IncludeCleaner] Handle more C++ constructs

2022-08-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/include-cleaner/lib/WalkAST.cpp:66
+  bool VisitOverloadExpr(OverloadExpr *E) {
+// Mark all candidates as used when overload is not resolved.
+llvm::for_each(E->decls(),

kadircet wrote:
> sammccall wrote:
> > sammccall wrote:
> > > I think we need a policy knob for this, to decide whether to over or 
> > > underestimate.
> > > This would be the wrong behavior for missing-includes analysis.
> > comment echoes the code, say why instead
> i agree that this needs a knob. it's just unclear at which level currently, i 
> am putting together a doc to have a better decision here (mostly to post vs 
> pre filter).
> 
> i'd rather move forward with this version, to prepare grounds for the tidy 
> check and clangd usage based on this library, and address these issues in a 
> new iteration.
OK, add a FIXME?



Comment at: clang-tools-extra/include-cleaner/lib/WalkAST.cpp:72
+
+  bool VisitUsingDecl(UsingDecl *UD) {
+for (const auto *Shadow : UD->shadows())

kadircet wrote:
> sammccall wrote:
> > I wonder if this is correct enough.
> > 
> > This brings a set of overloads into scope, the intention may be to bring a 
> > particular overload with others as harmless side effects: consider `using 
> > std::swap`.
> > In this case, inserting includes for all the overloads that happened to be 
> > visible would be too much.
> > 
> > Possible behaviors:
> >  - what we do here
> >  - only do this if overestimate=true
> >  - if overestimate=false, only include those USDs marked as `referenced` 
> > (not sure if they actually get marked appropriately, the bit exists)
> i agree, basically the same things as I mentioned above, we should definitely 
> have a way to filter these.
ack, again let's mark this as incomplete somehow (esp because this one is 
subtle)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132110

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


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

2022-08-19 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen accepted this revision.
sdesmalen added a comment.
This revision is now accepted and ready to land.

LGTM, thanks @CarolineConcatto. Please land D132137 
 before landing this one to avoid regressions 
on combines that previously worked on svget/svset.




Comment at: clang/lib/CodeGen/CGBuiltin.cpp:9382
 SVETypeFlags TF(Builtin->TypeModifier);
 auto VTy = cast(getSVEType(TF));
+Value *V0 = Builder.CreateExtractVector(VTy, Ops[0],

nit: If you cast this to `ScalableVectorType`, you can use 
`VTy->getMinNumElements()` below on line 9385


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131547

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


[clang] 1bd2b2d - Add support for specifying the severity of a SARIF Result

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

Author: Vaibhav Yenamandra
Date: 2022-08-19T07:14:50-04:00
New Revision: 1bd2b2dce2a92dd2777f4fe08098b8f19e3fb593

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

LOG: Add support for specifying the severity of a SARIF Result

* Extend SarifResult with level property, and allow rule configuration
* Create SarifReportingConfiguration which allow configuring rules with
a default priority, severity and an enable-toggle
* Support for setting the level property[1] of a result.

If unset, it defaults to "warning", which is the result of an empty
default configuration on rules[2]

[1]: 
https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/sarif-v2.1.0-os.html#_Toc34317648
[2]: 
https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/sarif-v2.1.0-os.html#_Toc34317855

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

Added: 


Modified: 
clang/include/clang/Basic/Sarif.h
clang/lib/Basic/Sarif.cpp
clang/unittests/Basic/SarifTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Sarif.h 
b/clang/include/clang/Basic/Sarif.h
index 818d78668ff15..3d169e1122b12 100644
--- a/clang/include/clang/Basic/Sarif.h
+++ b/clang/include/clang/Basic/Sarif.h
@@ -145,6 +145,25 @@ class SarifArtifact {
 
 enum class ThreadFlowImportance { Important, Essential, Unimportant };
 
+/// The level of severity associated with a \ref SarifResult.
+///
+/// Of all the levels, \c None is the only one that is not associated with
+/// a failure.
+///
+/// A typical mapping for clang's DiagnosticKind to SarifResultLevel would look
+/// like:
+/// * \c None: \ref clang::DiagnosticsEngine::Level::Remark, \ref 
clang::DiagnosticsEngine::Level::Ignored
+/// * \c Note: \ref clang::DiagnosticsEngine::Level::Note
+/// * \c Warning: \ref clang::DiagnosticsEngine::Level::Warning
+/// * \c Error could be generated from one of:
+///   - \ref clang::DiagnosticsEngine::Level::Warning with \c -Werror
+///   - \ref clang::DiagnosticsEngine::Level::Error
+///   - \ref clang::DiagnosticsEngine::Level::Fatal when \ref 
clang::DiagnosticsEngine::ErrorsAsFatal is set.
+///
+/// Reference:
+/// 1. https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/sarif-v2.1.0-os.html#_Toc34317648";>level
 property
+enum class SarifResultLevel { None, Note, Warning, Error };
+
 /// A thread flow is a sequence of code locations that specify a possible path
 /// through a single thread of execution.
 /// A thread flow in SARIF is related to a code flow which describes
@@ -183,6 +202,47 @@ class ThreadFlow {
   }
 };
 
+/// A SARIF Reporting Configuration (\c reportingConfiguration) object contains
+/// properties for a \ref SarifRule that can be configured at runtime before
+/// analysis begins.
+///
+/// Reference:
+/// 1. https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/sarif-v2.1.0-os.html#_Toc34317852";>reportingConfiguration
 object
+class SarifReportingConfiguration {
+  friend class clang::SarifDocumentWriter;
+
+  bool Enabled = true;
+  SarifResultLevel Level = SarifResultLevel::Warning;
+  float Rank = -1.0f;
+
+  SarifReportingConfiguration() = default;
+
+public:
+  static SarifReportingConfiguration create() { return {}; };
+
+  SarifReportingConfiguration disable() {
+Enabled = false;
+return *this;
+  }
+
+  SarifReportingConfiguration enable() {
+Enabled = true;
+return *this;
+  }
+
+  SarifReportingConfiguration setLevel(SarifResultLevel TheLevel) {
+Level = TheLevel;
+return *this;
+  }
+
+  SarifReportingConfiguration setRank(float TheRank) {
+assert(TheRank >= 0.0f && "Rule rank cannot be smaller than 0.0");
+assert(TheRank <= 100.0f && "Rule rank cannot be larger than 100.0");
+Rank = TheRank;
+return *this;
+  }
+};
+
 /// A SARIF rule (\c reportingDescriptor object) contains information that
 /// describes a reporting item generated by a tool. A reporting item is
 /// either a result of analysis or notification of a condition encountered by
@@ -201,8 +261,9 @@ class SarifRule {
   std::string Id;
   std::string Description;
   std::string HelpURI;
+  SarifReportingConfiguration DefaultConfiguration;
 
-  SarifRule() = default;
+  SarifRule() : DefaultConfiguration(SarifReportingConfiguration::create()) {}
 
 public:
   static SarifRule create() { return {}; }
@@ -226,6 +287,12 @@ class SarifRule {
 HelpURI = RuleHelpURI.str();
 return *this;
   }
+
+  SarifRule
+  setDefaultConfiguration(const SarifReportingConfiguration &Configuration) {
+DefaultConfiguration = Configuration;
+return *this;
+  }
 };
 
 /// A SARIF result (also called a "reporting item") is a unit of output
@@ -257,6 +324,7 @@ class SarifResult {
   std::string DiagnosticMessage;
   llvm::SmallVector Locations;
   llvm::SmallVector ThreadFlows;
+  llvm::Optional LevelOverride;
 
   SarifResult() 

[PATCH] D131084: Add support for specifying the severity of a SARIF Result.

2022-08-19 Thread Aaron Ballman 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 rG1bd2b2dce2a9: Add support for specifying the severity of a 
SARIF Result (authored by vaibhav.y, committed by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131084

Files:
  clang/include/clang/Basic/Sarif.h
  clang/lib/Basic/Sarif.cpp
  clang/unittests/Basic/SarifTest.cpp

Index: clang/unittests/Basic/SarifTest.cpp
===
--- clang/unittests/Basic/SarifTest.cpp
+++ clang/unittests/Basic/SarifTest.cpp
@@ -7,7 +7,6 @@
 //===--===//
 
 #include "clang/Basic/Sarif.h"
-#include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
@@ -33,9 +32,9 @@
 
 static std::string serializeSarifDocument(llvm::json::Object &&Doc) {
   std::string Output;
-  llvm::json::Value value(std::move(Doc));
+  llvm::json::Value Value(std::move(Doc));
   llvm::raw_string_ostream OS{Output};
-  OS << llvm::formatv("{0}", value);
+  OS << llvm::formatv("{0}", Value);
   OS.flush();
   return Output;
 }
@@ -86,7 +85,7 @@
   const llvm::json::Object &EmptyDoc = Writer.createDocument();
   std::vector Keys(EmptyDoc.size());
   std::transform(EmptyDoc.begin(), EmptyDoc.end(), Keys.begin(),
- [](auto item) { return item.getFirst(); });
+ [](auto Item) { return Item.getFirst(); });
 
   // THEN:
   ASSERT_THAT(Keys, testing::UnorderedElementsAre("$schema", "version"));
@@ -113,17 +112,17 @@
   ASSERT_EQ(Runs->size(), 1UL);
 
   // The tool associated with the run was the tool
-  const llvm::json::Object *driver =
+  const llvm::json::Object *Driver =
   Runs->begin()->getAsObject()->getObject("tool")->getObject("driver");
-  ASSERT_THAT(driver, testing::NotNull());
+  ASSERT_THAT(Driver, testing::NotNull());
 
-  ASSERT_TRUE(driver->getString("name").has_value());
-  ASSERT_TRUE(driver->getString("fullName").has_value());
-  ASSERT_TRUE(driver->getString("language").has_value());
+  ASSERT_TRUE(Driver->getString("name").has_value());
+  ASSERT_TRUE(Driver->getString("fullName").has_value());
+  ASSERT_TRUE(Driver->getString("language").has_value());
 
-  EXPECT_EQ(driver->getString("name").value(), ShortName);
-  EXPECT_EQ(driver->getString("fullName").value(), LongName);
-  EXPECT_EQ(driver->getString("language").value(), "en-US");
+  EXPECT_EQ(Driver->getString("name").value(), ShortName);
+  EXPECT_EQ(Driver->getString("fullName").value(), LongName);
+  EXPECT_EQ(Driver->getString("language").value(), "en-US");
 }
 
 TEST_F(SarifDocumentWriterTest, addingResultsWillCrashIfThereIsNoRun) {
@@ -147,6 +146,47 @@
   ASSERT_DEATH(Writer.appendResult(EmptyResult), Matcher);
 }
 
+TEST_F(SarifDocumentWriterTest, settingInvalidRankWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A SarifReportingConfiguration is created with an invalid "rank"
+  // * Ranks below 0.0 are invalid
+  // * Ranks above 100.0 are invalid
+
+  // THEN: The builder will crash in either case
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(-1.0),
+   ::testing::HasSubstr("Rule rank cannot be smaller than 0.0"));
+  EXPECT_DEATH(SarifReportingConfiguration::create().setRank(101.0),
+   ::testing::HasSubstr("Rule rank cannot be larger than 100.0"));
+}
+
+TEST_F(SarifDocumentWriterTest, creatingResultWithDisabledRuleWillCrash) {
+#if defined(NDEBUG) || !GTEST_HAS_DEATH_TEST
+  GTEST_SKIP() << "This death test is only available for debug builds.";
+#endif
+
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  // A disabled Rule is created, and a result is create referencing this rule
+  const auto &Config = SarifReportingConfiguration::create().disable();
+  auto RuleIdx =
+  Writer.createRule(SarifRule::create().setDefaultConfiguration(Config));
+  const SarifResult &Result = SarifResult::create(RuleIdx);
+
+  // THEN:
+  // SarifResult::create(...) will produce a crash
+  ASSERT_DEATH(
+  Writer.appendResult(Result),
+  ::testing::HasSubstr("Cannot add a result referencing a disabled Rule"));
+}
+
 // Test adding rule and result shows up in the final document
 TEST_F(SarifDocumentWriterTest, addingResultWithValidRuleAndRunIsOk) {
   // GIVEN:
@@ -160,9 +200,9 @@
   // WHEN:
   Writer.createRun("sarif test", "sarif test runner");
   unsigned RuleIdx = Writer.createRule(Rule);
-  const SarifResult &result = SarifResult::create(RuleIdx);
+  const SarifResult &Result = SarifResult::create(RuleIdx);
 
-  Writer.appendResult(result);
+  Writ

[PATCH] D131175: [clangd] Use the "macro" semantic token for pre-defined identifiers

2022-08-19 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D131175#3732379 , @sammccall wrote:

> But often I forget and edit it in phab, and I don't know of a command to pull 
> those edits down into my git repo.

I ended up always doing this for landing changes:

  $ git switch main
  $ git pull --ff-only
  $ arc patch --nobranch D123456
  $ git push origin main

That way I get the latest description from phabricator and also the reviewed-by 
tags.
And I basically ignore what the commit messages says on my branch while it's 
WIP, phab is source of truth after the initial change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131175

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


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

2022-08-19 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

When this relands and it's not too much trouble, it'd be nice if you could 
reland d3a1dbc4907b59690f9013cdb6221573ca4233f1 
 in the 
commit that relands this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130586

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


[PATCH] D131388: [docs] Add "C++20 Modules"

2022-08-19 Thread Johel Ernesto Guerrero Peña via Phabricator via cfe-commits
JohelEGP requested changes to this revision.
JohelEGP added inline comments.
This revision now requires changes to proceed.



Comment at: clang/docs/CPlusPlus20Modules.rst:290
+``primary module interface unit`` by ``-fmodule-file``
+since the langugae specification says a module implementation unit implicitly 
imports
+the primary module interface unit.





Comment at: clang/docs/CPlusPlus20Modules.rst:457
+
+The declarations in a module unit which are not in global module fragment have 
new linkage names.
+




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

https://reviews.llvm.org/D131388

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


[PATCH] D131665: [CMake] Support passing arguments to build tool (bootstrap).

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

To give more scope to the reviewers, the following CMake options illustrate the 
benefit of this patch.

For example, if I want to do a dry run on stage-2, I will pass 
`-DLLVM_EXTERNAL_PROJECT_BUILD_TOOL_ARGS="-n --verbose"`

  -DCLANG_ENABLE_BOOTSTRAP=ON -DLLVM_ENABLE_PROJECTS=clang 
-DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD=X86 -G"Ninja" 
-DLLVM_EXTERNAL_PROJECT_BUILD_TOOL_ARGS="-n --verbose"

When `ninja` builds `stage-2` it receives the additional `-n` and `--verbose` 
options.

The `build_tool_args` passed to `BUILD_COMMAND` looks like:

  '--;-n;--verbose'


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131665

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:620
+  case UO_Deref:  // *x
+  case UO_Not:// ~x
+  case UO_Real:   // __real x

tbaeder wrote:
> aaron.ballman wrote:
> > This is reachable and will always return true thanks to the magic of 
> > integer promotions:
> > ```
> > void func() {
> >   bool b = true;
> >   b = ~b;
> > }
> > ```
> This code path is not just for boolean values though.
All the more reason to be worried about `~` being marked as unreachable (I 
mostly worry because people often try to make bit fiddling operations constant 
expressions when possible, so this seems pretty likely to be hit). Perhaps make 
it into an `assert(false && "operation not supported yet");` or something more 
loud?



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:129-130
+return this->emitCast(*FromT, *ToT, CE);
+  }
+return false;
+





Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

tbaeder wrote:
> I'm a bit out of my element with the template magic here.
It mostly looks correct to me, but the part I'm struggling with is 
`static_cast`; can you explain what you're trying to do there?


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:620
+  case UO_Deref:  // *x
+  case UO_Not:// ~x
+  case UO_Real:   // __real x

aaron.ballman wrote:
> tbaeder wrote:
> > aaron.ballman wrote:
> > > This is reachable and will always return true thanks to the magic of 
> > > integer promotions:
> > > ```
> > > void func() {
> > >   bool b = true;
> > >   b = ~b;
> > > }
> > > ```
> > This code path is not just for boolean values though.
> All the more reason to be worried about `~` being marked as unreachable (I 
> mostly worry because people often try to make bit fiddling operations 
> constant expressions when possible, so this seems pretty likely to be hit). 
> Perhaps make it into an `assert(false && "operation not supported yet");` or 
> something more loud?
How is that different? It's just a marker for me so I know later in development 
that this is not implemented yet. And now that I'm writing this, I guess I see 
what you mean. Yes, it's not unreachable, but it shouldn't be reached when 
testing what is currently implemented.



Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

aaron.ballman wrote:
> tbaeder wrote:
> > I'm a bit out of my element with the template magic here.
> It mostly looks correct to me, but the part I'm struggling with is 
> `static_cast`; can you explain what you're trying to do there?
I was trying to implement creating an Integral from a Boolean; the 
`static_cast` casts to `Integral::T` (which in my case is `int`). It might not 
be needed.


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:620
+  case UO_Deref:  // *x
+  case UO_Not:// ~x
+  case UO_Real:   // __real x

tbaeder wrote:
> aaron.ballman wrote:
> > tbaeder wrote:
> > > aaron.ballman wrote:
> > > > This is reachable and will always return true thanks to the magic of 
> > > > integer promotions:
> > > > ```
> > > > void func() {
> > > >   bool b = true;
> > > >   b = ~b;
> > > > }
> > > > ```
> > > This code path is not just for boolean values though.
> > All the more reason to be worried about `~` being marked as unreachable (I 
> > mostly worry because people often try to make bit fiddling operations 
> > constant expressions when possible, so this seems pretty likely to be hit). 
> > Perhaps make it into an `assert(false && "operation not supported yet");` 
> > or something more loud?
> How is that different? It's just a marker for me so I know later in 
> development that this is not implemented yet. And now that I'm writing this, 
> I guess I see what you mean. Yes, it's not unreachable, but it shouldn't be 
> reached when testing what is currently implemented.
Aaron: we tend to NEVER use 'assert(false...' and instead use llvm_unreachable 
for 'not implemented yet' quite often in clang. I don't see the semantic 
difference here?


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:620
+  case UO_Deref:  // *x
+  case UO_Not:// ~x
+  case UO_Real:   // __real x

erichkeane wrote:
> tbaeder wrote:
> > aaron.ballman wrote:
> > > tbaeder wrote:
> > > > aaron.ballman wrote:
> > > > > This is reachable and will always return true thanks to the magic of 
> > > > > integer promotions:
> > > > > ```
> > > > > void func() {
> > > > >   bool b = true;
> > > > >   b = ~b;
> > > > > }
> > > > > ```
> > > > This code path is not just for boolean values though.
> > > All the more reason to be worried about `~` being marked as unreachable 
> > > (I mostly worry because people often try to make bit fiddling operations 
> > > constant expressions when possible, so this seems pretty likely to be 
> > > hit). Perhaps make it into an `assert(false && "operation not supported 
> > > yet");` or something more loud?
> > How is that different? It's just a marker for me so I know later in 
> > development that this is not implemented yet. And now that I'm writing 
> > this, I guess I see what you mean. Yes, it's not unreachable, but it 
> > shouldn't be reached when testing what is currently implemented.
> Aaron: we tend to NEVER use 'assert(false...' and instead use 
> llvm_unreachable for 'not implemented yet' quite often in clang. I don't see 
> the semantic difference here?
Aaron clarified offline: the problem is that llvm_unreachable inserts 
optimization hints in non-asserts builds, so the result is optimizer-caused-UB 
here.  The preference for 'assert(false', though it causing an odd state, at 
least doesn't allow the optimizer to go hog wild.

So I agree with Aaron here.

We DO do this wrong in some places, which is unfortunate, but should be 
considered mistakes, not precedent.


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

tbaeder wrote:
> aaron.ballman wrote:
> > tbaeder wrote:
> > > I'm a bit out of my element with the template magic here.
> > It mostly looks correct to me, but the part I'm struggling with is 
> > `static_cast`; can you explain what you're trying to do there?
> I was trying to implement creating an Integral from a Boolean; the 
> `static_cast` casts to `Integral::T` (which in my case is `int`). It might 
> not be needed.
Oh!!! I see now why there's so much confusion. You have `template ` 
and I was wondering why you were trying to use that here. I see now that 
there's `Integral::T` as a private member.

Can we please rename `Integral::T` to be something mildly descriptive? (I'm 
fine if that's done in a follow-up as an NFC change.)


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

aaron.ballman wrote:
> tbaeder wrote:
> > aaron.ballman wrote:
> > > tbaeder wrote:
> > > > I'm a bit out of my element with the template magic here.
> > > It mostly looks correct to me, but the part I'm struggling with is 
> > > `static_cast`; can you explain what you're trying to do 
> > > there?
> > I was trying to implement creating an Integral from a Boolean; the 
> > `static_cast` casts to `Integral::T` (which in my case is `int`). It might 
> > not be needed.
> Oh!!! I see now why there's so much confusion. You have `template  T>` and I was wondering why you were trying to use that here. I see now that 
> there's `Integral::T` as a private member.
> 
> Can we please rename `Integral::T` to be something mildly descriptive? (I'm 
> fine if that's done in a follow-up as an NFC change.)
As Aaron said separately, the 'T' name of the integral member is bonkers and 
confusing!

So it appears the intent here is to take a non-integral 'Value', cast it to the 
underlying representation, and then call the version of this on 159.  

From a 'style' perspective, I'd prefer this live right next to that version 
(since it is the inverse SFINAE).  In fact, I'd probably prefer you switch this 
to an 'if constexpr' instead:


``` 
template 
static Integral from (ValTy Value) {
if constexpr (std::is_integral_v) {
   return Integral(Value);
} else {
   return Integral(static_cast(Value));
}
 }
```
}
```



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

https://reviews.llvm.org/D132098

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


[clang-tools-extra] 13b2a0c - [clangd] Support hover on __func__ etc (PredefinedExpr)

2022-08-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-08-19T14:51:46+02:00
New Revision: 13b2a0c69ba69c1317308b6e5a8279160561c4b2

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

LOG: [clangd] Support hover on __func__ etc (PredefinedExpr)

Expose these as variables as that's what the standard calls them (and D131175).

To make this work, we also fix a bug in SelectionTree: PredefinedExpr has
an implicit/invisible StringLiteral, and SelectionTree should not traverse
implicit things.

Reviewed By: ckandeler

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

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index f599f067d6ee..eb44d1e915af 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -32,6 +32,7 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/Type.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
@@ -640,6 +641,29 @@ HoverInfo getHoverContents(const NamedDecl *D, const 
PrintingPolicy &PP,
   return HI;
 }
 
+/// The standard defines __func__ as a "predefined variable".
+llvm::Optional
+getPredefinedExprHoverContents(const PredefinedExpr &PE, ASTContext &Ctx,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+  HI.Name = PE.getIdentKindName();
+  HI.Kind = index::SymbolKind::Variable;
+  HI.Documentation = "Name of the current function (predefined variable)";
+  if (const StringLiteral *Name = PE.getFunctionName()) {
+HI.Value.emplace();
+llvm::raw_string_ostream OS(*HI.Value);
+Name->outputString(OS);
+HI.Type = printType(Name->getType(), Ctx, PP);
+  } else {
+// Inside templates, the approximate type `const char[]` is still useful.
+QualType StringType = Ctx.getIncompleteArrayType(
+Ctx.CharTy.withConst(), ArrayType::ArraySizeModifier::Normal,
+/*IndexTypeQuals=*/0);
+HI.Type = printType(StringType, Ctx, PP);
+  }
+  return HI;
+}
+
 /// Generate a \p Hover object given the macro \p MacroDecl.
 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
   HoverInfo HI;
@@ -764,6 +788,8 @@ llvm::Optional getHoverContents(const Expr *E, 
ParsedAST &AST,
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
+  if (const PredefinedExpr *PE = dyn_cast(E))
+return getPredefinedExprHoverContents(*PE, AST.getASTContext(), PP);
   // For expressions we currently print the type and the value, iff it is
   // evaluatable.
   if (auto Val = printExprValue(E, AST.getASTContext())) {

diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index e11b43047ec1..80763701d167 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -720,6 +720,14 @@ class SelectionVisitor : public 
RecursiveASTVisitor {
 return Base::TraverseTypeConstraint(C);
   }
 
+  // Override child traversal for certain node types.
+  using RecursiveASTVisitor::getStmtChildren;
+  // PredefinedExpr like __func__ has a StringLiteral child for its value.
+  // It's not written, so don't traverse it.
+  Stmt::child_range getStmtChildren(PredefinedExpr *) {
+return {StmtIterator{}, StmtIterator{}};
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 53e4f55c2e3a..997b761e6a69 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -139,6 +139,33 @@ TEST(Hover, Structured) {
  HI.Definition = "int bar";
  HI.Type = "int";
}},
+  // Predefined variable
+  {R"cpp(
+  void foo() {
+[[__f^unc__]];
+  }
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "__func__";
+ HI.Kind = index::SymbolKind::Variable;
+ HI.Documentation =
+ "Name of the current function (predefined variable)";
+ HI.Value = "\"foo\"";
+ HI.Type = "const char[4]";
+   }},
+  // Predefined variable (dependent)
+  {R"cpp(
+  template void foo() {
+[[__f^unc__]];
+  }
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "__func__";
+ HI.Kind = index::SymbolKin

[PATCH] D132135: [clangd] Support hover on __func__ etc (PredefinedExpr)

2022-08-19 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG13b2a0c69ba6: [clangd] Support hover on __func__ etc 
(PredefinedExpr) (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132135

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -527,6 +527,10 @@
 /*error-ok*/
 void func() [[{^]])cpp",
"CompoundStmt"},
+  {R"cpp(
+void func() { [[__^func__]]; }
+)cpp",
+   "PredefinedExpr"},
   };
 
   for (const Case &C : Cases) {
Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -139,6 +139,33 @@
  HI.Definition = "int bar";
  HI.Type = "int";
}},
+  // Predefined variable
+  {R"cpp(
+  void foo() {
+[[__f^unc__]];
+  }
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "__func__";
+ HI.Kind = index::SymbolKind::Variable;
+ HI.Documentation =
+ "Name of the current function (predefined variable)";
+ HI.Value = "\"foo\"";
+ HI.Type = "const char[4]";
+   }},
+  // Predefined variable (dependent)
+  {R"cpp(
+  template void foo() {
+[[__f^unc__]];
+  }
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "__func__";
+ HI.Kind = index::SymbolKind::Variable;
+ HI.Documentation =
+ "Name of the current function (predefined variable)";
+ HI.Type = "const char[]";
+   }},
   // Anon namespace and local scope.
   {R"cpp(
   namespace ns1 { namespace {
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -720,6 +720,14 @@
 return Base::TraverseTypeConstraint(C);
   }
 
+  // Override child traversal for certain node types.
+  using RecursiveASTVisitor::getStmtChildren;
+  // PredefinedExpr like __func__ has a StringLiteral child for its value.
+  // It's not written, so don't traverse it.
+  Stmt::child_range getStmtChildren(PredefinedExpr *) {
+return {StmtIterator{}, StmtIterator{}};
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -32,6 +32,7 @@
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/Type.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
@@ -640,6 +641,29 @@
   return HI;
 }
 
+/// The standard defines __func__ as a "predefined variable".
+llvm::Optional
+getPredefinedExprHoverContents(const PredefinedExpr &PE, ASTContext &Ctx,
+   const PrintingPolicy &PP) {
+  HoverInfo HI;
+  HI.Name = PE.getIdentKindName();
+  HI.Kind = index::SymbolKind::Variable;
+  HI.Documentation = "Name of the current function (predefined variable)";
+  if (const StringLiteral *Name = PE.getFunctionName()) {
+HI.Value.emplace();
+llvm::raw_string_ostream OS(*HI.Value);
+Name->outputString(OS);
+HI.Type = printType(Name->getType(), Ctx, PP);
+  } else {
+// Inside templates, the approximate type `const char[]` is still useful.
+QualType StringType = Ctx.getIncompleteArrayType(
+Ctx.CharTy.withConst(), ArrayType::ArraySizeModifier::Normal,
+/*IndexTypeQuals=*/0);
+HI.Type = printType(StringType, Ctx, PP);
+  }
+  return HI;
+}
+
 /// Generate a \p Hover object given the macro \p MacroDecl.
 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
   HoverInfo HI;
@@ -764,6 +788,8 @@
   // For `this` expr we currently generate hover with pointee type.
   if (const CXXThisExpr *CTE = dyn_cast(E))
 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
+  if (const PredefinedExpr *PE = dyn_cast(E))
+return getPredefinedExprHoverContents(*PE, AST.getASTContext(), PP);
   // For expressions we currently print the type and the value, iff it is
   // evaluatable.
   if (auto Val = printExprValue(E, AST.getASTContext())) {
_

[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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

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

https://reviews.llvm.org/D132098

Files:
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -1,15 +1,33 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++11 -verify %s
+// RUN: %clang_cc1 -std=c++11 -verify=ref %s
 
 static_assert(true, "");
-static_assert(false, ""); // expected-error{{failed}}
+static_assert(false, ""); // expected-error{{failed}} ref-error{{failed}}
 static_assert(nullptr == nullptr, "");
 static_assert(1 == 1, "");
-static_assert(1 == 3, ""); // expected-error{{failed}}
+static_assert(1 == 3, ""); // expected-error{{failed}} ref-error{{failed}}
 
 constexpr int number = 10;
 static_assert(number == 10, "");
-static_assert(number != 10, ""); // expected-error{{failed}}
+static_assert(number != 10, ""); // expected-error{{failed}} \
+ // ref-error{{failed}} \
+ // ref-note{{evaluates to}}
 
 constexpr bool getTrue() { return true; }
 constexpr bool getFalse() { return false; }
 constexpr void* getNull() { return nullptr; }
+
+constexpr int neg(int m) { return -m; }
+constexpr bool inv(bool b) { return !b; }
+
+static_assert(12, "");
+static_assert(12 == -(-(12)), "");
+static_assert(!false, "");
+static_assert(!!true, "");
+static_assert(!!true == !false, "");
+static_assert(true == 1, "");
+static_assert(false == 0, "");
+static_assert(!5 == false, "");
+static_assert(!0, "");
+static_assert(-true, "");
+static_assert(-false, ""); //expected-error{{failed}} ref-error{{failed}}
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -73,6 +73,10 @@
   let Types = [Ptr];
 }
 
+def BoolTypeClass : TypeClass {
+  let Types = [Bool];
+}
+
 def AllTypeClass : TypeClass {
   let Types = !listconcat(AluTypeClass.Types, PtrTypeClass.Types);
 }
@@ -383,6 +387,37 @@
 def Add : AluOpcode;
 def Mul : AluOpcode;
 
+
+//===--===//
+// Unary operators.
+//===--===//
+
+// [Real] -> [Real]
+def Inv: Opcode {
+  let Types = [BoolTypeClass];
+  let HasGroup = 1;
+}
+
+// [Real] -> [Real]
+def Neg: Opcode {
+  let Types = [AluTypeClass];
+  let HasGroup = 1;
+}
+
+//===--===//
+// Cast.
+//===--===//
+// TODO: Expand this to handle casts between more types.
+
+def Sint32TypeClass : TypeClass {
+  let Types = [Sint32];
+}
+
+def Cast: Opcode {
+  let Types = [BoolTypeClass, Sint32TypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Comparison opcodes.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -154,6 +154,36 @@
   return AddSubMulHelper(S, OpPC, Bits, LHS, RHS);
 }
 
+//===--===//
+// Inv
+//===--===//
+
+template ::T>
+bool Inv(InterpState &S, CodePtr OpPC) {
+  using BoolT = PrimConv::T;
+  const T &Val = S.Stk.pop();
+  const unsigned Bits = Val.bitWidth();
+  Boolean R;
+  Boolean::inv(BoolT::from(Val, Bits), &R);
+
+  S.Stk.push(R);
+  return true;
+}
+
+//===--===//
+// Neg
+//===--===//
+
+template ::T>
+bool Neg(InterpState &S, CodePtr OpPC) {
+  const T &Val = S.Stk.pop();
+  T Result;
+  T::neg(Val, &Result);
+
+  S.Stk.push(Result);
+  return true;
+}
+
 //===--===//
 // EQ, NE, GT, GE, LT, LE
 //===--===//
Index: clang/lib/AST/Interp/Integral.h
===
--- clang/lib/AST/Interp/Integral.h
+++ clang/lib/AST/Interp/Integral.h
@@ -155,9 +155,11 @@
 return Integral(Max);
   }
 
-  template 
-  static std::enable_if_t::value, Integral> from(T Value) {
-return Integral(Value);
+  te

[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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



Comment at: clang/lib/AST/Interp/Integral.h:173
+  }
+
   template  static Integral from(Integral<0, SrcSign> Value) {

erichkeane wrote:
> aaron.ballman wrote:
> > tbaeder wrote:
> > > aaron.ballman wrote:
> > > > tbaeder wrote:
> > > > > I'm a bit out of my element with the template magic here.
> > > > It mostly looks correct to me, but the part I'm struggling with is 
> > > > `static_cast`; can you explain what you're trying to do 
> > > > there?
> > > I was trying to implement creating an Integral from a Boolean; the 
> > > `static_cast` casts to `Integral::T` (which in my case is `int`). It 
> > > might not be needed.
> > Oh!!! I see now why there's so much confusion. You have `template  > T>` and I was wondering why you were trying to use that here. I see now 
> > that there's `Integral::T` as a private member.
> > 
> > Can we please rename `Integral::T` to be something mildly descriptive? (I'm 
> > fine if that's done in a follow-up as an NFC change.)
> As Aaron said separately, the 'T' name of the integral member is bonkers and 
> confusing!
> 
> So it appears the intent here is to take a non-integral 'Value', cast it to 
> the underlying representation, and then call the version of this on 159.  
> 
> From a 'style' perspective, I'd prefer this live right next to that version 
> (since it is the inverse SFINAE).  In fact, I'd probably prefer you switch 
> this to an 'if constexpr' instead:
> 
> 
> ``` 
> template 
> static Integral from (ValTy Value) {
> if constexpr (std::is_integral_v) {
>return Integral(Value);
> } else {
>return Integral(static_cast(Value));
> }
>  }
> ```
> }
> ```
> 
That's a cool solution, thanks! And yes I'll push a renaming patch.


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

https://reviews.llvm.org/D132098

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


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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

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

https://reviews.llvm.org/D132098

Files:
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -1,15 +1,33 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++11 -verify %s
+// RUN: %clang_cc1 -std=c++11 -verify=ref %s
 
 static_assert(true, "");
-static_assert(false, ""); // expected-error{{failed}}
+static_assert(false, ""); // expected-error{{failed}} ref-error{{failed}}
 static_assert(nullptr == nullptr, "");
 static_assert(1 == 1, "");
-static_assert(1 == 3, ""); // expected-error{{failed}}
+static_assert(1 == 3, ""); // expected-error{{failed}} ref-error{{failed}}
 
 constexpr int number = 10;
 static_assert(number == 10, "");
-static_assert(number != 10, ""); // expected-error{{failed}}
+static_assert(number != 10, ""); // expected-error{{failed}} \
+ // ref-error{{failed}} \
+ // ref-note{{evaluates to}}
 
 constexpr bool getTrue() { return true; }
 constexpr bool getFalse() { return false; }
 constexpr void* getNull() { return nullptr; }
+
+constexpr int neg(int m) { return -m; }
+constexpr bool inv(bool b) { return !b; }
+
+static_assert(12, "");
+static_assert(12 == -(-(12)), "");
+static_assert(!false, "");
+static_assert(!!true, "");
+static_assert(!!true == !false, "");
+static_assert(true == 1, "");
+static_assert(false == 0, "");
+static_assert(!5 == false, "");
+static_assert(!0, "");
+static_assert(-true, "");
+static_assert(-false, ""); //expected-error{{failed}} ref-error{{failed}}
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -73,6 +73,10 @@
   let Types = [Ptr];
 }
 
+def BoolTypeClass : TypeClass {
+  let Types = [Bool];
+}
+
 def AllTypeClass : TypeClass {
   let Types = !listconcat(AluTypeClass.Types, PtrTypeClass.Types);
 }
@@ -383,6 +387,37 @@
 def Add : AluOpcode;
 def Mul : AluOpcode;
 
+
+//===--===//
+// Unary operators.
+//===--===//
+
+// [Real] -> [Real]
+def Inv: Opcode {
+  let Types = [BoolTypeClass];
+  let HasGroup = 1;
+}
+
+// [Real] -> [Real]
+def Neg: Opcode {
+  let Types = [AluTypeClass];
+  let HasGroup = 1;
+}
+
+//===--===//
+// Cast.
+//===--===//
+// TODO: Expand this to handle casts between more types.
+
+def Sint32TypeClass : TypeClass {
+  let Types = [Sint32];
+}
+
+def Cast: Opcode {
+  let Types = [BoolTypeClass, Sint32TypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Comparison opcodes.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -154,6 +154,36 @@
   return AddSubMulHelper(S, OpPC, Bits, LHS, RHS);
 }
 
+//===--===//
+// Inv
+//===--===//
+
+template ::T>
+bool Inv(InterpState &S, CodePtr OpPC) {
+  using BoolT = PrimConv::T;
+  const T &Val = S.Stk.pop();
+  const unsigned Bits = Val.bitWidth();
+  Boolean R;
+  Boolean::inv(BoolT::from(Val, Bits), &R);
+
+  S.Stk.push(R);
+  return true;
+}
+
+//===--===//
+// Neg
+//===--===//
+
+template ::T>
+bool Neg(InterpState &S, CodePtr OpPC) {
+  const T &Val = S.Stk.pop();
+  T Result;
+  T::neg(Val, &Result);
+
+  S.Stk.push(Result);
+  return true;
+}
+
 //===--===//
 // EQ, NE, GT, GE, LT, LE
 //===--===//
Index: clang/lib/AST/Interp/Integral.h
===
--- clang/lib/AST/Interp/Integral.h
+++ clang/lib/AST/Interp/Integral.h
@@ -155,9 +155,11 @@
 return Integral(Max);
   }
 
-  template 
-  static std::enable_if_t::value, Integral> from(T Value) {
-return Integral(Value);
+  te

[PATCH] D132141: [X86] Emulate _rdrand64_step with two rdrand32 if it is 32bit

2022-08-19 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: clang/test/CodeGen/X86/rdrand-builtins.c:20
 
 #if __x86_64__
 int rdrand64(unsigned long long *p) {

why do you still need the #if-else-endif?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132141

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


[PATCH] D130788: [clang-repl] Disable building when LLVM_STATIC_LINK_CXX_STDLIB is ON.

2022-08-19 Thread Sunho Kim via Phabricator via cfe-commits
sunho added a comment.

In D130788#3732325 , @sbc100 wrote:

> In D130788#3731232 , @sunho wrote:
>
>> In D130788#3730533 , @sbc100 wrote:
>>
>>> I'm not totally sure but I think the change is responsible for the 
>>> emscripten integration bot failing `InterpreterTest.CatchException`: 
>>> https://logs.chromium.org/logs/emscripten-releases/buildbucket/cr-buildbucket/8807160007692150337/+/u/LLVM_regression/stdout
>>>
>>>   [==] Running 1 test from 1 test suite.
>>>   [--] Global test environment set-up.
>>>   [--] 1 test from InterpreterTest
>>>   [ RUN  ] InterpreterTest.CatchException
>>>   JIT session error: Symbols not found: [ __gxx_personality_v0, 
>>> _ZSt9terminatev, _ZTVN10__cxxabiv117__class_type_infoE, 
>>> __cxa_allocate_exception, __cxa_begin_catch, __cxa_end_catch, 
>>> __cxa_free_exception, __cxa_throw ]
>>>   Failure value returned from cantFail wrapped call
>>>   Failed to materialize symbols: { (main, { _ZN16custom_exceptionC2EPKc, 
>>> __clang_call_terminate, _ZTI16custom_exception, _ZTS16custom_exception, 
>>> throw_exception }) }
>>>   UNREACHABLE executed at 
>>> /b/s/w/ir/cache/builder/emscripten-releases/llvm-project/llvm/include/llvm/Support/Error.h:786!
>>>   Stack dump without symbol names (ensure you have llvm-symbolizer in your 
>>> PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it):
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x2464413)[0x55cb14660413]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x246236c)[0x55cb1465e36c]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x24648df)[0x55cb146608df]
>>>   /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fad2fab1980]
>>>   /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7fad2eb0de87]
>>>   /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7fad2eb0f7f1]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x23f798f)[0x55cb145f398f]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x1e9de35)[0x55cb14099e35]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x1e9d597)[0x55cb14099597]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x246d6be)[0x55cb146696be]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x246e659)[0x55cb1466a659]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x246ee40)[0x55cb1466ae40]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x247b2c3)[0x55cb146772c3]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x247ab42)[0x55cb14676b42]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x246559c)[0x55cb1466159c]
>>>   /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x7fad2eaf0c87]
>>>   
>>> /b/s/w/ir/cache/builder/emscripten-releases/build/llvm-out/tools/clang/unittests/Interpreter/ExceptionTests/./ClangReplInterpreterExceptionTests(+0x1e9ceda)[0x55cb14098eda]
>>>
>>> This started happening consistently after this change 
>>> https://chromium.googlesource.com/emscripten-releases/+/584b2f531314d1e70cd5ebadcce7e015a6215c9a.
>>>   The only CL in that list that looks related seems to be this one.
>>
>> Could you share the detailed build configuration of those bots?
>
> All the step should be visible here: 
> https://ci.chromium.org/ui/p/emscripten-releases/builders/ci/linux-test-suites/b8805531315340503553/steps
>
> The most relevant one I guess would be:
>
> https://logs.chromium.org/logs/emscripten-releases/buildbucket/cr-buildbucket/8805531315340503553/+/u/Build_LLVM/stdout
>
> Here you can see LLVM being configured with:
>
>   
> subprocess.check_call(`/b/s/w/ir/cache/builder/emscripten-releases/cmake-3.21.3-linux-x86_64/bin/cmake
>  -G Ninja -DPython3_EXECUTAB

[PATCH] D130523: [pseudo] Perform unconstrained recovery prior to completion.

2022-08-19 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/GLR.cpp:621
 // Consume the token.
 glrShift(Heads, Terminals[I], Params, Lang, NextHeads);
 

hokein wrote:
> hokein wrote:
> > I think we can move the Line634 `Heads.resize(HeadsPartition)` before the 
> > `glrShift()` as we only do shift on the nearly-created heads, we might gain 
> > some performance back.
> oops, my previous comment is incorrect, here we want the second part of the 
> partition; while on recovery, we want the first part of partition.
> 
> we can pass `llvm::ArrayRef *>(Heads).drop_front(HeadsPartition);` as the Heads to `glrShift`.
> 
> 
As discussed offline, shifting onto a head that was produced by shift should be 
allowed.

given grammar
```
foo := [ ]
bar := [
baz := bar ]
```
and input `[]`, after `[` we have `Heads={ [, bar} }` with the former shifted 
and the latter reduced.
If we applied your suggestion here, we would fail to parse `foo` (but would 
succeed in parsing `baz`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130523

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


[PATCH] D130523: [pseudo] Perform unconstrained recovery prior to completion.

2022-08-19 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2cc7463c85c0: [pseudo] Perform unconstrained reduction prior 
to recovery. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D130523?vs=447487&id=453972#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130523

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp


Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -625,6 +625,32 @@
 "[  1, end) └─; := \n");
 }
 
+TEST_F(GLRTest, RecoverUnrestrictedReduce) {
+  // Here, ! is not in any rule and therefore not in the follow set of `word`.
+  // We would not normally reduce `word := IDENTIFIER`, but do so for recovery.
+
+  build(R"bnf(
+_ := sentence
+
+word := IDENTIFIER
+sentence := word word [recover=AcceptAnyTokenInstead]
+  )bnf");
+
+  clang::LangOptions LOptions;
+  const TokenStream &Tokens = cook(lex("id !", LOptions), LOptions);
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("AcceptAnyTokenInstead"),
+  [](Token::Index Start, const TokenStream &Stream) { return Start + 1; });
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("sentence"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) sentence := word word 
[recover=AcceptAnyTokenInstead]\n"
+"[  0,   1) ├─word := IDENTIFIER\n"
+"[  0,   1) │ └─IDENTIFIER := tok[0]\n"
+"[  1, end) └─word := \n");
+}
 
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
Index: clang-tools-extra/pseudo/lib/GLR.cpp
===
--- clang-tools-extra/pseudo/lib/GLR.cpp
+++ clang-tools-extra/pseudo/lib/GLR.cpp
@@ -601,6 +601,10 @@
   std::vector Heads = {GSS.addNode(/*State=*/StartState,
   /*ForestNode=*/nullptr,
   {})};
+  // Invariant: Heads is partitioned by source: {shifted | reduced}.
+  // HeadsPartition is the index of the first head formed by reduction.
+  // We use this to discard and recreate the reduced heads during recovery.
+  unsigned HeadsPartition = 0;
   std::vector NextHeads;
   auto MaybeGC = [&, Roots(std::vector{}), I(0u)]() mutable 
{
 assert(NextHeads.empty() && "Running GC at the wrong time!");
@@ -623,8 +627,17 @@
 // If we weren't able to consume the token, try to skip over some tokens
 // so we can keep parsing.
 if (NextHeads.empty()) {
-  // FIXME: Heads may not be fully reduced, because our reductions were
-  // constrained by lookahead (but lookahead is meaningless to recovery).
+  // The reduction in the previous round was constrained by lookahead.
+  // On valid code this only rejects dead ends, but on broken code we 
should
+  // consider all possibilities.
+  //
+  // We discard all heads formed by reduction, and recreate them without
+  // this constraint. This may duplicate some nodes, but it's rare.
+  LLVM_DEBUG(llvm::dbgs() << "Shift failed, will attempt recovery. "
+ "Re-reducing without lookahead.");
+  Heads.resize(HeadsPartition);
+  Reduce(Heads, /*allow all reductions*/ tokenSymbol(tok::unknown));
+
   glrRecover(Heads, I, Params, Lang, NextHeads);
   if (NextHeads.empty())
 // FIXME: Ensure the `_ := start-symbol` rules have a fallback
@@ -636,6 +649,7 @@
 // Form nonterminals containing the token we just consumed.
 SymbolID Lookahead =
 I == Terminals.size() ? tokenSymbol(tok::eof) : Terminals[I].symbol();
+HeadsPartition = NextHeads.size();
 Reduce(NextHeads, Lookahead);
 // Prepare for the next token.
 std::swap(Heads, NextHeads);
Index: clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
@@ -105,7 +105,11 @@
   bool canFollow(SymbolID Nonterminal, SymbolID Terminal) const {
 assert(isToken(Terminal));
 assert(isNonterminal(Nonterminal));
-return FollowSets.test(tok::NUM_TOKENS * Nonterminal +
+// tok::unknown is a sentinel value used in recovery: can follow anything.
+if (tok::unknown)
+  return true;
+return Terminal == tokenSymbol(tok::unknown) ||
+   FollowSets.test(tok::NUM_TOKENS * Nonterminal +
symbolToToken(Terminal));
 

[clang-tools-extra] 2cc7463 - [pseudo] Perform unconstrained reduction prior to recovery.

2022-08-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-08-19T15:07:36+02:00
New Revision: 2cc7463c85c056e956ad332448189ce3e9004182

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

LOG: [pseudo] Perform unconstrained reduction prior to recovery.

Our GLR uses lookahead: only perform reductions that might be consumed by the
shift immediately following. However when shift fails and so reduce is followed
by recovery instead, this restriction is incorrect and leads to missing heads.

In turn this means certain recovery strategies can't be made to work. e.g.
```
ns := NAMESPACE { namespace-body } [recover=Skip]
ns-body := namespace_opt
```
When `namespace { namespace {` is parsed, we can recover the inner `ns` (using
the `Skip` strategy to ignore the missing `}`). However this `namespace` will
not be reduced to a `namespace-body` as EOF is not in the follow-set, and so we
are unable to recover the outer `ns`.

This patch fixes this by tracking which heads were produced by constrained
reduce, and discarding and rebuilding them before performing recovery.

This is a prerequisite for the `Skip` strategy mentioned above, though there are
some other limitations we need to address too.

Reviewed By: hokein

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

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
index 890a5125a1ef..8d8f8f74f16e 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
@@ -105,7 +105,11 @@ class LRTable {
   bool canFollow(SymbolID Nonterminal, SymbolID Terminal) const {
 assert(isToken(Terminal));
 assert(isNonterminal(Nonterminal));
-return FollowSets.test(tok::NUM_TOKENS * Nonterminal +
+// tok::unknown is a sentinel value used in recovery: can follow anything.
+if (tok::unknown)
+  return true;
+return Terminal == tokenSymbol(tok::unknown) ||
+   FollowSets.test(tok::NUM_TOKENS * Nonterminal +
symbolToToken(Terminal));
   }
 

diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index 10a94860ffc9..1765eb18732c 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -601,6 +601,10 @@ const ForestNode &glrParse(const ParseParams &Params, 
SymbolID StartSymbol,
   std::vector Heads = {GSS.addNode(/*State=*/StartState,
   /*ForestNode=*/nullptr,
   {})};
+  // Invariant: Heads is partitioned by source: {shifted | reduced}.
+  // HeadsPartition is the index of the first head formed by reduction.
+  // We use this to discard and recreate the reduced heads during recovery.
+  unsigned HeadsPartition = 0;
   std::vector NextHeads;
   auto MaybeGC = [&, Roots(std::vector{}), I(0u)]() mutable 
{
 assert(NextHeads.empty() && "Running GC at the wrong time!");
@@ -623,8 +627,17 @@ const ForestNode &glrParse(const ParseParams &Params, 
SymbolID StartSymbol,
 // If we weren't able to consume the token, try to skip over some tokens
 // so we can keep parsing.
 if (NextHeads.empty()) {
-  // FIXME: Heads may not be fully reduced, because our reductions were
-  // constrained by lookahead (but lookahead is meaningless to recovery).
+  // The reduction in the previous round was constrained by lookahead.
+  // On valid code this only rejects dead ends, but on broken code we 
should
+  // consider all possibilities.
+  //
+  // We discard all heads formed by reduction, and recreate them without
+  // this constraint. This may duplicate some nodes, but it's rare.
+  LLVM_DEBUG(llvm::dbgs() << "Shift failed, will attempt recovery. "
+ "Re-reducing without lookahead.");
+  Heads.resize(HeadsPartition);
+  Reduce(Heads, /*allow all reductions*/ tokenSymbol(tok::unknown));
+
   glrRecover(Heads, I, Params, Lang, NextHeads);
   if (NextHeads.empty())
 // FIXME: Ensure the `_ := start-symbol` rules have a fallback
@@ -636,6 +649,7 @@ const ForestNode &glrParse(const ParseParams &Params, 
SymbolID StartSymbol,
 // Form nonterminals containing the token we just consumed.
 SymbolID Lookahead =
 I == Terminals.size() ? tokenSymbol(tok::eof) : Terminals[I].symbol();
+HeadsPartition = NextHeads.size();
 Reduce(NextHeads, Lookahead);
 // Prepare for the next token.
 

[PATCH] D131052: [CMake] Allow setting the location of host tools with LLVM_NATIVE_TOOL_DIR

2022-08-19 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D131052#3731894 , @sammccall wrote:

> FWIW I have no idea: in principle this makes sense, but I don't use such a 
> configuration and don't have a clear idea of what people who do use it want.

Thanks for having a look and discussing the matter! FWIW, my current cross 
compilation script does something like this: 
https://github.com/mstorsjo/llvm-mingw/blob/master/build-llvm.sh#L176-L195 All 
of those lines could be changed into setting this one option.

When there's more native tools added, I want to keep this in sync to avoid 
needless recompilation of those tools - which is kinda burdensome in the 
current setup - while with this option, we'd only need to set one option and be 
done with it. (As long as everything else works, if there's a new tool that I 
haven't got hooked up, it "only" makes things slower to build.)

> It also adds significant CMake complexity: e.g. clang-pseudo-gen now has 30 
> lines just to support the non-default "native tools" configuration, and this 
> is duplicated for each tool. Maybe this could be made cheaper by sharing more 
> of this logic in a separate place, but we should probably only add it at all 
> if this really is helping someone significantly.
>
> (Lines of CMake logic are extremely expensive to maintain IME: tooling and 
> diagnostics are poor, there are no tests, there are too many configurations 
> to reason about, interacting components are not documented, the language is 
> inherently confusing and many of us that maintain it have only a rudimentary 
> understanding)

This is a very good point indeed.

Most of the boilerplate for setting up clang-pseudo-gen and 
clang-tidy-confusable-chars-gen is identical, so those could probably be merged 
into a macro (hiding all the cross/native complexity entirely from the business 
logic, just like for tablegen) - but the complexity is still there. (It would 
end up in at least three cases; tablegen, llvm-config and in a 
generic-buildtime-tool-macro.)

On the topic of "really is helping someone significantly" - if we wouldn't have 
the burden of existing users using the existing options (for setting the path 
to each tool individually), picking this new option is a nobrainer - doing the 
same thing but in a much less annoying way. But since we have existing users 
with the existing options (which would need to be kept for some time 
transitionally), it's much less clear cut whether it's a "significant" 
improvement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131052

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


[clang-tools-extra] 605035b - [pseudo] Changes omitted from previous commit

2022-08-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-08-19T15:15:37+02:00
New Revision: 605035bf4508460f8c28857c7aaecf1d8c449ca8

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

LOG: [pseudo] Changes omitted from previous commit

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
clang-tools-extra/pseudo/lib/GLR.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
index 8d8f8f74f16e..fc21eff35792 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/LRTable.h
@@ -106,8 +106,6 @@ class LRTable {
 assert(isToken(Terminal));
 assert(isNonterminal(Nonterminal));
 // tok::unknown is a sentinel value used in recovery: can follow anything.
-if (tok::unknown)
-  return true;
 return Terminal == tokenSymbol(tok::unknown) ||
FollowSets.test(tok::NUM_TOKENS * Nonterminal +
symbolToToken(Terminal));

diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index 1765eb18732c..3e49a7a9c269 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -403,6 +403,10 @@ class GLRReduce {
   GLRReduce(const ParseParams &Params, const Language &Lang)
   : Params(Params), Lang(Lang) {}
 
+  // Reduce Heads, resulting in new nodes that are appended to Heads.
+  // The "consumed" nodes are not removed!
+  // Only reduce rules compatible with the Lookahead are applied, though
+  // tokenSymbol(tok::unknown) will match any rule.
   void operator()(std::vector &Heads, SymbolID Lookahead) {
 assert(isToken(Lookahead));
 



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


[PATCH] D129642: [Sema] Tweak diagnostic logic so suppress-in-hedaer logic works in tools too.

2022-08-19 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGac3178175988: [Sema] Tweak diagnostic logic so 
suppress-in-header logic works in tools too. (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129642

Files:
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang/lib/Sema/SemaDecl.cpp


Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -1855,7 +1855,7 @@
 // FIXME: This needs to be refactored; some other isInMainFile users want
 // these semantics.
 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
-  if (S.TUKind != TU_Complete)
+  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
 return false;
   return S.SourceMgr.isInMainFile(Loc);
 }
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -54,6 +54,9 @@
   return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
 }
 
+::testing::Matcher withID(unsigned ID) {
+  return Field(&Diag::ID, ID);
+}
 ::testing::Matcher
 withNote(::testing::Matcher NoteMatcher) {
   return Field(&Diag::Notes, ElementsAre(NoteMatcher));
@@ -1869,6 +1872,20 @@
   "'int' to 'int *' for 1st argument; take the address of "
   "the argument with &");
 }
+
+TEST(DiagnosticsTest, UnusedInHeader) {
+  // Clang diagnoses unused static inline functions outside headers.
+  auto TU = TestTU::withCode("static inline void foo(void) {}");
+  TU.ExtraArgs.push_back("-Wunused-function");
+  TU.Filename = "test.c";
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(withID(diag::warn_unused_function)));
+  // Sema should recognize a *.h file open in clangd as a header.
+  // https://github.com/clangd/vscode-clangd/issues/360
+  TU.Filename = "test.h";
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -1855,7 +1855,7 @@
 // FIXME: This needs to be refactored; some other isInMainFile users want
 // these semantics.
 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
-  if (S.TUKind != TU_Complete)
+  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
 return false;
   return S.SourceMgr.isInMainFile(Loc);
 }
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -54,6 +54,9 @@
   return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
 }
 
+::testing::Matcher withID(unsigned ID) {
+  return Field(&Diag::ID, ID);
+}
 ::testing::Matcher
 withNote(::testing::Matcher NoteMatcher) {
   return Field(&Diag::Notes, ElementsAre(NoteMatcher));
@@ -1869,6 +1872,20 @@
   "'int' to 'int *' for 1st argument; take the address of "
   "the argument with &");
 }
+
+TEST(DiagnosticsTest, UnusedInHeader) {
+  // Clang diagnoses unused static inline functions outside headers.
+  auto TU = TestTU::withCode("static inline void foo(void) {}");
+  TU.ExtraArgs.push_back("-Wunused-function");
+  TU.Filename = "test.c";
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(withID(diag::warn_unused_function)));
+  // Sema should recognize a *.h file open in clangd as a header.
+  // https://github.com/clangd/vscode-clangd/issues/360
+  TU.Filename = "test.h";
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] ac31781 - [Sema] Tweak diagnostic logic so suppress-in-header logic works in tools too.

2022-08-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-08-19T15:16:10+02:00
New Revision: ac31781759889226711b801c3833fea280fdb7aa

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

LOG: [Sema] Tweak diagnostic logic so suppress-in-header logic works in tools 
too.

Certain idioms are ignored by -Wunused in header files only.
The current "is a header" check assumes that if headers are the main file, we're
building a PCH or a module or something. However in tools we may be parsing the
header in its own right, but still want to treat it as a header.

Fixes https://github.com/clangd/vscode-clangd/issues/360

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang/lib/Sema/SemaDecl.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index 0a24f3c0c69b..306c8b122109 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -54,6 +54,9 @@ ::testing::Matcher 
withFix(::testing::Matcher FixMatcher1,
   return Field(&Diag::Fixes, UnorderedElementsAre(FixMatcher1, FixMatcher2));
 }
 
+::testing::Matcher withID(unsigned ID) {
+  return Field(&Diag::ID, ID);
+}
 ::testing::Matcher
 withNote(::testing::Matcher NoteMatcher) {
   return Field(&Diag::Notes, ElementsAre(NoteMatcher));
@@ -1869,6 +1872,20 @@ TEST(DiagnosticsTest, FixItFromHeader) {
   "'int' to 'int *' for 1st argument; take the address of "
   "the argument with &");
 }
+
+TEST(DiagnosticsTest, UnusedInHeader) {
+  // Clang diagnoses unused static inline functions outside headers.
+  auto TU = TestTU::withCode("static inline void foo(void) {}");
+  TU.ExtraArgs.push_back("-Wunused-function");
+  TU.Filename = "test.c";
+  EXPECT_THAT(*TU.build().getDiagnostics(),
+  ElementsAre(withID(diag::warn_unused_function)));
+  // Sema should recognize a *.h file open in clangd as a header.
+  // https://github.com/clangd/vscode-clangd/issues/360
+  TU.Filename = "test.h";
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d4c8377bbce7..33b49482c6e5 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1855,7 +1855,7 @@ bool Sema::mightHaveNonExternalLinkage(const 
DeclaratorDecl *D) {
 // FIXME: This needs to be refactored; some other isInMainFile users want
 // these semantics.
 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
-  if (S.TUKind != TU_Complete)
+  if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
 return false;
   return S.SourceMgr.isInMainFile(Loc);
 }



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


[PATCH] D131052: [CMake] Allow setting the location of host tools with LLVM_NATIVE_TOOL_DIR

2022-08-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

TL;DR: Thanks for explanation, LG if we move the common logic into a macro.

In D131052#3734986 , @mstorsjo wrote:

> In D131052#3731894 , @sammccall 
> wrote:
>
>> FWIW I have no idea: in principle this makes sense, but I don't use such a 
>> configuration and don't have a clear idea of what people who do use it want.
>
> Thanks for having a look and discussing the matter! FWIW, my current cross 
> compilation script does something like this: 
> https://github.com/mstorsjo/llvm-mingw/blob/master/build-llvm.sh#L176-L195 
> All of those lines could be changed into setting this one option.
>
> When there's more native tools added, I want to keep this in sync to avoid 
> needless recompilation of those tools - which is kinda burdensome in the 
> current setup - while with this option, we'd only need to set one option and 
> be done with it. (As long as everything else works, if there's a new tool 
> that I haven't got hooked up, it "only" makes things slower to build.)

Thanks, if this option is useful for you then I think it's probably useful for 
others too.
(Just want to make sure we're not adding features for no-one)

>> It also adds significant CMake complexity: e.g. clang-pseudo-gen now has 30 
>> lines just to support the non-default "native tools" configuration, and this 
>> is duplicated for each tool. Maybe this could be made cheaper by sharing 
>> more of this logic in a separate place, but we should probably only add it 
>> at all if this really is helping someone significantly.
>>
>> (Lines of CMake logic are extremely expensive to maintain IME: tooling and 
>> diagnostics are poor, there are no tests, there are too many configurations 
>> to reason about, interacting components are not documented, the language is 
>> inherently confusing and many of us that maintain it have only a rudimentary 
>> understanding)
>
> This is a very good point indeed.
>
> Most of the boilerplate for setting up clang-pseudo-gen and 
> clang-tidy-confusable-chars-gen is identical, so those could probably be 
> merged into a macro (hiding all the cross/native complexity entirely from the 
> business logic, just like for tablegen) - but the complexity is still there. 
> (It would end up in at least three cases; tablegen, llvm-config and in a 
> generic-buildtime-tool-macro.)

I think the generic tool macro would be valuable even if it can't be used for 
tablegen (though it's not obvious at first glance why not).
In practice if we copy the logic in two places it's extremely likely to get 
copied in a third and/or modified by someone who doesn't really understand it 
at some point. A macro would make this less likely, the macro name itself is 
documentation, it increases the benefit/cost of having a comment.

> On the topic of "really is helping someone significantly" - if we wouldn't 
> have the burden of existing users using the existing options (for setting the 
> path to each tool individually), picking this new option is a nobrainer - 
> doing the same thing but in a much less annoying way. But since we have 
> existing users with the existing options (which would need to be kept for 
> some time transitionally), it's much less clear cut whether it's a 
> "significant" improvement.

Agree this is probably a much nicer structure. (Only concern: is it likely that 
someone wants to use LLVM tools from out-of-tree but build clang tools in-tree?)
If it's plausible to remove the existing options, it probably makes sense to do 
it sooner rather than later - it'll break people the same amount either way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131052

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


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

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

updated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

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

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

[PATCH] D12669: [libcxxabi] Fix alignment of pointers returned by fallback_malloc

2022-08-19 Thread Louis Dionne via Phabricator via cfe-commits
ldionne commandeered this revision.
ldionne added a reviewer: EricWF.
ldionne added a comment.

Commandeering to abandon since we're landing D129842 
 instead.


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

https://reviews.llvm.org/D12669

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


[clang-tools-extra] e32799d - [pseudo] NFC, remove redundant ;

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

Author: Haojian Wu
Date: 2022-08-19T15:55:19+02:00
New Revision: e32799d1d6f84206712076d385a1ce03e0944ab3

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

LOG: [pseudo] NFC, remove redundant ;

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Forest.h

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
index f25e4cf1dd11..35212c18a116 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Forest.h
@@ -79,7 +79,7 @@ class alignas(class ForestNode *) ForestNode {
   llvm::ArrayRef elements() const {
 assert(kind() == Sequence);
 return children(Data >> RuleBits);
-  };
+  }
 
   // Returns all possible interpretations of the code.
   // REQUIRES: this is an Ambiguous node.
@@ -213,7 +213,7 @@ class ForestNode::RecursiveIterator
 public:
   RecursiveIterator(const ForestNode *N = nullptr) : Cur(N) {}
 
-  const ForestNode &operator*() const { return *Cur; };
+  const ForestNode &operator*() const { return *Cur; }
   void operator++();
   bool operator==(const RecursiveIterator &I) const { return Cur == I.Cur; }
   bool operator!=(const RecursiveIterator &I) const { return !(*this == I); }



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


[PATCH] D132229: [clang][dataflow] Mark `getDeclCtx` function in dataflow `Environment` `const`.

2022-08-19 Thread weiyi via Phabricator via cfe-commits
wyt created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
wyt 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/D132229

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


Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -348,7 +348,7 @@
 
   /// Returns the `DeclContext` of the block being analysed, if any. Otherwise,
   /// returns null.
-  const DeclContext *getDeclCtx() { return CallStack.back(); }
+  const DeclContext *getDeclCtx() const { return CallStack.back(); }
 
   /// Returns whether this `Environment` can be extended to analyze the given
   /// `Callee` (i.e. if `pushCall` can be used), with recursion disallowed and 
a


Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -348,7 +348,7 @@
 
   /// Returns the `DeclContext` of the block being analysed, if any. Otherwise,
   /// returns null.
-  const DeclContext *getDeclCtx() { return CallStack.back(); }
+  const DeclContext *getDeclCtx() const { return CallStack.back(); }
 
   /// Returns whether this `Environment` can be extended to analyze the given
   /// `Callee` (i.e. if `pushCall` can be used), with recursion disallowed and a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

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

LGTM!


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

https://reviews.llvm.org/D132098

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


[clang] 80bbc05 - [clang][Interp] Implement inv and neg unary operations

2022-08-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-08-19T16:05:00+02:00
New Revision: 80bbc05436d9c98d65b9b3a5f3907346ef3cb095

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

LOG: [clang][Interp] Implement inv and neg unary operations

Implement negating and inverting values. Also implement
IntegralToBoolean casts so the operations are easier to test.

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

Added: 


Modified: 
clang/lib/AST/Interp/Boolean.h
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/Integral.h
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Opcodes.td
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Boolean.h b/clang/lib/AST/Interp/Boolean.h
index 2baa717311bc4..cc3d4686f8f75 100644
--- a/clang/lib/AST/Interp/Boolean.h
+++ b/clang/lib/AST/Interp/Boolean.h
@@ -49,6 +49,7 @@ class Boolean {
   explicit operator unsigned() const { return V; }
   explicit operator int64_t() const { return V; }
   explicit operator uint64_t() const { return V; }
+  explicit operator int() const { return V; }
 
   APSInt toAPSInt() const {
 return APSInt(APInt(1, static_cast(V), false), true);
@@ -134,6 +135,16 @@ class Boolean {
 *R = Boolean(A.V && B.V);
 return false;
   }
+
+  static bool inv(Boolean A, Boolean *R) {
+*R = Boolean(!A.V);
+return false;
+  }
+
+  static bool neg(Boolean A, Boolean *R) {
+*R = Boolean(A.V);
+return false;
+  }
 };
 
 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Boolean &B) {

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 732d4d5c15a28..8f53f0e1d6f5b 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -116,13 +116,36 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   case CK_NullToPointer:
 return this->Visit(SubExpr);
 
+  case CK_IntegralCast: {
+Optional FromT = classify(SubExpr->getType());
+Optional ToT = classify(CE->getType());
+if (!FromT || !ToT)
+  return false;
+
+if (!this->Visit(SubExpr))
+  return false;
+
+return this->emitCast(*FromT, *ToT, CE);
+  }
+
   case CK_ToVoid:
 return discard(SubExpr);
 
-  default: {
-// TODO: implement other casts.
-return this->bail(CE);
-  }
+  case CK_IntegralToBoolean:
+// Compare integral from Subexpr with 0
+if (Optional T = classify(SubExpr->getType())) {
+  if (!this->Visit(SubExpr))
+return false;
+
+  if (!this->emitConst(SubExpr, 0))
+return false;
+
+  return this->emitNE(*T, SubExpr);
+}
+return false;
+
+  default:
+assert(false && "Cast not implemented");
   }
 }
 
@@ -583,6 +606,40 @@ bool ByteCodeExprGen::VisitCXXNullPtrLiteralExpr(
   return this->emitNullPtr(E);
 }
 
+template 
+bool ByteCodeExprGen::VisitUnaryOperator(const UnaryOperator *E) {
+  if (!this->Visit(E->getSubExpr()))
+return false;
+
+  switch (E->getOpcode()) {
+  case UO_PostInc: // x++
+  case UO_PostDec: // x--
+  case UO_PreInc:  // --x
+  case UO_PreDec:  // ++x
+return false;
+
+  case UO_LNot: // !x
+return this->emitInvBool(E);
+  case UO_Minus: // -x
+if (Optional T = classify(E->getType()))
+  return this->emitNeg(*T, E);
+return false;
+  case UO_Plus:  // +x
+return true; // noop
+
+  case UO_AddrOf: // &x
+  case UO_Deref:  // *x
+  case UO_Not:// ~x
+  case UO_Real:   // __real x
+  case UO_Imag:   // __imag x
+  case UO_Extension:
+  case UO_Coawait:
+assert(false && "Unhandled opcode");
+  }
+
+  return false;
+}
+
 template 
 void ByteCodeExprGen::emitCleanup() {
   for (VariableScope *C = VarScope; C; C = C->getParent())

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 4ce1c8dbe11c1..ae023aee9390d 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -71,6 +71,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitBinaryOperator(const BinaryOperator *E);
   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
+  bool VisitUnaryOperator(const UnaryOperator *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/lib/AST/Interp/Integral.h b/clang/lib/AST/Interp/Integral.h
index 46cd611ee3892..fd2c0947a516a 100644
--- a/clang/lib/AST/Interp/Integral.h
+++ b/clang/lib/AST/Interp/Integral.h
@@ -155,9 +155,11 @@ template  class Integral {
 return Integral(Max);
   }
 
-  template 
-  static std::enable_if_t::value, Integral> from(T Value) {
-return Integral(Value);
+  template  static In

[PATCH] D132098: [clang][Interp] Implement inv and neg unary operations

2022-08-19 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG80bbc05436d9: [clang][Interp] Implement inv and neg unary 
operations (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132098

Files:
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -1,15 +1,33 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++11 -verify %s
+// RUN: %clang_cc1 -std=c++11 -verify=ref %s
 
 static_assert(true, "");
-static_assert(false, ""); // expected-error{{failed}}
+static_assert(false, ""); // expected-error{{failed}} ref-error{{failed}}
 static_assert(nullptr == nullptr, "");
 static_assert(1 == 1, "");
-static_assert(1 == 3, ""); // expected-error{{failed}}
+static_assert(1 == 3, ""); // expected-error{{failed}} ref-error{{failed}}
 
 constexpr int number = 10;
 static_assert(number == 10, "");
-static_assert(number != 10, ""); // expected-error{{failed}}
+static_assert(number != 10, ""); // expected-error{{failed}} \
+ // ref-error{{failed}} \
+ // ref-note{{evaluates to}}
 
 constexpr bool getTrue() { return true; }
 constexpr bool getFalse() { return false; }
 constexpr void* getNull() { return nullptr; }
+
+constexpr int neg(int m) { return -m; }
+constexpr bool inv(bool b) { return !b; }
+
+static_assert(12, "");
+static_assert(12 == -(-(12)), "");
+static_assert(!false, "");
+static_assert(!!true, "");
+static_assert(!!true == !false, "");
+static_assert(true == 1, "");
+static_assert(false == 0, "");
+static_assert(!5 == false, "");
+static_assert(!0, "");
+static_assert(-true, "");
+static_assert(-false, ""); //expected-error{{failed}} ref-error{{failed}}
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -73,6 +73,10 @@
   let Types = [Ptr];
 }
 
+def BoolTypeClass : TypeClass {
+  let Types = [Bool];
+}
+
 def AllTypeClass : TypeClass {
   let Types = !listconcat(AluTypeClass.Types, PtrTypeClass.Types);
 }
@@ -383,6 +387,37 @@
 def Add : AluOpcode;
 def Mul : AluOpcode;
 
+
+//===--===//
+// Unary operators.
+//===--===//
+
+// [Real] -> [Real]
+def Inv: Opcode {
+  let Types = [BoolTypeClass];
+  let HasGroup = 1;
+}
+
+// [Real] -> [Real]
+def Neg: Opcode {
+  let Types = [AluTypeClass];
+  let HasGroup = 1;
+}
+
+//===--===//
+// Cast.
+//===--===//
+// TODO: Expand this to handle casts between more types.
+
+def Sint32TypeClass : TypeClass {
+  let Types = [Sint32];
+}
+
+def Cast: Opcode {
+  let Types = [BoolTypeClass, Sint32TypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Comparison opcodes.
 //===--===//
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -154,6 +154,36 @@
   return AddSubMulHelper(S, OpPC, Bits, LHS, RHS);
 }
 
+//===--===//
+// Inv
+//===--===//
+
+template ::T>
+bool Inv(InterpState &S, CodePtr OpPC) {
+  using BoolT = PrimConv::T;
+  const T &Val = S.Stk.pop();
+  const unsigned Bits = Val.bitWidth();
+  Boolean R;
+  Boolean::inv(BoolT::from(Val, Bits), &R);
+
+  S.Stk.push(R);
+  return true;
+}
+
+//===--===//
+// Neg
+//===--===//
+
+template ::T>
+bool Neg(InterpState &S, CodePtr OpPC) {
+  const T &Val = S.Stk.pop();
+  T Result;
+  T::neg(Val, &Result);
+
+  S.Stk.push(Result);
+  return true;
+}
+
 //===--===//
 // EQ, NE, GT, GE, LT, LE
 //===--===//
Index: clang/lib/AST/Interp/Integral.h
===
--- clang/lib/AST/Interp/Integral.h
+++ clang/lib/AST/In

[clang] 7614785 - [clang][Interp] Rename Integral::T to Integral::ReprT

2022-08-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2022-08-19T16:14:37+02:00
New Revision: 7614785e1d284db5b1d1b9b0017f3bb5a3724f8c

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

LOG: [clang][Interp] Rename Integral::T to Integral::ReprT

Just 'T' is a bit generic and causes confusion.

Added: 


Modified: 
clang/lib/AST/Interp/Integral.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Integral.h b/clang/lib/AST/Interp/Integral.h
index fd2c0947a516..dc17df44282a 100644
--- a/clang/lib/AST/Interp/Integral.h
+++ b/clang/lib/AST/Interp/Integral.h
@@ -58,12 +58,12 @@ template  class Integral {
   template  friend class Integral;
 
   // The primitive representing the integral.
-  using T = typename Repr::Type;
-  T V;
+  using ReprT = typename Repr::Type;
+  ReprT V;
 
   /// Primitive representing limits.
-  static const auto Min = std::numeric_limits::min();
-  static const auto Max = std::numeric_limits::max();
+  static const auto Min = std::numeric_limits::min();
+  static const auto Max = std::numeric_limits::max();
 
   /// Construct an integral from anything that is convertible to storage.
   template  explicit Integral(T V) : V(V) {}
@@ -124,25 +124,27 @@ template  class Integral {
 
   bool isMin() const { return *this == min(bitWidth()); }
 
-  bool isMinusOne() const { return Signed && V == T(-1); }
+  bool isMinusOne() const { return Signed && V == ReprT(-1); }
 
   constexpr static bool isSigned() { return Signed; }
 
-  bool isNegative() const { return V < T(0); }
+  bool isNegative() const { return V < ReprT(0); }
   bool isPositive() const { return !isNegative(); }
 
   ComparisonCategoryResult compare(const Integral &RHS) const {
 return Compare(V, RHS.V);
   }
 
-  unsigned countLeadingZeros() const { return llvm::countLeadingZeros(V); }
+  unsigned countLeadingZeros() const {
+return llvm::countLeadingZeros(V);
+  }
 
   Integral truncate(unsigned TruncBits) const {
 if (TruncBits >= Bits)
   return *this;
-const T BitMask = (T(1) << T(TruncBits)) - 1;
-const T SignBit = T(1) << (TruncBits - 1);
-const T ExtMask = ~BitMask;
+const ReprT BitMask = (ReprT(1) << ReprT(TruncBits)) - 1;
+const ReprT SignBit = ReprT(1) << (TruncBits - 1);
+const ReprT ExtMask = ~BitMask;
 return Integral((V & BitMask) | (Signed && (V & SignBit) ? ExtMask : 0));
   }
 
@@ -159,7 +161,7 @@ template  class Integral {
 if constexpr (std::is_integral::value)
   return Integral(Value);
 else
-  return Integral::from(static_cast(Value));
+  return Integral::from(static_cast(Value));
   }
 
   template 
@@ -182,15 +184,15 @@ template  class Integral {
   }
 
   static bool inRange(int64_t Value, unsigned NumBits) {
-return CheckRange(Value);
+return CheckRange(Value);
   }
 
   static bool increment(Integral A, Integral *R) {
-return add(A, Integral(T(1)), A.bitWidth(), R);
+return add(A, Integral(ReprT(1)), A.bitWidth(), R);
   }
 
   static bool decrement(Integral A, Integral *R) {
-return sub(A, Integral(T(1)), A.bitWidth(), R);
+return sub(A, Integral(ReprT(1)), A.bitWidth(), R);
   }
 
   static bool add(Integral A, Integral B, unsigned OpBits, Integral *R) {



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


[PATCH] D132197: [RISCV] Use Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC

2022-08-19 Thread Philip Reames via Phabricator via cfe-commits
reames accepted this revision.
reames added a comment.
This revision is now accepted and ready to land.

LGTM w/ optional comment.




Comment at: clang/lib/Driver/ToolChains/Linux.cpp:741
  getTriple().getArch() == llvm::Triple::thumbeb;
-  const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
+  const bool IsRISCV64 = getTriple().isRISCV64();
   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;

I would leave this one unchanged for consistency with surrounding code.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132197

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


[PATCH] D132079: [AMDGPU] Add iglp_opt builtin and MFMA GEMM Opt strategy

2022-08-19 Thread Jeffrey Byrnes via Phabricator via cfe-commits
jrbyrnes added inline comments.



Comment at: llvm/lib/Target/AMDGPU/AMDGPUIGroupLP.cpp:1063
+} else if (Opc == AMDGPU::IGLP_OPT) {
+  if (!foundSB && !foundIGLP)
+initIGLPOpt(*R);

I think this makes more sense if you parse the entire dag first, then check if 
neither were found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132079

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


[PATCH] D130768: [OpenCL][SPIR-V] Add test for extern functions with a pointer

2022-08-19 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh accepted this revision.
svenvh added a comment.

LGTM.


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

https://reviews.llvm.org/D130768

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


[PATCH] D132232: Update coding standards for constexpr if statements; NFC

2022-08-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: dblaikie, rjmccall, echristo, erichkeane.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added a project: LLVM.

We currently suggest that users not use an `else` clause after a `return` 
statement in a prior `if` branch. e.g.,

  if (foo)
return 1;
  else // Should remove this else clause
return 10;

however, this suggestion is incorrect for a constexpr if statement because one 
of the two branches will be a discarded statement and thus can impact template 
instantiation behavior. This updates the coding standard to make it clear that 
it's okay to have a `return` after an `else` in a constexpr if statement.

I think this is an NFC change to the intent of the rule, which is why I've not 
started an RFC for the changes.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132232

Files:
  llvm/docs/CodingStandards.rst


Index: llvm/docs/CodingStandards.rst
===
--- llvm/docs/CodingStandards.rst
+++ llvm/docs/CodingStandards.rst
@@ -1026,6 +1026,21 @@
 The idea is to reduce indentation and the amount of code you have to keep track
 of when reading the code.
 
+Note: this advice does not apply to a ``constexpr if`` statement. The
+substatement of the ``else`` clause may be a discarded statement, so removing
+the ``else`` can cause unexpected template instantiations. Thus, the following
+example is correct:
+
+.. code-block:: c++
+
+  template 
+  static int foo(Ty T) {
+if constexpr (std::is_integral_v)
+  return 10 + T;
+else
+  return 100;
+  }
+
 Turn Predicate Loops into Predicate Functions
 ^
 


Index: llvm/docs/CodingStandards.rst
===
--- llvm/docs/CodingStandards.rst
+++ llvm/docs/CodingStandards.rst
@@ -1026,6 +1026,21 @@
 The idea is to reduce indentation and the amount of code you have to keep track
 of when reading the code.
 
+Note: this advice does not apply to a ``constexpr if`` statement. The
+substatement of the ``else`` clause may be a discarded statement, so removing
+the ``else`` can cause unexpected template instantiations. Thus, the following
+example is correct:
+
+.. code-block:: c++
+
+  template 
+  static int foo(Ty T) {
+if constexpr (std::is_integral_v)
+  return 10 + T;
+else
+  return 100;
+  }
+
 Turn Predicate Loops into Predicate Functions
 ^
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129608: [Clang][OpenMP] Fix segmentation fault when data field is used in is_device_pt.

2022-08-19 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

It looks like this commit introduces an AddressSanitizer: stack-use-after-scope 
error:

  ==2796==ERROR: AddressSanitizer: stack-use-after-scope on address 
0x7f544e9acc20 at pc 0x55f1f7f4b83e bp 0x7ffdfb37c560 sp 0x7ffdfb37c558
  READ of size 4 at 0x7f544e9acc20 thread T0
  #0 0x55f1f7f4b83d in find 
toolchain/bin/../include/c++/v1/__algorithm/find.h:25:9
  #1 0x55f1f7f4b83d in 
is_contained &, 
clang::OpenMPMapModifierKind> 
llvm-project/llvm/include/llvm/ADT/STLExtras.h:1684:10
  #2 0x55f1f7f4b83d in (anonymous 
namespace)::MappableExprsHandler::getMapTypeBits(clang::OpenMPMapClauseKind, 
llvm::ArrayRef, 
llvm::ArrayRef, bool, bool, bool, bool) const 
llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:7507:9
  #3 0x55f1f7f460b5 in (anonymous 
namespace)::MappableExprsHandler::generateInfoForComponentList(clang::OpenMPMapClauseKind,
 llvm::ArrayRef, 
llvm::ArrayRef, 
llvm::ArrayRef, 
(anonymous namespace)::MappableExprsHandler::MapCombinedInfoTy&, (anonymous 
namespace)::MappableExprsHandler::StructRangeInfoTy&, bool, bool, 
clang::ValueDecl const*, bool, clang::ValueDecl const*, clang::Expr const*, 
llvm::ArrayRef>)
 const llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:8078:45
  #4 0x55f1f7f592f7 in generateInfoForCapture 
llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:9272:9
  #5 0x55f1f7f592f7 in 
clang::CodeGen::CGOpenMPRuntime::emitTargetCall(clang::CodeGen::CodeGenFunction&,
 clang::OMPExecutableDirective const&, llvm::Function*, llvm::Value*, 
clang::Expr const*, llvm::PointerIntPair, llvm::PointerIntPairInfo>>, 
llvm::function_ref)::$_22::operator()(clang::CodeGen::CodeGenFunction&, 
clang::CodeGen::PrePostActionTy&) const 
llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:10411:19
  #6 0x55f1f7ec9f8b in 
clang::CodeGen::RegionCodeGenTy::operator()(clang::CodeGen::CodeGenFunction&) 
const llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:603:5
  #7 0x55f1f7f20fb5 in 
clang::CodeGen::CGOpenMPRuntime::emitTargetCall(clang::CodeGen::CodeGenFunction&,
 clang::OMPExecutableDirective const&, llvm::Function*, llvm::Value*, 
clang::Expr const*, llvm::PointerIntPair, llvm::PointerIntPairInfo>>, 
llvm::function_ref) 
llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp:10497:7
  #8 0x55f1f7dbbad3 in 
emitCommonOMPTargetDirective(clang::CodeGen::CodeGenFunction&, 
clang::OMPExecutableDirective const&, clang::CodeGen::RegionCodeGenTy const&) 
llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp:6639:26
  #9 0x55f1f7ddb476 in 
clang::CodeGen::CodeGenFunction::EmitOMPTargetDirective(clang::OMPTargetDirective
 const&) llvm-project/clang/lib/CodeGen/CGStmtOpenMP.cpp:6675:3
  #10 0x55f1f7d877db in 
clang::CodeGen::CodeGenFunction::EmitCompoundStmtWithoutScope(clang::CompoundStmt
 const&, bool, clang::CodeGen::AggValueSlot) 
llvm-project/clang/lib/CodeGen/CGStmt.cpp:531:7
  #11 0x55f1f822ede6 in 
clang::CodeGen::CodeGenFunction::EmitFunctionBody(clang::Stmt const*) 
llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp:1234:5
  #12 0x55f1f82304de in 
clang::CodeGen::CodeGenFunction::GenerateCode(clang::GlobalDecl, 
llvm::Function*, clang::CodeGen::CGFunctionInfo const&) 
llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp:1442:5
  #13 0x55f1f826ebdf in 
clang::CodeGen::CodeGenModule::EmitGlobalFunctionDefinition(clang::GlobalDecl, 
llvm::GlobalValue*) llvm-project/clang/lib/CodeGen/CodeGenModule.cpp:5243:26
  #14 0x55f1f8261f55 in 
clang::CodeGen::CodeGenModule::EmitGlobalDefinition(clang::GlobalDecl, 
llvm::GlobalValue*) llvm-project/clang/lib/CodeGen/CodeGenModule.cpp:3510:9
  #15 0x55f1f824b75d in clang::CodeGen::CodeGenModule::EmitDeferred() 
llvm-project/clang/lib/CodeGen/CodeGenModule.cpp:2681:5
  #16 0x55f1f824b79d in clang::CodeGen::CodeGenModule::EmitDeferred() 
llvm-project/clang/lib/CodeGen/CodeGenModule.cpp:2687:7
  #17 0x55f1f824742e in clang::CodeGen::CodeGenModule::Release() 
llvm-project/clang/lib/CodeGen/CodeGenModule.cpp:526:3
  #18 0x55f1f848b03f in (anonymous 
namespace)::CodeGeneratorImpl::HandleTranslationUnit(clang::ASTContext&) 
llvm-project/clang/lib/CodeGen/ModuleBuilder.cpp:286:18
  #19 0x55f1f7b5cf7a in 
clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) 
llvm-project/clang/lib/CodeGen/CodeGenAction.cpp:306:14
  #20 0x55f1f96d724a in clang::ParseAST(clang::Sema&, bool, bool) 
llvm-project/clang/lib/Parse/ParseAST.cpp:198:13
  #21 0x55f1f7b5816f in clang::CodeGenAction::ExecuteAction() 
llvm-project/clang/lib/CodeGen/CodeGenAction.cpp:1144:30
  #22 0x55f1f923f912 in clang::FrontendAction::Execute() 
llvm-project/clang/lib/Frontend/FrontendAction.cpp:1037:8
  #23 0x55f1f916e16d in 
clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) 
llvm-project/clang/lib/Frontend/CompilerInstance.cpp:1035:33
  #24 0x55f1f742275c in 
clang::ExecuteCompilerInvocation(clang::CompilerInstance*) 
llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cp

[PATCH] D132232: Update coding standards for constexpr if statements; NFC

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

Agreed.  For other reviewers, note that this is the compelling example:

  template
  static constexpr bool VarTempl = true;
  
  template
  int func() {
if constexpr (VarTempl)
  return 1;

static_assert(!VarTempl);
  }
  
  void use() {
  func();
  }

The static-assert would fail, since it isn't a discarded statement.

  template
  static constexpr bool VarTempl = true;
  
  template
  int func() {
if constexpr (VarTempl)
  return 1;
else 
static_assert(!VarTempl);
  }
  
  void use() {
  func();
  }

But in THIS case the static-assert is discarded. That is, the 'else' in a 
if-constexpr isn't required to be anything other than lexically valid, so 
dependent lookup doesn't need to happen, instantiations aren't required, etc.

Therefore there is EXTREME value to having an 'else' there after a return.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132232

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


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

2022-08-19 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfd874e5fb119: Missing tautological compare warnings due to 
unary operators (authored by Codesbyusman, committed by aaron.ballman).

Changed prior to commit:
  https://reviews.llvm.org/D130510?vs=453976&id=453997#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130510

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

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

[clang] fd874e5 - Missing tautological compare warnings due to unary operators

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

Author: Muhammad Usman Shahid
Date: 2022-08-19T10:46:29-04:00
New Revision: fd874e5fb119e1d9f427a299ffa5bbabaeba9455

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

LOG: Missing tautological compare warnings due to unary operators

The patch mainly focuses on the no warnings for -Wtautological-compare.
It work fine for the positive numbers but doesn't for the negative
numbers. This is because the warning explicitly checks for an
IntegerLiteral AST node, but -1 is represented by a UnaryOperator with
an IntegerLiteral sub-Expr.

Fixes #42918
Differential Revision: https://reviews.llvm.org/D130510

Added: 


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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ccbe7a510ea80..e313f006b514e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -75,6 +75,9 @@ Bug Fixes
   This fixes `Issue 56094 
`_.
 - Fix `#57151 `_.
   ``-Wcomma`` is emitted for void returning functions.
+- ``-Wtautological-compare`` missed warnings for tautological comparisons
+  involving a negative integer literal. This fixes
+  `Issue 42918 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 2b99b8e680805..31655e43e8993 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -72,6 +72,10 @@ static SourceLocation GetEndLoc(Decl *D) {
 
 /// Returns true on constant values based around a single IntegerLiteral.
 /// Allow for use of parentheses, integer casts, and negative signs.
+/// FIXME: it would be good to unify this function with
+/// getIntegerLiteralSubexpressionValue at some point given the similarity
+/// between the functions.
+
 static bool IsIntegerLiteralConstantExpr(const Expr *E) {
   // Allow parentheses
   E = E->IgnoreParens();
@@ -964,15 +968,16 @@ class CFGBuilder {
 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
 
-const IntegerLiteral *IntLiteral = dyn_cast(LHSExpr);
+Optional IntLiteral1 =
+getIntegerLiteralSubexpressionValue(LHSExpr);
 const Expr *BoolExpr = RHSExpr;
 
-if (!IntLiteral) {
-  IntLiteral = dyn_cast(RHSExpr);
+if (!IntLiteral1) {
+  IntLiteral1 = getIntegerLiteralSubexpressionValue(RHSExpr);
   BoolExpr = LHSExpr;
 }
 
-if (!IntLiteral)
+if (!IntLiteral1)
   return TryResult();
 
 const BinaryOperator *BitOp = dyn_cast(BoolExpr);
@@ -981,26 +986,26 @@ class CFGBuilder {
   const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
   const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
 
-  const IntegerLiteral *IntLiteral2 = dyn_cast(LHSExpr2);
+  Optional IntLiteral2 =
+  getIntegerLiteralSubexpressionValue(LHSExpr2);
 
   if (!IntLiteral2)
-IntLiteral2 = dyn_cast(RHSExpr2);
+IntLiteral2 = getIntegerLiteralSubexpressionValue(RHSExpr2);
 
   if (!IntLiteral2)
 return TryResult();
 
-  llvm::APInt L1 = IntLiteral->getValue();
-  llvm::APInt L2 = IntLiteral2->getValue();
-  if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
-  (BitOp->getOpcode() == BO_Or  && (L2 | L1) != L1)) {
+  if ((BitOp->getOpcode() == BO_And &&
+   (*IntLiteral2 & *IntLiteral1) != *IntLiteral1) ||
+  (BitOp->getOpcode() == BO_Or &&
+   (*IntLiteral2 | *IntLiteral1) != *IntLiteral1)) {
 if (BuildOpts.Observer)
   BuildOpts.Observer->compareBitwiseEquality(B,
  B->getOpcode() != BO_EQ);
 TryResult(B->getOpcode() != BO_EQ);
   }
 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
-  llvm::APInt IntValue = IntLiteral->getValue();
-  if ((IntValue == 1) || (IntValue == 0)) {
+  if ((*IntLiteral1 == 1) || (*IntLiteral1 == 0)) {
 return TryResult();
   }
   return TryResult(B->getOpcode() != BO_EQ);
@@ -1009,6 +1014,46 @@ class CFGBuilder {
 return TryResult();
   }
 
+  // Helper function to get an APInt from an expression. Supports expressions
+  // which are an IntegerLiteral or a UnaryOperator and returns the value with
+  // all operations performed on it.
+  // FIXME: it would be good to unify this function with
+  // IsIntegerLiteralConstantExpr at some point given the similarity between 
the
+  // functions.
+  Optiona

[clang-tools-extra] bd5cc65 - [pseudo] Start rules are `_ := start-symbol EOF`, improve recovery.

2022-08-19 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-08-19T16:49:37+02:00
New Revision: bd5cc6575bdbe1d091f1cc70fb7f0b3c07cb894b

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

LOG: [pseudo] Start rules are `_ := start-symbol EOF`, improve recovery.

Previously we were calling glrRecover() ad-hoc at the end of input.
Two main problems with this:
 - glrRecover() on two separate code paths is inelegant
 - We may have to recover several times in succession (e.g. to exit from
   nested scopes), so we need a loop at end-of-file
Having an actual shift action for an EOF terminal allows us to handle
both concerns in the main shift/recover/reduce loop.

This revealed a recovery design bug where recovery could enter a loop by
repeatedly choosing the same parent to identically recover from.
Addressed this by allowing each node to be used as a recovery base once.

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

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
clang-tools-extra/pseudo/lib/Forest.cpp
clang-tools-extra/pseudo/lib/GLR.cpp
clang-tools-extra/pseudo/lib/cxx/cxx.bnf
clang-tools-extra/pseudo/lib/grammar/LRGraph.cpp
clang-tools-extra/pseudo/test/lr-build-basic.test
clang-tools-extra/pseudo/test/lr-build-conflicts.test
clang-tools-extra/pseudo/unittests/ForestTest.cpp
clang-tools-extra/pseudo/unittests/GLRTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
index 7b0a80920da98..f5257ce8d82f3 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
@@ -71,6 +71,8 @@ struct GSS {
 LRTable::StateID State;
 // Used internally to track reachability during garbage collection.
 bool GCParity;
+// Have we already used this node for error recovery? (prevents loops)
+mutable bool Recovered = false;
 // Number of the parents of this node.
 // The parents hold previous parsed symbols, and may resume control after
 // this node is reduced.

diff  --git a/clang-tools-extra/pseudo/lib/Forest.cpp 
b/clang-tools-extra/pseudo/lib/Forest.cpp
index bea93809c5b38..131dd4dca8393 100644
--- a/clang-tools-extra/pseudo/lib/Forest.cpp
+++ b/clang-tools-extra/pseudo/lib/Forest.cpp
@@ -178,7 +178,7 @@ std::string ForestNode::dumpRecursive(const Grammar &G,
 
 llvm::ArrayRef
 ForestArena::createTerminals(const TokenStream &Code) {
-  ForestNode *Terminals = Arena.Allocate(Code.tokens().size());
+  ForestNode *Terminals = Arena.Allocate(Code.tokens().size() + 1);
   size_t Index = 0;
   for (const auto &T : Code.tokens()) {
 new (&Terminals[Index])
@@ -186,6 +186,12 @@ ForestArena::createTerminals(const TokenStream &Code) {
/*Start=*/Index, /*TerminalData*/ 0);
 ++Index;
   }
+  // Include an `eof` terminal.
+  // This is important to drive the final shift/recover/reduce loop.
+  new (&Terminals[Index])
+  ForestNode(ForestNode::Terminal, tokenSymbol(tok::eof),
+ /*Start=*/Index, /*TerminalData*/ 0);
+  ++Index;
   NodeCount = Index;
   return llvm::makeArrayRef(Terminals, Index);
 }

diff  --git a/clang-tools-extra/pseudo/lib/GLR.cpp 
b/clang-tools-extra/pseudo/lib/GLR.cpp
index 3e49a7a9c2691..8e4e6181eb2a6 100644
--- a/clang-tools-extra/pseudo/lib/GLR.cpp
+++ b/clang-tools-extra/pseudo/lib/GLR.cpp
@@ -95,17 +95,19 @@ void glrRecover(llvm::ArrayRef OldHeads,
   auto WalkUp = [&](const GSS::Node *N, Token::Index NextTok, auto &WalkUp) {
 if (!Seen.insert(N).second)
   return;
-for (auto Strategy : Lang.Table.getRecovery(N->State)) {
-  Options.push_back(PlaceholderRecovery{
-  NextTok,
-  Strategy.Result,
-  Strategy.Strategy,
-  N,
-  Path,
-  });
-  LLVM_DEBUG(llvm::dbgs()
- << "Option: recover " << Lang.G.symbolName(Strategy.Result)
- << " at token " << NextTok << "\n");
+if (!N->Recovered) { // Don't recover the same way twice!
+  for (auto Strategy : Lang.Table.getRecovery(N->State)) {
+Options.push_back(PlaceholderRecovery{
+NextTok,
+Strategy.Result,
+Strategy.Strategy,
+N,
+Path,
+});
+LLVM_DEBUG(llvm::dbgs()
+   << "Option: recover " << Lang.G.symbolName(Strategy.Result)
+   << " at token " << NextTok << "\n");
+  }
 }
 Path.push_back(N->Payload);
 for (const GSS::Node *Parent : N->parents())
@@ -180,6 +182,7 @@ void glrRecover(llvm::ArrayRef OldHeads,
   // There are various options, including simply breaking ties between options.
   // For now it's obscure enough to ignore.
   for (const Placeh

[PATCH] D130550: [pseudo] Start rules are `_ := start-symbol EOF`, improve recovery.

2022-08-19 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.
sammccall marked 4 inline comments as done.
Closed by commit rGbd5cc6575bdb: [pseudo] Start rules are `_ := start-symbol 
EOF`, improve recovery. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D130550?vs=447580&id=453999#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130550

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/GLR.h
  clang-tools-extra/pseudo/lib/Forest.cpp
  clang-tools-extra/pseudo/lib/GLR.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/lib/grammar/LRGraph.cpp
  clang-tools-extra/pseudo/test/lr-build-basic.test
  clang-tools-extra/pseudo/test/lr-build-conflicts.test
  clang-tools-extra/pseudo/unittests/ForestTest.cpp
  clang-tools-extra/pseudo/unittests/GLRTest.cpp

Index: clang-tools-extra/pseudo/unittests/GLRTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GLRTest.cpp
+++ clang-tools-extra/pseudo/unittests/GLRTest.cpp
@@ -509,7 +509,7 @@
   // item `expr := • IDENTIFIER`, and both have different goto states on the
   // nonterminal `expr`.
   build(R"bnf(
-_ := test
+_ := test EOF
 
 test := { expr
 test := { IDENTIFIER
@@ -548,7 +548,7 @@
   // foo should be reduced first, so that in step 2 we have completed reduces
   // for test, and form an ambiguous forest node.
   build(R"bnf(
-_ := test
+_ := test EOF
 
 test := IDENTIFIER
 test := foo
@@ -575,7 +575,7 @@
   //  - multiple possible recovery rules
   //  - recovery from outer scopes is rejected
   build(R"bnf(
-_ := block
+_ := block EOF
 
 block := { block [recover=Braces] }
 block := { numbers [recover=Braces] }
@@ -606,14 +606,14 @@
 
 TEST_F(GLRTest, RecoverTerminal) {
   build(R"bnf(
-_ := stmt
+_ := stmt EOF
 
 stmt := IDENTIFIER ; [recover=Skip]
   )bnf");
   TestLang.Table = LRTable::buildSLR(TestLang.G);
   TestLang.RecoveryStrategies.try_emplace(
   extensionID("Skip"),
-  [](Token::Index Start, const TokenStream &) { return Start + 1; });
+  [](Token::Index Start, const TokenStream &) { return Start; });
   clang::LangOptions LOptions;
   TokenStream Tokens = cook(lex("foo", LOptions), LOptions);
 
@@ -630,7 +630,7 @@
   // We would not normally reduce `word := IDENTIFIER`, but do so for recovery.
 
   build(R"bnf(
-_ := sentence
+_ := sentence EOF
 
 word := IDENTIFIER
 sentence := word word [recover=AcceptAnyTokenInstead]
@@ -652,9 +652,40 @@
 "[  1, end) └─word := \n");
 }
 
+TEST_F(GLRTest, RepeatedRecovery) {
+  // We require multiple steps of recovery at eof and then a reduction in order
+  // to successfully parse.
+  build(R"bnf(
+_ := function EOF
+# FIXME: this forces EOF to be in follow(signature).
+# Remove it once we use unconstrained reduction for recovery.
+_ := signature EOF
+
+function := signature body [recover=Skip]
+signature := IDENTIFIER params [recover=Skip]
+params := ( )
+body := { }
+  )bnf");
+  TestLang.Table = LRTable::buildSLR(TestLang.G);
+  TestLang.RecoveryStrategies.try_emplace(
+  extensionID("Skip"),
+  [](Token::Index Start, const TokenStream &) { return Start; });
+  clang::LangOptions LOptions;
+  TokenStream Tokens = cook(lex("main", LOptions), LOptions);
+
+  const ForestNode &Parsed =
+  glrParse({Tokens, Arena, GSStack}, id("function"), TestLang);
+  EXPECT_EQ(Parsed.dumpRecursive(TestLang.G),
+"[  0, end) function := signature body [recover=Skip]\n"
+"[  0,   1) ├─signature := IDENTIFIER params [recover=Skip]\n"
+"[  0,   1) │ ├─IDENTIFIER := tok[0]\n"
+"[  1,   1) │ └─params := \n"
+"[  1, end) └─body := \n");
+}
+
 TEST_F(GLRTest, NoExplicitAccept) {
   build(R"bnf(
-_ := test
+_ := test EOF
 
 test := IDENTIFIER test
 test := IDENTIFIER
@@ -677,7 +708,7 @@
 
 TEST_F(GLRTest, GuardExtension) {
   build(R"bnf(
-_ := start
+_ := start EOF
 
 start := IDENTIFIER [guard]
   )bnf");
Index: clang-tools-extra/pseudo/unittests/ForestTest.cpp
===
--- clang-tools-extra/pseudo/unittests/ForestTest.cpp
+++ clang-tools-extra/pseudo/unittests/ForestTest.cpp
@@ -54,7 +54,7 @@
 
 TEST_F(ForestTest, DumpBasic) {
   build(R"cpp(
-_ := add-expression
+_ := add-expression EOF
 add-expression := id-expression + id-expression
 id-expression := IDENTIFIER
   )cpp");
@@ -64,7 +64,7 @@
   cook(lex("a + b", clang::LangOptions()), clang::LangOptions());
 
   auto T = Arena.createTerminals(TS);
-  ASSERT_EQ(T.size(), 3u);
+  ASSERT_EQ(T.size(), 

[PATCH] D132197: [RISCV] Use Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC

2022-08-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Driver/ToolChains/Linux.cpp:741
  getTriple().getArch() == llvm::Triple::thumbeb;
-  const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
+  const bool IsRISCV64 = getTriple().isRISCV64();
   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;

reames wrote:
> I would leave this one unchanged for consistency with surrounding code.  
It’s consistent with MIPS further up, but I can change it back.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132197

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


[clang] dbb95c2 - [clang][dataflow] Debug string for value kinds.

2022-08-19 Thread Wei Yi Tee via cfe-commits

Author: Wei Yi Tee
Date: 2022-08-19T15:00:01Z
New Revision: dbb95c2a851c64e50ca9801a331cb871da88be49

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

LOG: [clang][dataflow] Debug string for value kinds.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
clang/lib/Analysis/FlowSensitive/DebugSupport.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h 
b/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
index b8efdeb61d280..ca50ffc5f5c8a 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
@@ -20,15 +20,19 @@
 #include "clang/Analysis/FlowSensitive/Solver.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 namespace dataflow {
 
+/// Returns a string representation of a value kind.
+llvm::StringRef debugString(Value::Kind Kind);
+
 /// Returns a string representation of a boolean assignment to true or false.
-std::string debugString(Solver::Result::Assignment Assignment);
+llvm::StringRef debugString(Solver::Result::Assignment Assignment);
 
 /// Returns a string representation of the result status of a SAT check.
-std::string debugString(Solver::Result::Status Status);
+llvm::StringRef debugString(Solver::Result::Status Status);
 
 /// Returns a string representation for the boolean value `B`.
 ///

diff  --git a/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp 
b/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
index 714ad08643edb..220617ab9e30d 100644
--- a/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatAdapters.h"
@@ -31,7 +32,33 @@ using llvm::AlignStyle;
 using llvm::fmt_pad;
 using llvm::formatv;
 
-std::string debugString(Solver::Result::Assignment Assignment) {
+llvm::StringRef debugString(Value::Kind Kind) {
+  switch (Kind) {
+  case Value::Kind::Integer:
+return "Integer";
+  case Value::Kind::Reference:
+return "Reference";
+  case Value::Kind::Pointer:
+return "Pointer";
+  case Value::Kind::Struct:
+return "Struct";
+  case Value::Kind::AtomicBool:
+return "AtomicBool";
+  case Value::Kind::Conjunction:
+return "Conjunction";
+  case Value::Kind::Disjunction:
+return "Disjunction";
+  case Value::Kind::Negation:
+return "Negation";
+  case Value::Kind::Implication:
+return "Implication";
+  case Value::Kind::Biconditional:
+return "Biconditional";
+  }
+  llvm_unreachable("Unhandled value kind");
+}
+
+llvm::StringRef debugString(Solver::Result::Assignment Assignment) {
   switch (Assignment) {
   case Solver::Result::Assignment::AssignedFalse:
 return "False";
@@ -41,7 +68,7 @@ std::string debugString(Solver::Result::Assignment 
Assignment) {
   llvm_unreachable("Booleans can only be assigned true/false");
 }
 
-std::string debugString(Solver::Result::Status Status) {
+llvm::StringRef debugString(Solver::Result::Status Status) {
   switch (Status) {
   case Solver::Result::Status::Satisfiable:
 return "Satisfiable";



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


[PATCH] D131891: [clang][dataflow] Debug string for value kinds.

2022-08-19 Thread weiyi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdbb95c2a851c: [clang][dataflow] Debug string for value 
kinds. (authored by wyt).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131891

Files:
  clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
  clang/lib/Analysis/FlowSensitive/DebugSupport.cpp


Index: clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
===
--- clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
+++ clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatAdapters.h"
@@ -31,7 +32,33 @@
 using llvm::fmt_pad;
 using llvm::formatv;
 
-std::string debugString(Solver::Result::Assignment Assignment) {
+llvm::StringRef debugString(Value::Kind Kind) {
+  switch (Kind) {
+  case Value::Kind::Integer:
+return "Integer";
+  case Value::Kind::Reference:
+return "Reference";
+  case Value::Kind::Pointer:
+return "Pointer";
+  case Value::Kind::Struct:
+return "Struct";
+  case Value::Kind::AtomicBool:
+return "AtomicBool";
+  case Value::Kind::Conjunction:
+return "Conjunction";
+  case Value::Kind::Disjunction:
+return "Disjunction";
+  case Value::Kind::Negation:
+return "Negation";
+  case Value::Kind::Implication:
+return "Implication";
+  case Value::Kind::Biconditional:
+return "Biconditional";
+  }
+  llvm_unreachable("Unhandled value kind");
+}
+
+llvm::StringRef debugString(Solver::Result::Assignment Assignment) {
   switch (Assignment) {
   case Solver::Result::Assignment::AssignedFalse:
 return "False";
@@ -41,7 +68,7 @@
   llvm_unreachable("Booleans can only be assigned true/false");
 }
 
-std::string debugString(Solver::Result::Status Status) {
+llvm::StringRef debugString(Solver::Result::Status Status) {
   switch (Status) {
   case Solver::Result::Status::Satisfiable:
 return "Satisfiable";
Index: clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
===
--- clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
+++ clang/include/clang/Analysis/FlowSensitive/DebugSupport.h
@@ -20,15 +20,19 @@
 #include "clang/Analysis/FlowSensitive/Solver.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 namespace dataflow {
 
+/// Returns a string representation of a value kind.
+llvm::StringRef debugString(Value::Kind Kind);
+
 /// Returns a string representation of a boolean assignment to true or false.
-std::string debugString(Solver::Result::Assignment Assignment);
+llvm::StringRef debugString(Solver::Result::Assignment Assignment);
 
 /// Returns a string representation of the result status of a SAT check.
-std::string debugString(Solver::Result::Status Status);
+llvm::StringRef debugString(Solver::Result::Status Status);
 
 /// Returns a string representation for the boolean value `B`.
 ///


Index: clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
===
--- clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
+++ clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormatAdapters.h"
@@ -31,7 +32,33 @@
 using llvm::fmt_pad;
 using llvm::formatv;
 
-std::string debugString(Solver::Result::Assignment Assignment) {
+llvm::StringRef debugString(Value::Kind Kind) {
+  switch (Kind) {
+  case Value::Kind::Integer:
+return "Integer";
+  case Value::Kind::Reference:
+return "Reference";
+  case Value::Kind::Pointer:
+return "Pointer";
+  case Value::Kind::Struct:
+return "Struct";
+  case Value::Kind::AtomicBool:
+return "AtomicBool";
+  case Value::Kind::Conjunction:
+return "Conjunction";
+  case Value::Kind::Disjunction:
+return "Disjunction";
+  case Value::Kind::Negation:
+return "Negation";
+  case Value::Kind::Implication:
+return "Implication";
+  case Value::Kind::Biconditional:
+return "Biconditional";
+  }
+  llvm_unreachable("Unhandled value kind");
+}
+
+llvm::StringRef debugString(Solver::Result::Assignment Assignment) {
   switch (Assignment) {
   case Solver::Result::Assignment::AssignedFalse:
 return "False";
@@ -41,7 +68,7 @@
   llvm_unreachable("Booleans can only be assigned true/false");
 }
 
-std::string debugString(Solver::Result::Status Status) {
+llvm::StringRef debugS

[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

2022-08-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 454009.
steakhal added a comment.

- Use `:digit:` regex matching in the tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

Files:
  clang/include/clang/StaticAnalyzer/Checkers/SValExplainer.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
  clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/ctor.mm
  clang/test/Analysis/expr-inspection.c
  clang/test/Analysis/memory-model.cpp
  clang/test/Analysis/ptr-arith.c
  clang/test/Analysis/ptr-arith.cpp
  clang/test/Analysis/trivial-copy-struct.cpp

Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- /dev/null
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -0,0 +1,36 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -verify %s
+
+template  void clang_analyzer_dump(T);
+void clang_analyzer_warnIfReached();
+
+struct Node { int* ptr; };
+
+void copy_on_stack(Node* n1) {
+  Node tmp = *n1;
+  Node* n2 = &tmp;
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning {{&tmp}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // unreachable
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
+
+void copy_on_heap(Node* n1) {
+  Node* n2 = new Node(*n1);
+
+  clang_analyzer_dump(n1); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}
+  clang_analyzer_dump(n2); // expected-warning-re {{&HeapSymRegion{conj_${{[0-9]+}}{Node *, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}
+
+  clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
+  clang_analyzer_dump(n2->ptr); // expected-warning {{Unknown}} FIXME: This should be the same as above.
+
+  if (n1->ptr != n2->ptr)
+clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} FIXME: This should not be reachable.
+  (void)(n1->ptr);
+  (void)(n2->ptr);
+}
Index: clang/test/Analysis/ptr-arith.cpp
===
--- clang/test/Analysis/ptr-arith.cpp
+++ clang/test/Analysis/ptr-arith.cpp
@@ -134,10 +134,10 @@
 int parse(parse_t *p) {
   unsigned copy = p->bits2;
   clang_analyzer_dump(copy);
-  // expected-warning@-1 {{reg_$1}.bits2>}}
+  // expected-warning@-1 {{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>}}
   header *bits = (header *)©
   clang_analyzer_dump(bits->b);
-  // expected-warning@-1 {{derived_$2{reg_$1}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
+  // expected-warning@-1 {{derived_$2{reg_$1},0 S64b,struct Bug_55934::parse_t}.bits2>,Element{copy,0 S64b,struct Bug_55934::header}.b}}}
   return bits->b; // no-warning
 }
 } // namespace Bug_55934
Index: clang/test/Analysis/ptr-arith.c
===
--- clang/test/Analysis/ptr-arith.c
+++ clang/test/Analysis/ptr-arith.c
@@ -340,11 +340,11 @@
 void struct_pointer_canon(struct s *ps) {
   struct s ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_eval((*ps).v == ps[0].v); // expected-warning{{TRUE}}
   clang_analyzer_eval((*ps).v == ps->v);   // expected-warning{{TRUE}}
   clang_analyzer_eval(ps[0].v == ps->v);   // expected-warning{{TRUE}}
@@ -360,11 +360,11 @@
 void struct_pointer_canon_typedef(T1 *ps) {
   T2 ss = *ps;
   clang_analyzer_dump((*ps).v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps[0].v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_dump(ps->v);
-  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}}.v>}}
+  // expected-warning-re@-1{{reg_${{[[:digit:]]+}}},0 S64b,struct s}.v>}}
   clang_analyzer_eval((*ps).v == ps[0].v); // expected-warning{{TRUE}}
 

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

2022-08-19 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam marked 3 inline comments as done.
zahiraam added a comment.






Comment at: clang/test/CodeGen/X86/Float16-complex.c:1184
+// X86-NEXT:store float [[NEG_I]], ptr [[RETVAL_IMAGP]], align 2
+// X86-NEXT:[[TMP0:%.*]] = load <2 x half>, ptr [[RETVAL]], align 2
+// X86-NEXT:ret <2 x half> [[TMP0]]

rjmccall wrote:
> This code pattern is definitely wrong, and it's a sign that the expression 
> evaluator returned the wrong type.  This is coercing a `_Complex float` into 
> a `_Complex _Float16` through memory, which is essentially reinterpreting the 
> first float as a pair of `_Float16`s.  You should go through your tests and 
> make sure you don't see other instances of this.
I think the issue here is that in ComplexExprEmitter::EmitStoreOfComplex, we 
are computing the Ptr from lvalue which elementype is halfty instead of float. 
I think the code there needs to change when there is a getPromotionType. We 
need to compute a Ptr with float as elementype .
The Val argument returned by the complex emitter has the right type (Float). 



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

https://reviews.llvm.org/D113107

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


[PATCH] D132111: [clang][Interp] Implement pointer (de)ref operations and DeclRefExprs

2022-08-19 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:613-614
   case UO_LNot: // !x
+if (!this->Visit(SubExpr))
+  return false;
 return this->emitInvBool(E);

I don't love that the `Visit()` calls are now repeated for most of the 
operations, but I don't have a better suggestion. I see that `Visit()` must not 
be called for ``UO_Deref` since `dereference()` will perform the visitation. I 
guess that case could be pulled out of the switch, but that isn't necessarily 
better. Consider this an unactionable comment.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:662
+  return this->emitGetPtrParam(It->second, E);
+  }
+

Perhaps add:
  else {
assert(0 && "Unhandled declaration kind");
  }



Comment at: clang/test/AST/Interp/cxx20.cpp:2
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++20 -verify 
%s
+// RUN: %clang_cc1 -std=c++20 -verify %s -DREFERENCE
+

Is `-DREFERENCE` needed here? I don't see `REFERENCE` referenced in the test. 
From the other test, I gather that it is intended to annotate differences from 
the "reference" implementation.



Comment at: clang/test/AST/Interp/cxx20.cpp:11
+  return *p;
+}
+

Perhaps add:
  //static_assert(getMinux5() == -5, "");  TODO



Comment at: clang/test/AST/Interp/literals.cpp:43
+  return &m;
+}
+

Perhaps add:
  //static_assert(*getIntPointer() == 10, ""); TODO



Comment at: clang/test/AST/Interp/literals.cpp:47
+  return k;
+}

Perhaps add:
  //static_assert(gimme(5) == 5, ""); TODO


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

https://reviews.llvm.org/D132111

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


[PATCH] D132142: [analyzer] Prefer wrapping SymbolicRegions by ElementRegions

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:791-793
+  /// TODO: Ellaborate why this is not a typed region, and why this is just an
+  /// 'approximation'.
+  QualType getApproximatedType() const {

I'm not sure how much explanation I need to do here, but first, we should 
settle on the name of this member function if we decide to have it.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h:796-800
+// FIXME: 1) Shouldn't this branch always taken due to the assertions in 
the
+// ctor?
+// FIXME: 2) Shouldn't we also handle if T is a block pointer?
+if (T->isAnyPointerType() || T->isReferenceType())
+  T = T->getPointeeType();

I guess, these two questions together form the answer. The ctor only asserts 
that it is either a //any pointer//, //reference// *or* a //block pointer//. 
However, I'd like to get this confirmed. @NoQ 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132142

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


[PATCH] D132143: [analyzer] LazyCompoundVals should be always bound as default bindings

2022-08-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 454010.
steakhal added a comment.

- Rebase for using `:digit:` regex matching in the tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132143

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/trivial-copy-struct.cpp


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -27,10 +27,10 @@
   clang_analyzer_dump(n2); // expected-warning-re 
{{&HeapSymRegion{conj_${{[0-9]+}}{Node *, LC{{[0-9]+}}, S{{[0-9]+}}, 
#{{[0-9]+}}
 
   clang_analyzer_dump(n1->ptr); // expected-warning-re 
{{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
-  clang_analyzer_dump(n2->ptr); // expected-warning {{Unknown}} FIXME: This 
should be the same as above.
+  clang_analyzer_dump(n2->ptr); // expected-warning-re 
{{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
 
   if (n1->ptr != n2->ptr)
-clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} FIXME: 
This should not be reachable.
+clang_analyzer_warnIfReached(); // unreachable
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2400,7 +2400,11 @@
 
   // Clear out bindings that may overlap with this binding.
   RegionBindingsRef NewB = removeSubRegionBindings(B, cast(R));
-  return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
+
+  // LazyCompoundVals should be always bound as 'default' bindings.
+  auto KeyKind = isa(V) ? BindingKey::Default
+ : BindingKey::Direct;
+  return NewB.addBinding(BindingKey::Make(R, KeyKind), V);
 }
 
 RegionBindingsRef


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -27,10 +27,10 @@
   clang_analyzer_dump(n2); // expected-warning-re {{&HeapSymRegion{conj_${{[0-9]+}}{Node *, LC{{[0-9]+}}, S{{[0-9]+}}, #{{[0-9]+}}
 
   clang_analyzer_dump(n1->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
-  clang_analyzer_dump(n2->ptr); // expected-warning {{Unknown}} FIXME: This should be the same as above.
+  clang_analyzer_dump(n2->ptr); // expected-warning-re {{&SymRegion{reg_${{[0-9]+}}},0 S64b,struct Node}.ptr>}}}
 
   if (n1->ptr != n2->ptr)
-clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}} FIXME: This should not be reachable.
+clang_analyzer_warnIfReached(); // unreachable
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2400,7 +2400,11 @@
 
   // Clear out bindings that may overlap with this binding.
   RegionBindingsRef NewB = removeSubRegionBindings(B, cast(R));
-  return NewB.addBinding(BindingKey::Make(R, BindingKey::Direct), V);
+
+  // LazyCompoundVals should be always bound as 'default' bindings.
+  auto KeyKind = isa(V) ? BindingKey::Default
+ : BindingKey::Direct;
+  return NewB.addBinding(BindingKey::Make(R, KeyKind), V);
 }
 
 RegionBindingsRef
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D131388: [docs] Add "C++20 Modules"

2022-08-19 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 454012.
ChuanqiXu marked an inline comment as done.
ChuanqiXu added a comment.

Address comments.


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

https://reviews.llvm.org/D131388

Files:
  clang/docs/CPlusPlus20Modules.rst
  clang/docs/index.rst

Index: clang/docs/index.rst
===
--- clang/docs/index.rst
+++ clang/docs/index.rst
@@ -40,6 +40,7 @@
SafeStack
ShadowCallStack
SourceBasedCodeCoverage
+   CPlusPlus20Modules
Modules
MSVCCompatibility
MisExpect
Index: clang/docs/CPlusPlus20Modules.rst
===
--- /dev/null
+++ clang/docs/CPlusPlus20Modules.rst
@@ -0,0 +1,823 @@
+=
+C++20 Modules
+=
+
+.. contents::
+   :local:
+
+Introduction
+
+
+The term ``modules`` has a lot of meanings. For the users of Clang, modules may
+refer to ``Objective-C Modules``, ``Clang C++ Modules`` (or ``Clang Header Modules``,
+etc.) or C++20 modules. The implementation of all these kinds of modules in Clang 
+has a lot of shared code, but from the perspective of users, their semantics and
+command line interfaces are very different. This document focuses on
+an introduction of how to use C++20 modules in Clang.
+
+There is already a detailed document about `Clang modules `_, it
+should be helpful to read `Clang modules `_ if you want to know
+more about the general idea of modules. Since C++20 modules have different semantics
+(and work flows) from `Clang modules`, this page describes the background and use of
+Clang with C++20 modules
+
+Although the term ``modules`` has a unique meaning in C++20 Language Specification,
+when people talk about C++20 modules, they may refer to another C++20 feature:
+header units, which are also covered in this document.
+
+C++20 Modules
+=
+
+This document was intended to be a manual first and foremost, however, we consider it helpful to
+introduce some language background here for readers who are not familiar with
+the new language feature. This document is not intended to be a language
+tutorial; it will only introduce necessary concepts about the
+structure and building of the project.
+
+Background and terminology
+--
+
+Modules
+~~~
+
+In this document, the term ``Modules``/``modules`` refers to C++20 modules
+feature if it is not decorated by ``Clang``.
+
+Clang Modules
+~
+
+In this document, the term ``Clang Modules``/``Clang modules`` refer to Clang
+c++ modules extension. These are also known as ``Clang header modules``,
+``Clang module map modules`` or ``Clang c++ modules``.
+
+Module and module unit
+~~
+
+A module consists of one or more module units. A module unit is a special
+translation unit. Every module unit must have a module declaration. The syntax
+of the module declaration is:
+
+.. code-block:: c++
+
+  [export] module module_name[:partition_name];
+
+Terms enclosed in ``[]`` are optional. The syntax of ``module_name`` and ``partition_name``
+in regex form corresponds to ``[a-zA-Z_][a-zA-Z_0-9\.]*``. In particular, a literal dot ``.``
+in the name has no semantic meaning (e.g. implying a hierarchy).
+
+In this document, module units are classified into:
+
+* Primary module interface unit.
+
+* Module implementation unit.
+
+* Module interface partition unit.
+
+* Internal module partition unit.
+
+A primary module interface unit is a module unit whose module declaration is
+``export module module_name;``. The ``module_name`` here denotes the name of the
+module. A module should have one and only one primary module interface unit.
+
+A module implementation unit is a module unit whose module declaration is
+``module module_name;``. A module could have multiple module implementation
+units with the same declaration.
+
+A module interface partition unit is a module unit whose module declaration is
+``export module module_name:partition_name;``. The ``partition_name`` should be
+unique to the module.
+
+A internal module partition unit is a module unit whose module declaration
+is ``module module_name:partition_name;``. The ``partition_name`` should be
+unique to the module.
+
+In this document, we use the following umbrella terms:
+
+* A ``module interface unit`` refers to either a ``primary module interface unit``
+  or a ``module interface partition unit``.
+
+* An ``importable module unit`` refers to either a ``module interface unit``
+  or a ``internal module partition unit``.
+
+* A ``module partition unit`` refers to either a ``module interface partition unit``
+  or a ``internal module partition unit``.
+
+Built Module Interface file
+~~~
+
+A ``Built Module Interface file`` stands for the precompiled result of an importable module unit.
+It is also called the acronym ``BMI`` genrally.
+
+Global module fragment
+~~

[PATCH] D132236: [analyzer] Fix liveness of LazyCompoundVals

2022-08-19 Thread Balázs Benics via Phabricator via cfe-commits
steakhal created this revision.
steakhal added reviewers: NoQ, xazax.hun, martong, ASDenysPetrov, Szelethus, 
isuckatcs, vabridgers.
Herald added subscribers: manas, dkrupp, donat.nagy, mikhail.ramalho, 
a.sidorin, rnkovacs, szepet, baloghadamsoftware.
Herald added a project: All.
steakhal requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The `SymbolReaper` should consider a region //live// if that appears in
the store bindings anywhere - even if the region is wrapped by
`RegionSymbolVals`, `SymbolicRegions` or `LazyCompoundVals`.

This mistake by the `SymbolReaper` materialized in false-positives like
in the following example:

  void ptr1(List* n) {
List* n2 = new List(*n); // cctor
if (!n->next) {
  if (n2->next) {
clang_analyzer_warnIfReached(); // FP! This should be unreachable.
  }
}
delete n2;
  }

The store entry of the pointee of `n2` looks something like this:

  HeapSymRegion{conj_$1{List *, LC1, S2540, #1}}  0(Default)  
lazyCompoundVal{0x5641f1ed8830,Element{SymRegion{reg_$2},0 
S64b,struct List}}

So, any constraints referring to the `VarRegion` `n` supposed to be kept alive 
by that store binding.
Hence, the analyzer should be able to see that `reg_$3},0 S64b,struct List}.next> { [0, 0] }` when 
it reaches the `n2->next`.

This patch fixes the issue by reusing the `SymbolReaper::markLive(MemRegion)` 
for doing the appropriate traversal.

I'm yet to do the performance testing, given that this is actually in
the hot path.

Co-authored-by: Tomasz Kamiński 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132236

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/trivial-copy-struct.cpp


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -34,3 +34,28 @@
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
+
+struct List {
+  List* next;
+};
+
+void ptr1(List* n) {
+  List* n2 = new List(*n); // cctor
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
+
+void ptr2(List* n) {
+  List* n2 = new List(); // ctor
+  *n2 = *n; // assignment
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2829,22 +2829,14 @@
 }
 
 void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
-  // Is it a LazyCompoundVal?  All referenced regions are live as well.
-  if (Optional LCS =
-  V.getAs()) {
-
-const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
-
-for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
-E = Vals.end();
- I != E; ++I)
-  VisitBinding(*I);
+  const MemRegion *R = V.getAsRegion();
 
-return;
-  }
+  // Is it a LazyCompoundVal?  All referenced regions are live as well.
+  if (auto LCS = V.getAs())
+R = LCS->getRegion();
 
   // If V is a region, then add it to the worklist.
-  if (const MemRegion *R = V.getAsRegion()) {
+  if (R) {
 AddToWorkList(R);
 SymReaper.markLive(R);
 


Index: clang/test/Analysis/trivial-copy-struct.cpp
===
--- clang/test/Analysis/trivial-copy-struct.cpp
+++ clang/test/Analysis/trivial-copy-struct.cpp
@@ -34,3 +34,28 @@
   (void)(n1->ptr);
   (void)(n2->ptr);
 }
+
+struct List {
+  List* next;
+};
+
+void ptr1(List* n) {
+  List* n2 = new List(*n); // cctor
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
+
+void ptr2(List* n) {
+  List* n2 = new List(); // ctor
+  *n2 = *n; // assignment
+  if (!n->next) {
+if (n2->next) {
+  clang_analyzer_warnIfReached(); // unreachable
+}
+  }
+  delete n2;
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -2829,22 +2829,14 @@
 }
 
 void RemoveDeadBindingsWorker::VisitBinding(SVal V) {
-  // Is it a LazyCompoundVal?  All referenced regions are live as well.
-  if (Optional LCS =
-  V.getAs()) {
-
-const RegionStoreManager::SValListTy &Vals = RM.getInterestingValues(*LCS);
-
-for (RegionStoreManager::SValListTy::const_iterator I = Vals.begin(),
-E = Vals.end();
- I != E; ++I)
-  VisitBinding(*I);
+  const MemRegion *R = V.getAsRegion();
 
-return;
-  }

[PATCH] D131388: [docs] Add "C++20 Modules"

2022-08-19 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/docs/CPlusPlus20Modules.rst:457
+
+The declarations in a module unit which are not in global module fragment have 
new linkage names.
+

JohelEGP wrote:
> 
Thanks for reviewing. BTW, the `request to change` button is fair to use. But 
it scares me a little with typo comments..


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

https://reviews.llvm.org/D131388

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


[PATCH] D126818: Itanium ABI: Implement mangling for constrained friends

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

In D126818#3563376 , @erichkeane 
wrote:

> In D126818#3562355 , @tahonermann 
> wrote:
>
>>> Note we might be confused, the parens there aren't completely clear as to 
>>> what your intent is.
>>
>> Well, I know that I'm confused and not clear what my intent is :)
>>
>> I asked the question because there appears to be an asymmetry between 
>> (temp.friend)p9 sentence 1  
>> and (temp.friend)p9 sentence 2 
>> . Sentence 1 applies to all 
>> constrained non-template friend declarations regardless of any template 
>> argument dependence while sentence 2 applies to just a subset of constrained 
>> friend function templates; those that have some amount of template 
>> dependence. The difference impacts when mangling differences are required.
>>
>> I spent some time analyzing how gcc, clang, and MSVC handle these different 
>> cases. See https://godbolt.org/z/85E5eMh3x. Search for FIXME? to find cases 
>> where I think one or more of the compilers is misbehaving or where it is 
>> unclear to me whether or how [temp.friend]p9 applies. Some highlights:
>>
>> - Some compilers diagnose some ill-formed cases when parsing the class 
>> template, others don't until the class template is instantiated. Not 
>> surprising.
>> - All of the compilers reject non-template friend function definitions with 
>> non-dependent constraints due to duplicate definitions, presumably in 
>> violation of [temp.friend]p9; see the `ff2()` example.
>> - All of the compilers reject non-template friend function definitions with 
>> dependent constraints due to duplicate definitions, presumably in violation 
>> of [temp.friend]p9; see the `ff6()` example.
>> - Name mangling is currently insufficient to differentiate (otherwise) 
>> non-dependent friend function templates with dependent constraints; see the 
>> `fft5()` and `fft6()` examples.
>> - None of the compilers reject some cases of non-definitions that should be 
>> rejected by [temp.friend]p9; see the `fft5()` and `fft7()` examples.
>
> Yes, I understand that Clang doesn't currently properly implement 
> [temp.friend]p9, and it is my belief too that none of the other compilers get 
> it right at the moment either.  Clang approximates it by just directly 
> comparing partially instantiated constraints, so it gets it MOSTLY right.
>
> I believe I have all of your test cases in my implementation of 
> [temp.friend]p9 as a part of the deferred concepts patch here: 
> https://reviews.llvm.org/D126907
>
> Aaron, my, and at least 1 other core expert's reading was:
>
> -A non template friend declaration with a requires-clause shall be a 
> definition.
>
>   >> That is, ALL non-template friends, no matter what the requires-clause 
> depends on.
>
> -A friend function template with a constraint that depends on the template 
> parameter from an enclosing template shall be a definition.
>
>   >> That is, when the declaration is a friend function template, it must be 
> a definition ONLY IF it depends on a template param from an enclosing 
> template.
>
> THOSE two sentences aren't particularly relevant, except for setting up the 
> two groups (that is, ALL constrained non-template friends and constrained 
> friend function templates where the constraint depends on an enclosing 
> template).
>
> The third sentence is the valuable one to both of these:
>
> -Such a constrained friend function or function template declaration does not 
> declare the same function or function template as a declaration in any other 
> scope.
>
>   >> That is, any friend in either of those two groups from sentence 1 and 
> sentence 2 do not conflict with the same lexical declaration in a different 
> instantiation.
>
> THIS patch attempts to implement the mangling required in that last sentence, 
> however it doesn't differentiate the "ONLY if it depends on a template param 
> from an enclosing template", which I intend to fix in a future revision, once 
> the infrastructure from my deferred concepts patch (see link above) has made 
> it into the repo.

SO I believe my 'future revision' part in the above is actually no longer 
necessary.  We prohibit that with a Sema 'redefinition error': 
https://godbolt.org/z/1r549vfK4

So the question here is whether we want 'baz' in that godbolt link to use the 
'F' mangling or not.  @rjmccall?  The 'easiest' thing to do I think (based on 
this patch) is to ALWAYS use the 'F' mangling for a friend with a constraint.

WDYT?


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

https://reviews.llvm.org/D126818

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


[PATCH] D131625: [HLSL] Entry functions require param annotation

2022-08-19 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/include/clang/AST/Attr.h:193
 
+class HLSLAnnotationAttr : public InheritableAttr {
+protected:

aaron.ballman wrote:
> Is this intended to be used only for parameters (that's how I read the 
> summary for the patch)? If so, why is this not inheriting from 
> `InheritableParamAttr`?
Sadly these attributes are valid in places that aren’t parameters. For example, 
they can be applied on the members of a struct. When specifying an HLSL entry 
we require semantics for all scalar variables in the signature so that the we 
can match up the parameters from driver and user-provided values, but the 
parameters can be scalars or user defined structs. For example:

```
struct Pupper {
  int Legs : SomeAnnotation;
  int Ears : SomeOtherAnnotation;
}
...
void main(Pupper P) {...} // valid as an entry
```

We also allow these annotations (and require them) on return types for entry 
functions:

```
int main(...) : SomeAnnotation {...}
```

Where this all gets really special is that entry functions as passed to drivers 
have a `void(void)` signature, but entry functions with the source-specified 
signature can be called.

I'm trying to handle those cases in D131203 by generating the user-written 
function as is with C++ mangling, and generating a non-mangled `void(void)` 
wrapper that calls the underlying function after populating the annotation 
values. It is an incomplete implementation, but a starting point.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:11635
 def err_hlsl_attribute_param_mismatch : Error<"%0 attribute parameters do not 
match the previous declaration">;
+def err_hlsl_missing_parameter_annotation : Error<"entry function parameter %0 
missing annotation">;
 

aaron.ballman wrote:
> Will users know how to fix the issue when they get this diagnostic? "missing 
> annotation" sounds like "slap any old annotation on there, it'll be fine".
I should probably make this closer to our existing diagnostic: "Semantic must 
be defined for all parameters of an entry function or patch constant function."


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131625

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


[PATCH] D132241: [clang][dataflow] Dummy patch 1

2022-08-19 Thread Sam Estep via Phabricator via cfe-commits
samestep created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
samestep 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/D132241

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


Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -36,6 +36,8 @@
 public:
   virtual ~StmtToEnvMap() = default;
 
+  // hello
+
   /// Returns the environment of the basic block that contains `S` or nullptr 
if
   /// there isn't one.
   /// FIXME: Ensure that the result can't be null and return a const reference.


Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -36,6 +36,8 @@
 public:
   virtual ~StmtToEnvMap() = default;
 
+  // hello
+
   /// Returns the environment of the basic block that contains `S` or nullptr if
   /// there isn't one.
   /// FIXME: Ensure that the result can't be null and return a const reference.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132242: [clang][dataflow] Dummy patch 2

2022-08-19 Thread Sam Estep via Phabricator via cfe-commits
samestep created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
samestep requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Depends On D132241 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132242

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


Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -37,6 +37,7 @@
   virtual ~StmtToEnvMap() = default;
 
   // hello
+  // goodbye
 
   /// Returns the environment of the basic block that contains `S` or nullptr 
if
   /// there isn't one.


Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -37,6 +37,7 @@
   virtual ~StmtToEnvMap() = default;
 
   // hello
+  // goodbye
 
   /// Returns the environment of the basic block that contains `S` or nullptr if
   /// there isn't one.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


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

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

- Use `Optional` for `EofInitialized`
- Split tests into two files with and without note check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132017

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

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

[PATCH] D132244: [docs] improve documentation for misc-const-correctness

2022-08-19 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth created this revision.
JonasToth added reviewers: njames93, aaron.ballman, alexfh, hokein, sammccall.
Herald added a project: All.
JonasToth requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Improve the documentation for 'misc-const-correctness' to include better 
examples.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132244

Files:
  clang-tools-extra/docs/clang-tidy/checks/misc/const-correctness.rst

Index: clang-tools-extra/docs/clang-tidy/checks/misc/const-correctness.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/misc/const-correctness.rst
+++ clang-tools-extra/docs/clang-tidy/checks/misc/const-correctness.rst
@@ -4,12 +4,12 @@
 ==
 
 This check implements detection of local variables which could be declared as
-``const``, but are not. Declaring variables as ``const`` is required or recommended by many
+``const`` but are not. Declaring variables as ``const`` is required or recommended by many
 coding guidelines, such as:
 `CppCoreGuidelines ES.25 `_
 and `AUTOSAR C++14 Rule A7-1-1 (6.7.1 Specifiers) `_.
 
-Please note that this analysis is type-based only. Variables that are not modified
+Please note that this check's analysis is type-based only. Variables that are not modified
 but used to create a non-const handle that might escape the scope are not diagnosed
 as potential ``const``.
 
@@ -18,33 +18,37 @@
   // Declare a variable, which is not ``const`` ...
   int i = 42;
   // but use it as read-only. This means that `i` can be declared ``const``.
-  int result = i * i;
+  int result = i * i;   // Before transformation
+  int const result = i * i; // After transformation
 
-The check can analyzes values, pointers and references but not (yet) pointees:
+The check can analyze values, pointers and references but not (yet) pointees:
 
 .. code-block:: c++
 
   // Normal values like built-ins or objects.
-  int potential_const_int = 42; // 'const int potential_const_int = 42' suggestion.
+  int potential_const_int = 42;   // Before transformation
+  int const potential_const_int = 42; // After transformation
   int copy_of_value = potential_const_int;
 
-  MyClass could_be_const; // 'const MyClass could_be_const' suggestion;
+  MyClass could_be_const;   // Before transformation
+  MyClass const could_be_const; // After transformation
   could_be_const.const_qualified_method();
 
   // References can be declared const as well.
-  int &reference_value = potential_const_int; // 'const int &reference_value' suggestion.
+  int &reference_value = potential_const_int;   // Before transformation
+  int const& reference_value = potential_const_int; // After transformation
   int another_copy = reference_value;
 
   // The similar semantics of pointers are not (yet) analyzed.
-  int *pointer_variable = &potential_const_int; // Not 'const int *pointer_variable' suggestion.
+  int *pointer_variable = &potential_const_int; // _NO_ 'const int *pointer_variable' suggestion.
   int last_copy = *pointer_variable;
 
 The automatic code transformation is only applied to variables that are declared in single
 declarations. You may want to prepare your code base with
-`readability-isolate-declaration `_ first.
+`readability-isolate-declaration <../readability/isolate-declaration.html>`_ first.
 
 Note that there is the check
-`cppcoreguidelines-avoid-non-const-global-variables `_
+`cppcoreguidelines-avoid-non-const-global-variables <../cppcoreguidelines/avoid-non-const-global-variables.html>`_
 to enforce ``const`` correctness on all globals.
 
 Known Limitations
@@ -52,10 +56,10 @@
 
 The check will not analyze templated variables or variables that are instantiation dependent.
 Different instantiations can result in different ``const`` correctness properties and in general it
-is not possible to find all instantiations of a template. It might be used differently in an
-independent translation unit.
+is not possible to find all instantiations of a template. The template might be used differently in
+an independent translation unit.
 
-Pointees can not be analyzed for constness yet. The following code is shows this limitation.
+Pointees can not be analyzed for constness yet. The following code shows this limitation.
 
 .. code-block:: c++
 
@@ -74,15 +78,35 @@
 Options
 ---
 
-.. option:: AnalyzeValues (default = 1)
+.. option:: AnalyzeValues (default = true)
 
   Enable or disable the analysis of ordinary value variables, like ``int i = 42;``
 
-.. option:: AnalyzeReferences (default = 1)
+  .. code-block:: c++
+
+// Warning
+int i = 42;
+// 

[PATCH] D129608: [Clang][OpenMP] Fix segmentation fault when data field is used in is_device_pt.

2022-08-19 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 added a comment.

Hi @alexfh,

How could I reproduce the problem?  Thanks.
Thanks.

Jennifer


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129608

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


[PATCH] D130793: [clang-tidy] adjust treating of array-of-pointers when 'AnalyzePointers' is deactivated

2022-08-19 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 454031.
JonasToth marked an inline comment as done.
JonasToth added a comment.

- split patch
- remove unnecessary includes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130793

Files:
  clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.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-values.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
@@ -526,18 +526,15 @@
   // CHECK-FIXES: int const p_local1[2]
   for (const int &const_ref : p_local1) {
   }
+}
 
-  int *p_local2[2] = {&np_local0[0], &np_local0[1]};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int *[2]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local2[2]
-  for (const int *con_ptr : p_local2) {
-  }
-
-  int *p_local3[2] = {nullptr, nullptr};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local3' of type 'int *[2]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local3[2]
-  for (const auto *con_ptr : p_local3) {
-  }
+void arrays_of_pointers_are_ignored() {
+  int *np_local0[2] = {nullptr, nullptr};
+  // CHECK-NOT-FIXES: int * const np_local0[2]
+  
+  using intPtr = int*;
+  intPtr np_local1[2] = {nullptr, nullptr};
+  // CHECK-NOT-FIXES: intPtr const np_local1[2]
 }
 
 inline void *operator new(decltype(sizeof(void *)), void *p) { return p; }
@@ -908,41 +905,6 @@
   sizeof(int[++N]);
 }
 
-template 
-struct SmallVectorBase {
-  T data[4];
-  void push_back(const T &el) {}
-  int size() const { return 4; }
-  T *begin() { return data; }
-  const T *begin() const { return data; }
-  T *end() { return data + 4; }
-  const T *end() const { return data + 4; }
-};
-
-template 
-struct SmallVector : SmallVectorBase {};
-
-template 
-void EmitProtocolMethodList(T &&Methods) {
-  // Note: If the template is uninstantiated the analysis does not figure out,
-  // that p_local0 could be const. Not sure why, but probably bails because
-  // some expressions are type-dependent.
-  SmallVector p_local0;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'SmallVector' can be declared 'const'
-  // CHECK-FIXES: SmallVector const p_local0
-  SmallVector np_local0;
-  for (const auto *I : Methods) {
-if (I == nullptr)
-  np_local0.push_back(I);
-  }
-  p_local0.size();
-}
-void instantiate() {
-  int *p_local0[4] = {nullptr, nullptr, nullptr, nullptr};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int *[4]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local0[4]
-  EmitProtocolMethodList(p_local0);
-}
 struct base {
   int member;
 };
Index: clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-values.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-pointer-as-values.cpp
@@ -10,4 +10,65 @@
   double *p_local0 = &np_local0[1];
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'double *' can be declared 'const'
   // CHECK-FIXES: double *const p_local0
+
+  using doublePtr = double*;
+  using doubleArray = double[15];
+  doubleArray np_local1;
+  doublePtr p_local1 = &np_local1[0];
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'doublePtr' (aka 'double *') can be declared 'const'
+  // CHECK-FIXES: doublePtr const p_local1
+}
+
+void range_for() {
+  int np_local0[2] = {1, 2};
+  int *p_local0[2] = {&np_local0[0], &np_local0[1]};
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int *[2]' can be declared 'const'
+  // CHECK-FIXES: int *const p_local0[2]
+  for (const int *p_local1 : p_local0) {
+  // CHECK-MESSAGES: [[@LINE-1]]:8: warning: variable 'p_local1' of type 'const int *' can be declared 'const'
+  // CHECK-FIXES: for (const int *const p_local1 : p_local0)
+  }
+
+  int *p_local2[2] = {nullptr, nullptr};
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int *[2]' can be declared 'const'
+  // CHECK-FIXES: int *const p_local2[2]
+  for (const auto *con_ptr : p_local2) {
+  }
+
+}
+
+template 
+struct SmallVectorBase {
+  T data[4];
+  void push_back(const T &el) {}
+  int size() const { return 4; }
+  T *begin() { return data; }
+  const T *begin() const { return data; }
+  T *end() { return data + 4; }
+  const T *end() const { return data + 4; }
+};
+
+

[PATCH] D130788: [clang-repl] Disable building when LLVM_STATIC_LINK_CXX_STDLIB is ON.

2022-08-19 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 added a comment.

https://chromium-review.googlesource.com/c/emscripten-releases/+/3842345... 
I suppose the alternative would be to keep the backup method that was 
previously working in our case (but not in yours)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130788

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


[PATCH] D130793: [clang-tidy] adjust treating of array-of-pointers when 'AnalyzePointers' is deactivated

2022-08-19 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 454032.
JonasToth added a comment.

- remove bad change from diff


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130793

Files:
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.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-values.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
@@ -526,18 +526,15 @@
   // CHECK-FIXES: int const p_local1[2]
   for (const int &const_ref : p_local1) {
   }
+}
 
-  int *p_local2[2] = {&np_local0[0], &np_local0[1]};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int *[2]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local2[2]
-  for (const int *con_ptr : p_local2) {
-  }
-
-  int *p_local3[2] = {nullptr, nullptr};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local3' of type 'int *[2]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local3[2]
-  for (const auto *con_ptr : p_local3) {
-  }
+void arrays_of_pointers_are_ignored() {
+  int *np_local0[2] = {nullptr, nullptr};
+  // CHECK-NOT-FIXES: int * const np_local0[2]
+  
+  using intPtr = int*;
+  intPtr np_local1[2] = {nullptr, nullptr};
+  // CHECK-NOT-FIXES: intPtr const np_local1[2]
 }
 
 inline void *operator new(decltype(sizeof(void *)), void *p) { return p; }
@@ -908,41 +905,6 @@
   sizeof(int[++N]);
 }
 
-template 
-struct SmallVectorBase {
-  T data[4];
-  void push_back(const T &el) {}
-  int size() const { return 4; }
-  T *begin() { return data; }
-  const T *begin() const { return data; }
-  T *end() { return data + 4; }
-  const T *end() const { return data + 4; }
-};
-
-template 
-struct SmallVector : SmallVectorBase {};
-
-template 
-void EmitProtocolMethodList(T &&Methods) {
-  // Note: If the template is uninstantiated the analysis does not figure out,
-  // that p_local0 could be const. Not sure why, but probably bails because
-  // some expressions are type-dependent.
-  SmallVector p_local0;
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'SmallVector' can be declared 'const'
-  // CHECK-FIXES: SmallVector const p_local0
-  SmallVector np_local0;
-  for (const auto *I : Methods) {
-if (I == nullptr)
-  np_local0.push_back(I);
-  }
-  p_local0.size();
-}
-void instantiate() {
-  int *p_local0[4] = {nullptr, nullptr, nullptr, nullptr};
-  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int *[4]' can be declared 'const'
-  // CHECK-FIXES: int *const p_local0[4]
-  EmitProtocolMethodList(p_local0);
-}
 struct base {
   int member;
 };
Index: clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-values.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-pointer-as-values.cpp
@@ -10,4 +10,65 @@
   double *p_local0 = &np_local0[1];
   // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'double *' can be declared 'const'
   // CHECK-FIXES: double *const p_local0
+
+  using doublePtr = double*;
+  using doubleArray = double[15];
+  doubleArray np_local1;
+  doublePtr p_local1 = &np_local1[0];
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local1' of type 'doublePtr' (aka 'double *') can be declared 'const'
+  // CHECK-FIXES: doublePtr const p_local1
+}
+
+void range_for() {
+  int np_local0[2] = {1, 2};
+  int *p_local0[2] = {&np_local0[0], &np_local0[1]};
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local0' of type 'int *[2]' can be declared 'const'
+  // CHECK-FIXES: int *const p_local0[2]
+  for (const int *p_local1 : p_local0) {
+  // CHECK-MESSAGES: [[@LINE-1]]:8: warning: variable 'p_local1' of type 'const int *' can be declared 'const'
+  // CHECK-FIXES: for (const int *const p_local1 : p_local0)
+  }
+
+  int *p_local2[2] = {nullptr, nullptr};
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: variable 'p_local2' of type 'int *[2]' can be declared 'const'
+  // CHECK-FIXES: int *const p_local2[2]
+  for (const auto *con_ptr : p_local2) {
+  }
+
+}
+
+template 
+struct SmallVectorBase {
+  T data[4];
+  void push_back(const T &el) {}
+  int size() const { return 4; }
+  T *begin() { return data; }
+  const T *begin() const { return data; }
+  T *end() { return data + 4; }
+  const T *end() const { return data + 4; }
+};
+
+template 
+struct SmallVector : SmallVectorBase {};
+
+template 
+void EmitProtocolMethodList(T &&Methods) {
+  // Note: 

[PATCH] D131799: [HLSL] clang codeGen for HLSLNumThreadsAttr

2022-08-19 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:103
+   << NumThreadsAttr->getZ();
+OS.flush();
+F->addFnAttr(NumThreadsKindStr, NumThreadsStr);

You can replace this whole chunk of code with:
```
std::string NumThreadsStr = llvm::formatv("{0},{1},{2}", 
NumThreadsAttr->getX(), NumThreadsAttr->getY(), NumThreadsAttr->getZ()).str();
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131799

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


[PATCH] D132247: [clang] Fix emitVoidPtrVAArg for non-zero default alloca address space

2022-08-19 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 created this revision.
jrtc27 added a reviewer: arsenm.
Herald added subscribers: kosarev, tpr.
Herald added a project: All.
jrtc27 requested review of this revision.
Herald added subscribers: cfe-commits, wdng.
Herald added a project: clang.

Indirect arguments are passed on the stack and so va_arg should use the
default alloca address space, not hard-code 0, for pointers to those.
The only in-tree target with a non-zero default alloca address space is
AMDGPU, but that does not support variadic arguments, so we cannot test
this upstream. However, downstream in CHERI LLVM (and Morello LLVM, a
further fork of that) we have targets that do both and so require this
change.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132247

Files:
  clang/lib/CodeGen/TargetInfo.cpp


Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -392,8 +392,10 @@
 
   // Cast the address we've calculated to the right type.
   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
-  if (IsIndirect)
-DirectTy = DirectTy->getPointerTo(0);
+  if (IsIndirect) {
+unsigned AllocaAS = CGF.CGM.getDataLayout().getAllocaAddrSpace();
+DirectTy = DirectTy->getPointerTo(AllocaAS);
+  }
 
   Address Addr =
   emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, 
DirectAlign,


Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -392,8 +392,10 @@
 
   // Cast the address we've calculated to the right type.
   llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy), *ElementTy = DirectTy;
-  if (IsIndirect)
-DirectTy = DirectTy->getPointerTo(0);
+  if (IsIndirect) {
+unsigned AllocaAS = CGF.CGM.getDataLayout().getAllocaAddrSpace();
+DirectTy = DirectTy->getPointerTo(AllocaAS);
+  }
 
   Address Addr =
   emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, DirectSize, DirectAlign,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132248: [CUDA][OpenMP] Fix the new driver crashing on multiple device-only outputs

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

The new driver supports device-only compilation for the offloading
device. The way this is handlded is a little different from the old
offloading driver. The old driver would put all the outputs in the final
action list akin to a linker job. The new driver however generated these
in the middle of the host's job so we instead put them all in a single
offloading action. However, we only handled these kinds of offloading
actions correctly when there was only a single input. When we had
multiple inputs we would instead attempt to get the host job, which
didn't exist, and crash.

This patch simply adds some extra logic to generate the jobs for all
dependencies if there is not host action.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132248

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-bindings.cu


Index: clang/test/Driver/cuda-bindings.cu
===
--- clang/test/Driver/cuda-bindings.cu
+++ clang/test/Driver/cuda-bindings.cu
@@ -146,3 +146,15 @@
 // RUN:--cuda-gpu-arch=sm_52 --cuda-device-only -c -o foo.o %s 2>&1 \
 // RUN: | FileCheck -check-prefix=D_ONLY %s
 // D_ONLY: "foo.o"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only 
-c -o foo.o %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "nvptx64-nvidia-cuda" - "clang", inputs: 
["[[INPUT:.+]]"], output: "[[PTX_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: 
["[[PTX_70]]"], output: "[[CUBIN_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "clang", inputs: 
["[[INPUT]]"], output: "[[PTX_52:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: 
["[[PTX_52]]"], output: "[[CUBIN_52:.+]]"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5261,20 +5261,21 @@
 //  \
 //Device Action 1  ---> OffloadAction -> Device Action 2
 //
-// For a) and b), we just return the job generated for the dependence. For
+// For a) and b), we just return the job generated for the dependences. For
 // c) and d) we override the current action with the host/device dependence
 // if the current toolchain is host/device and set the offload dependences
 // info with the jobs obtained from the device/host dependence(s).
 
-// If there is a single device option, just generate the job for it.
-if (OA->hasSingleDeviceDependence()) {
+// If there is a single device option or has no host action, just generate
+// the job for it.
+if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
   InputInfoList DevA;
   OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
const char *DepBoundArch) {
-DevA =
-BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
-   /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
-   CachedResults, DepA->getOffloadingDeviceKind());
+DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, 
AtTopLevel,
+   /*MultipleArchs*/ !!DepBoundArch,
+   LinkingOutput, CachedResults,
+   DepA->getOffloadingDeviceKind()));
   });
   return DevA;
 }


Index: clang/test/Driver/cuda-bindings.cu
===
--- clang/test/Driver/cuda-bindings.cu
+++ clang/test/Driver/cuda-bindings.cu
@@ -146,3 +146,15 @@
 // RUN:--cuda-gpu-arch=sm_52 --cuda-device-only -c -o foo.o %s 2>&1 \
 // RUN: | FileCheck -check-prefix=D_ONLY %s
 // D_ONLY: "foo.o"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only -c -o foo.o %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_70]]"], output: "[[CUBIN_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "cla

[PATCH] D132066: [clang][deps] Allow switching between lazily/eagerly loaded PCMs

2022-08-19 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir 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/D132066/new/

https://reviews.llvm.org/D132066

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


[PATCH] D132248: [CUDA][OpenMP] Fix the new driver crashing on multiple device-only outputs

2022-08-19 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 454036.
jhuber6 added a comment.

Forgot to use the new driver in the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132248

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-bindings.cu


Index: clang/test/Driver/cuda-bindings.cu
===
--- clang/test/Driver/cuda-bindings.cu
+++ clang/test/Driver/cuda-bindings.cu
@@ -146,3 +146,15 @@
 // RUN:--cuda-gpu-arch=sm_52 --cuda-device-only -c -o foo.o %s 2>&1 \
 // RUN: | FileCheck -check-prefix=D_ONLY %s
 // D_ONLY: "foo.o"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu --offload-new-driver 
-ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only 
-c -o foo.o %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "nvptx64-nvidia-cuda" - "clang", inputs: 
["[[INPUT:.+]]"], output: "[[PTX_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: 
["[[PTX_70]]"], output: "[[CUBIN_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "clang", inputs: 
["[[INPUT]]"], output: "[[PTX_52:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: 
["[[PTX_52]]"], output: "[[CUBIN_52:.+]]"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5261,20 +5261,21 @@
 //  \
 //Device Action 1  ---> OffloadAction -> Device Action 2
 //
-// For a) and b), we just return the job generated for the dependence. For
+// For a) and b), we just return the job generated for the dependences. For
 // c) and d) we override the current action with the host/device dependence
 // if the current toolchain is host/device and set the offload dependences
 // info with the jobs obtained from the device/host dependence(s).
 
-// If there is a single device option, just generate the job for it.
-if (OA->hasSingleDeviceDependence()) {
+// If there is a single device option or has no host action, just generate
+// the job for it.
+if (OA->hasSingleDeviceDependence() || !OA->hasHostDependence()) {
   InputInfoList DevA;
   OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
const char *DepBoundArch) {
-DevA =
-BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
-   /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
-   CachedResults, DepA->getOffloadingDeviceKind());
+DevA.append(BuildJobsForAction(C, DepA, DepTC, DepBoundArch, 
AtTopLevel,
+   /*MultipleArchs*/ !!DepBoundArch,
+   LinkingOutput, CachedResults,
+   DepA->getOffloadingDeviceKind()));
   });
   return DevA;
 }


Index: clang/test/Driver/cuda-bindings.cu
===
--- clang/test/Driver/cuda-bindings.cu
+++ clang/test/Driver/cuda-bindings.cu
@@ -146,3 +146,15 @@
 // RUN:--cuda-gpu-arch=sm_52 --cuda-device-only -c -o foo.o %s 2>&1 \
 // RUN: | FileCheck -check-prefix=D_ONLY %s
 // D_ONLY: "foo.o"
+
+//
+// Check to make sure we can generate multiple outputs for device-only
+// compilation.
+//
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu --offload-new-driver -ccc-print-bindings \
+// RUN:--offload-arch=sm_70 --offload-arch=sm_52 --offload-device-only -c -o foo.o %s 2>&1 \
+// RUN: | FileCheck -check-prefix=MULTI-D-ONLY %s
+//  MULTI-D-ONLY: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_70]]"], output: "[[CUBIN_70:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_52:.+]]"
+// MULTI-D-ONLY-NEXT: # "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_52]]"], output: "[[CUBIN_52:.+]]"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5261,20 +5261,21 @@
 //  \
 //Device Action 1  ---> OffloadAction -> Device Action 2
 //
-// For a) and b), we just return the job generated for the dependence. For
+// For a) and b), we just return the job generated for the dependences. For
 // c) and d) we override the current action with the host/device dependence
 // if the current toolchain is host/device and set the of

[clang-tools-extra] ee648c0 - [clang][index] Index unresolved member expression as reference

2022-08-19 Thread Aleksandr Platonov via cfe-commits

Author: Denis Fatkulin
Date: 2022-08-19T19:02:42+03:00
New Revision: ee648c0ce09b1edcee65407041eab38228f4b042

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

LOG: [clang][index] Index unresolved member expression as reference

Unresolved member expressions aren't indexed as references.

Example code:

```
struct Foo {
  template  void bar(T t);
};
template  void test(Foo F, T t) {
  F.bar(t); // Not indexed
}
```

Reviewed By: hokein

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/XRefsTests.cpp
clang/lib/Index/IndexBody.cpp
clang/test/Index/Core/index-dependent-source.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 40650c36046cb..e9e6b6f79a2d5 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@ TEST(FindReferences, WithinAST) {
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(

diff  --git a/clang/lib/Index/IndexBody.cpp b/clang/lib/Index/IndexBody.cpp
index eb8905a7459cd..8b8235c133023 100644
--- a/clang/lib/Index/IndexBody.cpp
+++ b/clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@ class BodyIndexer : public RecursiveASTVisitor 
{
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())

diff  --git a/clang/test/Index/Core/index-dependent-source.cpp 
b/clang/test/Index/Core/index-dependent-source.cpp
index 8832edefd5bf9..8fec9abd1e926 100644
--- a/clang/test/Index/Core/index-dependent-source.cpp
+++ b/clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@ template  void bar() {
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | 
c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# 
|  | Ref,Call,RelCall,RelCont | rel: 1
+}



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


[PATCH] D131091: [clang][index] Index unresolved member expression as reference

2022-08-19 Thread Aleksandr Platonov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGee648c0ce09b: [clang][index] Index unresolved member 
expression as reference (authored by denis-fatkulin, committed by ArcsinX).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D131091

Files:
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/lib/Index/IndexBody.cpp
  clang/test/Index/Core/index-dependent-source.cpp


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | 
Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | 
c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# 
|  | Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(


Index: clang/test/Index/Core/index-dependent-source.cpp
===
--- clang/test/Index/Core/index-dependent-source.cpp
+++ clang/test/Index/Core/index-dependent-source.cpp
@@ -231,3 +231,12 @@
   foo();
 // CHECK: [[@LINE-1]]:3 | function/C | foo | c:@FT@>1#Tfoo#v# |  | Ref,Call,RelCall,RelCont | rel: 1
 }
+
+struct Foo {
+  template  void bar();
+  // CHECK: [[@LINE-1]]:30 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# |  | Decl,RelChild | rel: 1
+};
+template  void baz(Foo f) {
+  f.bar();
+  // CHECK: [[@LINE-1]]:5 | instance-method/C++ | bar | c:@S@Foo@FT@>1#Tbar#v# |  | Ref,Call,RelCall,RelCont | rel: 1
+}
Index: clang/lib/Index/IndexBody.cpp
===
--- clang/lib/Index/IndexBody.cpp
+++ clang/lib/Index/IndexBody.cpp
@@ -468,7 +468,7 @@
 return true;
   }
 
-  bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
+  bool VisitOverloadExpr(OverloadExpr *E) {
 SmallVector Relations;
 SymbolRoleSet Roles = getRolesForRef(E, Relations);
 for (auto *D : E->decls())
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2090,6 +2090,14 @@
   [[f^oo]](s);
 }
   )cpp",
+  R"cpp(// unresolved member expression
+struct Foo {
+  template  void $decl[[b^ar]](T t); 
+};
+template  void test(Foo F, T t) {
+  F.[[bar]](t);
+}
+  )cpp",
 
   // Enum base
   R"cpp(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a47ec1b - [analyzer][NFC] Be more descriptive when we replay without inlining

2022-08-19 Thread via cfe-commits

Author: isuckatcs
Date: 2022-08-19T18:05:52+02:00
New Revision: a47ec1b79797c8c48c44f9ddf36fb82f8d87229d

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

LOG: [analyzer][NFC] Be more descriptive when we replay without inlining

This patch adds a ProgramPointTag to the EpsilonPoint created
before we replay a call without inlining.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 09ccb30613be8..20b13975d054b 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2117,8 +2117,9 @@ bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
 
   // Build an Epsilon node from which we will restart the analyzes.
   // Note that CE is permitted to be NULL!
-  ProgramPoint NewNodeLoc =
-   EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
+  static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining");
+  ProgramPoint NewNodeLoc = EpsilonPoint(
+  BeforeProcessingCall->getLocationContext(), CE, nullptr, &PT);
   // Add the special flag to GDM to signal retrying with no inlining.
   // Note, changing the state ensures that we are not going to cache out.
   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();



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


[PATCH] D132246: [analyzer][NFC] Be more descriptive when we replay without inlining

2022-08-19 Thread Domján Dániel 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 rGa47ec1b79797: [analyzer][NFC] Be more descriptive when we 
replay without inlining (authored by isuckatcs).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132246

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


Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2117,8 +2117,9 @@
 
   // Build an Epsilon node from which we will restart the analyzes.
   // Note that CE is permitted to be NULL!
-  ProgramPoint NewNodeLoc =
-   EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
+  static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining");
+  ProgramPoint NewNodeLoc = EpsilonPoint(
+  BeforeProcessingCall->getLocationContext(), CE, nullptr, &PT);
   // Add the special flag to GDM to signal retrying with no inlining.
   // Note, changing the state ensures that we are not going to cache out.
   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();


Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2117,8 +2117,9 @@
 
   // Build an Epsilon node from which we will restart the analyzes.
   // Note that CE is permitted to be NULL!
-  ProgramPoint NewNodeLoc =
-   EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
+  static SimpleProgramPointTag PT("ExprEngine", "Replay without inlining");
+  ProgramPoint NewNodeLoc = EpsilonPoint(
+  BeforeProcessingCall->getLocationContext(), CE, nullptr, &PT);
   // Add the special flag to GDM to signal retrying with no inlining.
   // Note, changing the state ensures that we are not going to cache out.
   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D132249: [clang][analyzer] Add some functions to StreamChecker with errno modeling.

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

Functions `fsetpos`, `fgetpos`, `ftell`, `rewind` are added.
Function `fileno` is handled by `StdLibraryFunctionsChecker` too,
tests are added for it but eval function is not needed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D132249

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-errno.c
  clang/test/Analysis/stream-error.c

Index: clang/test/Analysis/stream-error.c
===
--- clang/test/Analysis/stream-error.c
+++ clang/test/Analysis/stream-error.c
@@ -11,6 +11,9 @@
 void StreamTesterChecker_make_feof_stream(FILE *);
 void StreamTesterChecker_make_ferror_stream(FILE *);
 
+const char *WBuf = "123456789";
+char RBuf[10];
+
 void error_fopen(void) {
   FILE *F = fopen("file", "r");
   if (!F)
@@ -233,3 +236,37 @@
   }
   fclose(F);
 }
+
+void error_fsetpos(void) {
+  FILE *F = fopen("file", "w");
+  if (!F)
+return;
+  fpos_t Pos;
+  int rc = fsetpos(F, &Pos);
+  clang_analyzer_eval(feof(F)); // expected-warning{{FALSE}}
+  if (rc) {
+if (ferror(F))
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+else
+  clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}}
+  } else {
+clang_analyzer_eval(ferror(F)); // expected-warning{{FALSE}}
+  }
+  fwrite(WBuf, 1, 10, F); // expected-warning {{might be 'indeterminate'}}
+  fclose(F);
+}
+
+void error_rewind(void) {
+  FILE *F = fopen("file", "r");
+  if (!F)
+return;
+  fread(RBuf, 1, 10, F);
+  if (feof(F)) {
+rewind(F);
+clang_analyzer_eval(feof(F)); // expected-warning{{FALSE}}
+  } else if (ferror(F)) {
+rewind(F);
+clang_analyzer_eval(ferror(F)); // expected-warning{{FALSE}}
+  }
+  fclose(F);
+}
Index: clang/test/Analysis/stream-errno.c
===
--- clang/test/Analysis/stream-errno.c
+++ clang/test/Analysis/stream-errno.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,apiModeling.StdCLibraryFunctions,debug.ExprInspection \
-// RUN:   -verify %s
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify %s
 
 #include "Inputs/system-header-simulator.h"
 #include "Inputs/errno_func.h"
@@ -121,3 +121,75 @@
   clang_analyzer_eval(errno == 1); // expected-warning{{TRUE}}
   fclose(F);
 }
+
+void check_fgetpos(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fgetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_fsetpos(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  fpos_t Pos;
+  int Ret = fsetpos(F, &Pos);
+  if (Ret)
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  else
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_ftell(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  long Ret = ftell(F);
+  if (Ret == -1) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+  } else {
+clang_analyzer_eval(errno == 0); // expected-warning{{TRUE}}
+clang_analyzer_eval(Ret >= 0); // expected-warning{{TRUE}}
+  }
+  if (errno) {} // no-warning
+  fclose(F);
+}
+
+void check_rewind(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  errno = 0;
+  rewind(F);
+  clang_analyzer_eval(errno == 0);
+  // expected-warning@-1{{FALSE}}
+  // expected-warning@-2{{TRUE}}
+  fclose(F);
+}
+
+void check_fileno(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int N = fileno(F);
+  if (N == -1) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {} // no-warning
+fclose(F);
+return;
+  }
+  if (errno) {} // expected-warning{{An undefined value may be read from 'errno'}}
+}
Index: clang/test/Analysis/stream-errno-note.c
===
--- clang/test/Analysis/stream-errno-note.c
+++ clang/test/Analysis/stream-errno-note.c
@@ -1,5 +1,5 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,apiModeling.StdCLibraryFunctions \
-// RUN:   -analyzer-output text -verify %s
+// 

[clang] 1a60e00 - [RISCV] Use Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC

2022-08-19 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2022-08-19T09:11:22-07:00
New Revision: 1a60e003df8a8c03aae123bdec77e6a9db690862

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

LOG: [RISCV] Use Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC

Reviewed By: reames

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

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Driver/ToolChains/Arch/RISCV.cpp
clang/lib/Driver/ToolChains/BareMetal.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 639285540c0a6..9b97e890c3523 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -968,14 +968,9 @@ void CodeGenModule::EmitOpenCLMetadata() {
 
 void CodeGenModule::EmitBackendOptionsMetadata(
 const CodeGenOptions CodeGenOpts) {
-  switch (getTriple().getArch()) {
-  default:
-break;
-  case llvm::Triple::riscv32:
-  case llvm::Triple::riscv64:
+  if (getTriple().isRISCV()) {
 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
   CodeGenOpts.SmallDataLimit);
-break;
   }
 }
 

diff  --git a/clang/lib/Driver/ToolChains/Arch/RISCV.cpp 
b/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
index de6e045a9447f..c845e69c14e84 100644
--- a/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/RISCV.cpp
@@ -52,7 +52,7 @@ static void getRISCFeaturesFromMcpu(const Driver &D, const 
llvm::Triple &Triple,
 const llvm::opt::ArgList &Args,
 const llvm::opt::Arg *A, StringRef Mcpu,
 std::vector &Features) {
-  bool Is64Bit = (Triple.getArch() == llvm::Triple::riscv64);
+  bool Is64Bit = Triple.isRISCV64();
   llvm::RISCV::CPUKind CPUKind = llvm::RISCV::parseCPUKind(Mcpu);
   if (!llvm::RISCV::checkCPUKind(CPUKind, Is64Bit) ||
   !llvm::RISCV::getCPUFeaturesExceptStdExt(CPUKind, Features)) {
@@ -163,9 +163,7 @@ void riscv::getRISCVTargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 }
 
 StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
-  assert((Triple.getArch() == llvm::Triple::riscv32 ||
-  Triple.getArch() == llvm::Triple::riscv64) &&
- "Unexpected triple");
+  assert(Triple.isRISCV() && "Unexpected triple");
 
   // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
   // configured using `--with-abi=`, then the logic for the default choice is
@@ -213,7 +211,7 @@ StringRef riscv::getRISCVABI(const ArgList &Args, const 
llvm::Triple &Triple) {
   // We deviate from GCC's defaults here:
   // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
   // - On all other OSs we use the double floating point calling convention.
-  if (Triple.getArch() == llvm::Triple::riscv32) {
+  if (Triple.isRISCV32()) {
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "ilp32";
 else
@@ -228,9 +226,7 @@ StringRef riscv::getRISCVABI(const ArgList &Args, const 
llvm::Triple &Triple) {
 
 StringRef riscv::getRISCVArch(const llvm::opt::ArgList &Args,
   const llvm::Triple &Triple) {
-  assert((Triple.getArch() == llvm::Triple::riscv32 ||
-  Triple.getArch() == llvm::Triple::riscv64) &&
- "Unexpected triple");
+  assert(Triple.isRISCV() && "Unexpected triple");
 
   // GCC's logic around choosing a default `-march=` is complex. If GCC is not
   // configured using `--with-arch=`, then the logic for the default choice is
@@ -291,7 +287,7 @@ StringRef riscv::getRISCVArch(const llvm::opt::ArgList 
&Args,
   // We deviate from GCC's defaults here:
   // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
   // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
-  if (Triple.getArch() == llvm::Triple::riscv32) {
+  if (Triple.isRISCV32()) {
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "rv32imac";
 else

diff  --git a/clang/lib/Driver/ToolChains/BareMetal.cpp 
b/clang/lib/Driver/ToolChains/BareMetal.cpp
index 75b06d5e7d0d5..7b4b5a35205f0 100644
--- a/clang/lib/Driver/ToolChains/BareMetal.cpp
+++ b/clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -39,7 +39,7 @@ static bool findRISCVMultilibs(const Driver &D,
   StringRef Arch = riscv::getRISCVArch(Args, TargetTriple);
   StringRef Abi = tools::riscv::getRISCVABI(Args, TargetTriple);
 
-  if (TargetTriple.getArch() == llvm::Triple::riscv64) {
+  if (TargetTriple.isRISCV64()) {
 Multilib Imac = 
makeMultilib("").flag("+march=rv64imac").flag("+mabi=lp64");
 Multilib Imafdc = makeMultilib("/rv64imafdc/lp64d")
   .flag("+march=rv64imafdc")
@@

[PATCH] D132197: [RISCV] Use Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC

2022-08-19 Thread Craig Topper 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 rG1a60e003df8a: [RISCV] Use 
Triple::isRISCV/isRISCV32/isRISCV64 helps in some places. NFC (authored by 
craig.topper).

Changed prior to commit:
  https://reviews.llvm.org/D132197?vs=453861&id=454043#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132197

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp

Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -39,7 +39,7 @@
   StringRef Arch = riscv::getRISCVArch(Args, TargetTriple);
   StringRef Abi = tools::riscv::getRISCVABI(Args, TargetTriple);
 
-  if (TargetTriple.getArch() == llvm::Triple::riscv64) {
+  if (TargetTriple.isRISCV64()) {
 Multilib Imac = makeMultilib("").flag("+march=rv64imac").flag("+mabi=lp64");
 Multilib Imafdc = makeMultilib("/rv64imafdc/lp64d")
   .flag("+march=rv64imafdc")
@@ -57,7 +57,7 @@
 Result.Multilibs = MultilibSet().Either(Imac, Imafdc);
 return Result.Multilibs.select(Flags, Result.SelectedMultilib);
   }
-  if (TargetTriple.getArch() == llvm::Triple::riscv32) {
+  if (TargetTriple.isRISCV32()) {
 Multilib Imac =
 makeMultilib("").flag("+march=rv32imac").flag("+mabi=ilp32");
 Multilib I =
@@ -140,8 +140,7 @@
 }
 
 static bool isRISCVBareMetal(const llvm::Triple &Triple) {
-  if (Triple.getArch() != llvm::Triple::riscv32 &&
-  Triple.getArch() != llvm::Triple::riscv64)
+  if (!Triple.isRISCV())
 return false;
 
   if (Triple.getVendor() != llvm::Triple::UnknownVendor)
Index: clang/lib/Driver/ToolChains/Arch/RISCV.cpp
===
--- clang/lib/Driver/ToolChains/Arch/RISCV.cpp
+++ clang/lib/Driver/ToolChains/Arch/RISCV.cpp
@@ -52,7 +52,7 @@
 const llvm::opt::ArgList &Args,
 const llvm::opt::Arg *A, StringRef Mcpu,
 std::vector &Features) {
-  bool Is64Bit = (Triple.getArch() == llvm::Triple::riscv64);
+  bool Is64Bit = Triple.isRISCV64();
   llvm::RISCV::CPUKind CPUKind = llvm::RISCV::parseCPUKind(Mcpu);
   if (!llvm::RISCV::checkCPUKind(CPUKind, Is64Bit) ||
   !llvm::RISCV::getCPUFeaturesExceptStdExt(CPUKind, Features)) {
@@ -163,9 +163,7 @@
 }
 
 StringRef riscv::getRISCVABI(const ArgList &Args, const llvm::Triple &Triple) {
-  assert((Triple.getArch() == llvm::Triple::riscv32 ||
-  Triple.getArch() == llvm::Triple::riscv64) &&
- "Unexpected triple");
+  assert(Triple.isRISCV() && "Unexpected triple");
 
   // GCC's logic around choosing a default `-mabi=` is complex. If GCC is not
   // configured using `--with-abi=`, then the logic for the default choice is
@@ -213,7 +211,7 @@
   // We deviate from GCC's defaults here:
   // - On `riscv{XLEN}-unknown-elf` we use the integer calling convention only.
   // - On all other OSs we use the double floating point calling convention.
-  if (Triple.getArch() == llvm::Triple::riscv32) {
+  if (Triple.isRISCV32()) {
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "ilp32";
 else
@@ -228,9 +226,7 @@
 
 StringRef riscv::getRISCVArch(const llvm::opt::ArgList &Args,
   const llvm::Triple &Triple) {
-  assert((Triple.getArch() == llvm::Triple::riscv32 ||
-  Triple.getArch() == llvm::Triple::riscv64) &&
- "Unexpected triple");
+  assert(Triple.isRISCV() && "Unexpected triple");
 
   // GCC's logic around choosing a default `-march=` is complex. If GCC is not
   // configured using `--with-arch=`, then the logic for the default choice is
@@ -291,7 +287,7 @@
   // We deviate from GCC's defaults here:
   // - On `riscv{XLEN}-unknown-elf` we default to `rv{XLEN}imac`
   // - On all other OSs we use `rv{XLEN}imafdc` (equivalent to `rv{XLEN}gc`)
-  if (Triple.getArch() == llvm::Triple::riscv32) {
+  if (Triple.isRISCV32()) {
 if (Triple.getOS() == llvm::Triple::UnknownOS)
   return "rv32imac";
 else
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -968,14 +968,9 @@
 
 void CodeGenModule::EmitBackendOptionsMetadata(
 const CodeGenOptions CodeGenOpts) {
-  switch (getTriple().getArch()) {
-  default:
-break;
-  case llvm::Triple::riscv32:
-  case llvm::Triple::riscv64:
+  if (getTriple().isRISCV()) {
 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
   CodeGenOpts.SmallDataLimit);
-break;
   }
 }
 

[PATCH] D132111: [clang][Interp] Implement pointer (de)ref operations and DeclRefExprs

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



Comment at: clang/test/AST/Interp/cxx20.cpp:2
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++20 -verify 
%s
+// RUN: %clang_cc1 -std=c++20 -verify %s -DREFERENCE
+

tahonermann wrote:
> Is `-DREFERENCE` needed here? I don't see `REFERENCE` referenced in the test. 
> From the other test, I gather that it is intended to annotate differences 
> from the "reference" implementation.
Yes, exactly. I'll switch this one to use `-verify=ref` as well.


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

https://reviews.llvm.org/D132111

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


  1   2   >