[PATCH] D126192: [Driver] Improve linking options for target AVR

2022-06-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 updated this revision to Diff 433300.

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

https://reviews.llvm.org/D126192

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/AVR.cpp
  clang/test/Driver/avr-toolchain.c

Index: clang/test/Driver/avr-toolchain.c
===
--- clang/test/Driver/avr-toolchain.c
+++ clang/test/Driver/avr-toolchain.c
@@ -53,8 +53,22 @@
 // LINKA-NOT: warning: {{.*}} data section address
 
 // RUN: %clang -### --target=avr --sysroot=%S/Inputs/ -mmcu=atmega328 %s 2>&1 | FileCheck --check-prefixes=NOGCC %s
-// NOGCC: warning: no avr-gcc installation can be found on the system, cannot link standard libraries
 // NOGCC: warning: standard library not linked and so no interrupt vector table or compiler runtime routines will be linked
 // NOGCC-NOT: warning: {{.*}} microcontroller
 // NOGCC-NOT: warning: {{.*}} avr-libc
 // NOGCC-NOT: warning: {{.*}} data section address
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=avrld 2>&1 | FileCheck --check-prefix=NOLD %s
+// NOLD: error: invalid linker
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=lld 2>&1 | FileCheck --check-prefix=LLD %s
+// LLD: {{".*lld"}}
+// LLD-NOT: "avr-ld"
+// LLD-NOT: "-mavr5"
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -T avr.lds 2>&1 | FileCheck --check-prefix=LDS0 %s
+// LDS0: "-T" "avr.lds" "-mavr5"
+
+// RUN: %clang -### --target=avr --sysroot=%S/Inputs/basic_avr_tree -mmcu=atmega328 %s -fuse-ld=lld -T avr.lds 2>&1 | FileCheck --check-prefix=LDS1 %s
+// LDS1: "-T" "avr.lds"
+// LDS1-NOT: "-mavr5"
Index: clang/lib/Driver/ToolChains/AVR.cpp
===
--- clang/lib/Driver/ToolChains/AVR.cpp
+++ clang/lib/Driver/ToolChains/AVR.cpp
@@ -375,8 +375,7 @@
 
   // Only add default libraries if the user hasn't explicitly opted out.
   if (!Args.hasArg(options::OPT_nostdlib) &&
-  !Args.hasArg(options::OPT_nodefaultlibs) &&
-  GCCInstallation.isValid()) {
+  !Args.hasArg(options::OPT_nodefaultlibs) && GCCInstallation.isValid()) {
 GCCInstallPath = GCCInstallation.getInstallPath();
 std::string GCCParentPath(GCCInstallation.getParentLibPath());
 getProgramPaths().push_back(GCCParentPath + "/../bin");
@@ -429,9 +428,12 @@
   // Compute information about the target AVR.
   std::string CPU = getCPUName(D, Args, getToolChain().getTriple());
   llvm::Optional FamilyName = GetMCUFamilyName(CPU);
+  llvm::Optional AVRLibcRoot = TC.findAVRLibcInstallation();
   llvm::Optional SectionAddressData = GetMCUSectionAddressData(CPU);
 
-  std::string Linker = getToolChain().GetProgramPath(getShortName());
+  // Compute the linker program path, and use GNU "avr-ld" as default.
+  std::string Linker = getToolChain().GetLinkerPath(nullptr);
+
   ArgStringList CmdArgs;
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
 
@@ -450,17 +452,11 @@
   if (!Args.hasArg(options::OPT_nostdlib) &&
   !Args.hasArg(options::OPT_nodefaultlibs)) {
 if (!CPU.empty()) {
-Optional FamilyName = GetMCUFamilyName(CPU);
-Optional AVRLibcRoot = TC.findAVRLibcInstallation();
-
   if (!FamilyName) {
 // We do not have an entry for this CPU in the family
 // mapping table yet.
 D.Diag(diag::warn_drv_avr_family_linking_stdlibs_not_implemented)
 << CPU;
-  } else if (TC.getGCCInstallPath().empty()) {
-// We can not link since there is no avr-ld.
-D.Diag(diag::warn_drv_avr_gcc_not_found);
   } else if (!AVRLibcRoot) {
 // No avr-libc found and so no runtime linked.
 D.Diag(diag::warn_drv_avr_libc_not_found);
@@ -473,7 +469,6 @@
 LinkStdlib = true;
   }
 }
-
 if (!LinkStdlib)
   D.Diag(diag::warn_drv_avr_stdlib_not_linked);
   }
@@ -508,11 +503,19 @@
 
 CmdArgs.push_back("--end-group");
 
+// Add user specified linker script.
+const Arg *LDS = Args.getLastArg(options::OPT_T);
+if (LDS) {
+  CmdArgs.push_back(Args.MakeArgString("-T"));
+  CmdArgs.push_back(Args.MakeArgString(LDS->getValue()));
+}
+
 // Specify the family name as the emulation mode to use.
 // This is almost always required because otherwise avr-ld
 // will assume 'avr2' and warn about the program being larger
 // than the bare minimum supports.
-CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
+if (Linker.find("avr-ld") != std::string::npos)
+  CmdArgs.push_back(Args.MakeArgString(std::string("-m") + *FamilyName));
   }
 
   C.addCommand(std::make_unique(
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/i

[PATCH] D126672: [Driver] Add multiarch path for RISC-V

2022-06-01 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

In D126672#3546782 , @Hahnfeld wrote:

> In D126672#3546773 , @MaskRay wrote:
>
>> This needs a test.
>
> There are no tests for any of the other architectures.

@MaskRay is this ok to land without the test? IMHO, if this part of the driver 
is to be tested, it should happen for all architectures and requires mock 
directories because the paths are only added to the list of include / library 
directories if they exist. This goes far beyond this patch, only adding a 
`case` to the existing method.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126672

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


[PATCH] D126192: [Driver] Improve linking options for target AVR

2022-06-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a comment.

In D126192#3549238 , @MaskRay wrote:

> I am still uncomfortable with such a change. Trying to be smart sometimes may 
> get in the way.

I have removed the guess of default linker script. Currently my patch only does

1. Support linking with lld if user specifed `-fuse-ld=lld`
2. Support user specifed linker script


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

https://reviews.llvm.org/D126192

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


[PATCH] D126757: Fix clang RecursiveASTVisitor for definition of XXXTemplateSpecializationDecl

2022-06-01 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Thanks for the patch!

Could you add a semantic highlighting test case to 
SemanticHighlighting.GetsCorrectTokens 

 as well please? The test cases there are pieces of code annotated with the 
type of highlighting kind each token should get.




Comment at: clang/include/clang/AST/RecursiveASTVisitor.h:2037

\
 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));  
\
+if (getDerived().shouldVisitTemplateInstantiations() ||
\

We should move this call to `TraverseNestedNameSpecifierLoc` into the `else` 
branch, since `Traverse...Helper` already does that:

* `TraverseCXXRecordHelper` does it via `TraverseRecordHelper` 
[here](https://searchfox.org/llvm/rev/c7bee26f4fe170a065e48a2650e70802e9fc9ece/clang/include/clang/AST/RecursiveASTVisitor.h#1995)
* `TraverseVarHelper` does it via `TraverseDeclaratorHelper` 
[here](https://searchfox.org/llvm/rev/c7bee26f4fe170a065e48a2650e70802e9fc9ece/clang/include/clang/AST/RecursiveASTVisitor.h#2098)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126757

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


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

2022-06-01 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 433301.
python3kgae added a comment.

Cleanup test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124753

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


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


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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

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

This isn't an NFC change. It's more than a refactor/cosmetic change.
Please run some benchmarks to validate the assumed performance characteristics.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:156
+  private:
+llvm::SmallSet Aux;
+  };

Have you considered [[ 
https://www.llvm.org/docs/ProgrammersManual.html#llvm-adt-smallptrset-h | 
llvm::SmallPtrSet]] ?



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:56-59
+  const ProgramState *RawSt = State.get();
+  if (AssumeStack.hasCycle(RawSt))
+return {State, State};
+  AssumeStack.push(RawSt);

Why don't you return `RawSt` on the early return path instead? That seems to 
contain more information than `State`, right?

You lookup twice the location of the `RawSt` entry; once in the `hasCycle()` 
and again in the `push()`.
I would recommend doing an unconditional `insert()` directly and reusing the 
returned bool part of the pair to observe if it did actually insert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[PATCH] D126725: [pseudo] rename pseudo-gen -> clang-pseudo-gen. NFC

2022-06-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: llvm/utils/gn/secondary/clang-tools-extra/pseudo/gen/BUILD.gn:1
-executable("pseudo-gen") {
+executable("clang-pseudo-gen") {
   configs += [ "//llvm/utils/gn/build:clang_code" ]

I was skeptical there should be an additional change in the gn build (building 
the inc file), but it looks like the gn file is incomplete, the `cxx` doesn't 
compile in gn build, there is a 
[fixme](https://github.com/llvm/llvm-project/blob/main/llvm/utils/gn/secondary/clang-tools-extra/pseudo/cxx/BUILD.gn#L2),
 I think it is ok.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126725

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


[PATCH] D126498: [clangd] Fix hover crashing on integral or enumeral casts

2022-06-01 Thread Georg Kotheimer via Phabricator via cfe-commits
gkll updated this revision to Diff 433304.
gkll added a comment.

Avoid double negation.


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

https://reviews.llvm.org/D126498

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h

Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -59,6 +59,9 @@
   // Extra arguments for the compiler invocation.
   std::vector ExtraArgs;
 
+  // Predefine macros such as __UINTPTR_TYPE__.
+  bool PredefineMacros = false;
+
   TidyProvider ClangTidyProvider = {};
   // Index to use when building AST.
   const SymbolIndex *ExternalIndex = nullptr;
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -40,9 +40,12 @@
   ParseInputs Inputs;
   Inputs.FeatureModules = FeatureModules;
   auto &Argv = Inputs.CompileCommand.CommandLine;
-  // In tests, omit predefined macros (__GNUC__ etc) for a 25% speedup.
-  // There are hundreds, and we'd generate, parse, serialize, and re-parse them!
-  Argv = {"clang", "-Xclang", "-undef"};
+  Argv = {"clang", "-Xclang"};
+  // In tests, unless explicitly specified otherwise, omit predefined macros
+  // (__GNUC__ etc) for a 25% speedup. There are hundreds, and we'd generate,
+  // parse, serialize, and re-parse them!
+  if (!PredefineMacros)
+Argv.push_back("-undef");
   // FIXME: this shouldn't need to be conditional, but it breaks a
   // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
   if (!HeaderCode.empty()) {
Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3206,6 +3206,41 @@
   ASSERT_TRUE(H);
   EXPECT_EQ(H->Definition, "int arr[]");
 }
+
+TEST(Hover, GlobalVarEnumeralCastNoCrash) {
+  Annotations T(R"cpp(
+using uintptr_t = __UINTPTR_TYPE__;
+enum Test : uintptr_t {};
+unsigned global_var;
+void foo() {
+  Test v^al = static_cast(reinterpret_cast(&global_var));
+}
+  )cpp");
+
+  TestTU TU = TestTU::withCode(T.code());
+  TU.PredefineMacros = true;
+  auto AST = TU.build();
+  auto HI = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(HI);
+  EXPECT_EQ(*HI->Value, "&global_var");
+}
+
+TEST(Hover, GlobalVarIntCastNoCrash) {
+  Annotations T(R"cpp(
+using uintptr_t = __UINTPTR_TYPE__;
+unsigned global_var;
+void foo() {
+  uintptr_t a^ddress = reinterpret_cast(&global_var);
+}
+  )cpp");
+
+  TestTU TU = TestTU::withCode(T.code());
+  TU.PredefineMacros = true;
+  auto AST = TU.build();
+  auto HI = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(HI);
+  EXPECT_EQ(*HI->Value, "&global_var");
+}
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -429,7 +429,8 @@
 return llvm::None;
 
   // Show enums symbolically, not numerically like APValue::printPretty().
-  if (T->isEnumeralType() && Constant.Val.getInt().getMinSignedBits() <= 64) {
+  if (T->isEnumeralType() && Constant.Val.isInt() &&
+  Constant.Val.getInt().getMinSignedBits() <= 64) {
 // Compare to int64_t to avoid bit-width match requirements.
 int64_t Val = Constant.Val.getInt().getExtValue();
 for (const EnumConstantDecl *ECD :
@@ -440,7 +441,7 @@
 .str();
   }
   // Show hex value of integers if they're at least 10 (or negative!)
-  if (T->isIntegralOrEnumerationType() &&
+  if (T->isIntegralOrEnumerationType() && Constant.Val.isInt() &&
   Constant.Val.getInt().getMinSignedBits() <= 64 &&
   Constant.Val.getInt().uge(10))
 return llvm::formatv("{0} ({1})", Constant.Val.getAsString(Ctx, T),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36423: [libc++] Introsort based sorting function

2022-06-01 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik commandeered this revision.
philnik added a reviewer: DIVYA.
philnik added a comment.
Herald added a subscriber: mgrang.
Herald added a project: All.

This has been superseded by D113413 .


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

https://reviews.llvm.org/D36423

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


[PATCH] D126731: [pseudo] Eliminate dependencies from clang-pseudo-gen. NFC

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

Nice.

> ninja clean; ninja pseudo-gen runs 169 actions only

I think previous version was ~400 actions.




Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:10
 #include "clang-pseudo/Grammar.h"
 #include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/ArrayRef.h"

Add a trailing comment `// for clang::tok::TokenKind`?

Maybe even remove this include -- we have an include in the Grammar.h, though 
it makes this file less IWYU-friendly).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126731

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


[PATCH] D126192: [Driver] Improve linking options for target AVR

2022-06-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a comment.

I have a bit confused, why `clang --target=x86_64 -fuse-ld=lld` needs not to be 
explicitly specified with a linker script and produces a runnable x86_64 ELF? 
How does lld arrange code/data addresses for x86_64 by default ?

My original will is `clang --target=avr -fuse-lld abc.c` can correctly produce 
an AVR ELF, as both `clang --target=x86_64 -fuse-ld=lld abc.c` and `avr-gcc 
abc.c` do. The `avr-gcc abc.c` command will use the default linker script 
inside avr-libc.


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

https://reviews.llvm.org/D126192

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


[PATCH] D126498: [clangd] Fix hover crashing on integral or enumeral casts

2022-06-01 Thread Georg Kotheimer via Phabricator via cfe-commits
gkll marked 2 inline comments as done.
gkll added a comment.

Thank you, and sorry for the chaos, this is my first submission to llvm :D




Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:3221
+  TestTU TU = TestTU::withCode(T.code());
+  TU.OmitPredefinedMacros = false;
+  auto AST = TU.build();

sammccall wrote:
> As an alternative (just to avoid adding this option), I think adding 
> "-target=x86_64-pc-linux-gnu" would force intptr_t to be long.
> Up to you.
I prefer using the predefine.


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

https://reviews.llvm.org/D126498

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


[clang] d597a46 - [clang][ASTImporter] Add support for import of UsingPackDecl.

2022-06-01 Thread Balázs Kéri via cfe-commits

Author: Balázs Kéri
Date: 2022-06-01T09:58:08+02:00
New Revision: d597a461e0f5b1d7508983878bc5a38326cffd14

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

LOG: [clang][ASTImporter] Add support for import of UsingPackDecl.

Reviewed By: martong

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

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 9c4f60511fb2f..5b35b70f09603 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -548,6 +548,7 @@ namespace clang {
 ExpectedDecl VisitUsingDecl(UsingDecl *D);
 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
+ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D);
 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
@@ -4832,6 +4833,35 @@ ExpectedDecl 
ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
   return ToUsingDir;
 }
 
+ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
+  DeclContext *DC, *LexicalDC;
+  DeclarationName Name;
+  SourceLocation Loc;
+  NamedDecl *ToD = nullptr;
+  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
+return std::move(Err);
+  if (ToD)
+return ToD;
+
+  auto ToInstantiatedFromUsingOrErr =
+  Importer.Import(D->getInstantiatedFromUsingDecl());
+  if (!ToInstantiatedFromUsingOrErr)
+return ToInstantiatedFromUsingOrErr.takeError();
+  SmallVector Expansions(D->expansions().size());
+  if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
+return std::move(Err);
+
+  UsingPackDecl *ToUsingPack;
+  if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
+  cast(*ToInstantiatedFromUsingOrErr),
+  Expansions))
+return ToUsingPack;
+
+  addDeclToContexts(D, ToUsingPack);
+
+  return ToUsingPack;
+}
+
 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
 UnresolvedUsingValueDecl *D) {
   DeclContext *DC, *LexicalDC;

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index f1965235c9a6d..4d37ac2ebb2ed 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -910,6 +910,20 @@ TEST_P(ImportDecl, ImportUsingEnumDecl) {
  functionDecl(hasDescendant(usingEnumDecl(hasName("bar");
 }
 
+const internal::VariadicDynCastAllOfMatcher usingPackDecl;
+
+TEST_P(ImportDecl, ImportUsingPackDecl) {
+  MatchVerifier Verifier;
+  testImport(
+  "struct A { int operator()() { return 1; } };"
+  "struct B { int operator()() { return 2; } };"
+  "template struct C : T... { using T::operator()...; };"
+  "C declToImport;",
+  Lang_CXX20, "", Lang_CXX20, Verifier,
+  varDecl(hasType(templateSpecializationType(hasDeclaration(
+  classTemplateSpecializationDecl(hasDescendant(usingPackDecl(;
+}
+
 /// \brief Matches shadow declarations introduced into a scope by a
 ///(resolved) using declaration.
 ///
@@ -1022,6 +1036,31 @@ TEST_P(ImportExpr, DependentSizedArrayType) {
  has(fieldDecl(hasType(dependentSizedArrayType(;
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportUsingPackDecl) {
+  Decl *FromTU = getTuDecl(
+  "struct A { int operator()() { return 1; } };"
+  "struct B { int operator()() { return 2; } };"
+  "template struct C : T... { using T::operator()...; };"
+  "C Var;",
+  Lang_CXX20);
+
+  auto From = FirstDeclMatcher().match(FromTU, usingPackDecl());
+  ASSERT_TRUE(From);
+  auto To = cast(Import(From, Lang_CXX20));
+  ASSERT_TRUE(To);
+
+  ArrayRef FromExpansions = From->expansions();
+  ArrayRef ToExpansions = To->expansions();
+  ASSERT_EQ(FromExpansions.size(), ToExpansions.size());
+  for (unsigned int I = 0; I < FromExpansions.size(); ++I) {
+auto ImportedExpansion = Import(FromExpansions[I], Lang_CXX20);
+EXPECT_EQ(ImportedExpansion, ToExpansions[I]);
+  }
+
+  auto ImportedDC = cast(Import(From->getDeclContext(), Lang_CXX20));
+  EXPECT_EQ(ImportedDC, cast(To->getDeclContext()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, TemplateTypeParmDeclNoDefaultArg) {
   Decl *FromTU = getTuDecl("template struct X {};", Lang_CXX03);
   auto From = FirstDeclMatcher().match(



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

[PATCH] D125986: [clang][ASTImporter] Add support for import of UsingPackDecl.

2022-06-01 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd597a461e0f5: [clang][ASTImporter] Add support for import of 
UsingPackDecl. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125986

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -910,6 +910,20 @@
  functionDecl(hasDescendant(usingEnumDecl(hasName("bar");
 }
 
+const internal::VariadicDynCastAllOfMatcher usingPackDecl;
+
+TEST_P(ImportDecl, ImportUsingPackDecl) {
+  MatchVerifier Verifier;
+  testImport(
+  "struct A { int operator()() { return 1; } };"
+  "struct B { int operator()() { return 2; } };"
+  "template struct C : T... { using T::operator()...; };"
+  "C declToImport;",
+  Lang_CXX20, "", Lang_CXX20, Verifier,
+  varDecl(hasType(templateSpecializationType(hasDeclaration(
+  classTemplateSpecializationDecl(hasDescendant(usingPackDecl(;
+}
+
 /// \brief Matches shadow declarations introduced into a scope by a
 ///(resolved) using declaration.
 ///
@@ -1022,6 +1036,31 @@
  has(fieldDecl(hasType(dependentSizedArrayType(;
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportUsingPackDecl) {
+  Decl *FromTU = getTuDecl(
+  "struct A { int operator()() { return 1; } };"
+  "struct B { int operator()() { return 2; } };"
+  "template struct C : T... { using T::operator()...; };"
+  "C Var;",
+  Lang_CXX20);
+
+  auto From = FirstDeclMatcher().match(FromTU, usingPackDecl());
+  ASSERT_TRUE(From);
+  auto To = cast(Import(From, Lang_CXX20));
+  ASSERT_TRUE(To);
+
+  ArrayRef FromExpansions = From->expansions();
+  ArrayRef ToExpansions = To->expansions();
+  ASSERT_EQ(FromExpansions.size(), ToExpansions.size());
+  for (unsigned int I = 0; I < FromExpansions.size(); ++I) {
+auto ImportedExpansion = Import(FromExpansions[I], Lang_CXX20);
+EXPECT_EQ(ImportedExpansion, ToExpansions[I]);
+  }
+
+  auto ImportedDC = cast(Import(From->getDeclContext(), Lang_CXX20));
+  EXPECT_EQ(ImportedDC, cast(To->getDeclContext()));
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, TemplateTypeParmDeclNoDefaultArg) {
   Decl *FromTU = getTuDecl("template struct X {};", Lang_CXX03);
   auto From = FirstDeclMatcher().match(
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -548,6 +548,7 @@
 ExpectedDecl VisitUsingDecl(UsingDecl *D);
 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
+ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D);
 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
@@ -4832,6 +4833,35 @@
   return ToUsingDir;
 }
 
+ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
+  DeclContext *DC, *LexicalDC;
+  DeclarationName Name;
+  SourceLocation Loc;
+  NamedDecl *ToD = nullptr;
+  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
+return std::move(Err);
+  if (ToD)
+return ToD;
+
+  auto ToInstantiatedFromUsingOrErr =
+  Importer.Import(D->getInstantiatedFromUsingDecl());
+  if (!ToInstantiatedFromUsingOrErr)
+return ToInstantiatedFromUsingOrErr.takeError();
+  SmallVector Expansions(D->expansions().size());
+  if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
+return std::move(Err);
+
+  UsingPackDecl *ToUsingPack;
+  if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
+  cast(*ToInstantiatedFromUsingOrErr),
+  Expansions))
+return ToUsingPack;
+
+  addDeclToContexts(D, ToUsingPack);
+
+  return ToUsingPack;
+}
+
 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
 UnresolvedUsingValueDecl *D) {
   DeclContext *DC, *LexicalDC;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126299: [Driver] Support linking to compiler-rt for target AVR

2022-06-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a comment.

It seems that the expected path should be 
`$resource_dir/lib/avr5/libclang_rt.builtins.a`, other than 
`libclang_rt.builtins-avr5.a`. I will fix that.


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

https://reviews.llvm.org/D126299

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


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

2022-06-01 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added subscribers: browneee, vitalybuka.
vitalybuka added a comment.

This patch breaks msan bots: 
https://lab.llvm.org/buildbot/#/builders/5/builds/24307 and 
https://lab.llvm.org/buildbot/#/builders/74

https://lab.llvm.org/buildbot/#/builders/5/builds/24335 is (last green build 
https://lab.llvm.org/buildbot/#/builders/5/builds/24306 + this patch)

FYI @browneee


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

https://reviews.llvm.org/D120201

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


[PATCH] D126758: [clang-format] Handle do-while loops for RemoveBracesLLVM

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

If a do-while loop is in the block of a control statement, do not remove the 
braces.

Also updates the unit tests to match the updated LLVM Coding Standards. (See 
D126512 .)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126758

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25100,12 +25100,12 @@
   FormatStyle Style = getLLVMStyle();
   Style.RemoveBracesLLVM = true;
 
-  // The following eight test cases are fully-braced versions of the examples at
+  // The following nine test cases are fully-braced versions of the examples at
   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
   // statement-bodies-of-if-else-loop-statements".
 
-  // 1. Omit the braces, since the body is simple and clearly associated with
-  // the if.
+  // 1. Omit the braces since the body is simple and clearly associated with the
+  // `if`.
   verifyFormat("if (isa(D))\n"
"  handleFunctionDecl(D);\n"
"else if (isa(D))\n"
@@ -25125,32 +25125,29 @@
"  // the scope of the `if`.\n"
"  // Because the condition is documented, we can't really\n"
"  // hoist this comment that applies to the body above the\n"
-   "  // if.\n"
+   "  // `if`.\n"
"  handleOtherDecl(D);\n"
"}",
Style);
 
-  // 3. Use braces on the outer `if` to avoid a potential dangling else
+  // 3. Use braces on the outer `if` to avoid a potential dangling `else`
   // situation.
   verifyFormat("if (isa(D)) {\n"
-   "  for (auto *A : D.attrs())\n"
-   "if (shouldProcessAttr(A))\n"
-   "  handleAttr(A);\n"
+   "  if (shouldProcessAttr(A))\n"
+   "handleAttr(A);\n"
"}",
"if (isa(D)) {\n"
-   "  for (auto *A : D.attrs()) {\n"
-   "if (shouldProcessAttr(A)) {\n"
-   "  handleAttr(A);\n"
-   "}\n"
+   "  if (shouldProcessAttr(A)) {\n"
+   "handleAttr(A);\n"
"  }\n"
"}",
Style);
 
-  // 4. Use braces for the `if` block to keep it uniform with the else block.
+  // 4. Use braces for the `if` block to keep it uniform with the `else` block.
   verifyFormat("if (isa(D)) {\n"
"  handleFunctionDecl(D);\n"
"} else {\n"
-   "  // In this else case, it is necessary that we explain the\n"
+   "  // In this `else` case, it is necessary that we explain the\n"
"  // situation with this surprisingly long comment, so it\n"
"  // would be unclear without the braces whether the\n"
"  // following statement is in the scope of the `if`.\n"
@@ -25158,9 +25155,9 @@
"}",
Style);
 
-  // 5. This should also omit braces.  The `for` loop contains only a single
+  // 5. This should also omit braces. The `for` loop contains only a single
   // statement, so it shouldn't have braces.  The `if` also only contains a
-  // single simple statement (the for loop), so it also should omit braces.
+  // single simple statement (the `for` loop), so it also should omit braces.
   verifyFormat("if (isa(D))\n"
"  for (auto *A : D.attrs())\n"
"handleAttr(A);",
@@ -25171,18 +25168,26 @@
"}",
Style);
 
-  // 6. Use braces for the outer `if` since the nested `for` is braced.
+  // 6. Use braces for a `do-while` loop and its enclosing statement.
+  verifyFormat("if (Tok->is(tok::l_brace)) {\n"
+   "  do {\n"
+   "Tok = Tok->Next;\n"
+   "  } while (Tok);\n"
+   "}",
+   Style);
+
+  // 7. Use braces for the outer `if` since the nested `for` is braced.
   verifyFormat("if (isa(D)) {\n"
"  for (auto *A : D.attrs()) {\n"
-   "// In this for loop body, it is necessary that we explain\n"
-   "// the situation with this surprisingly long comment,\n"
-   "// forcing braces on the `for` block.\n"
+   "// In this `for` loop body, it is necessary that we\n"
+   "// explain the situation with this surprisingly long\n"
+   "// comment, 

[PATCH] D126066: [clang] [WIP] Don't plumb access specifier attributes through Parser unnecessarily.

2022-06-01 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added a comment.

I erroneously stated in the description that all tests pass, but as the CI 
shows, this is actually not true. Marking this as "WIP" until I figure out 
whether this change can be salvaged or should be abandoned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126066

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


[PATCH] D126291: [flang][Driver] Update link job on windows

2022-06-01 Thread Diana Picus via Phabricator via cfe-commits
rovka added a comment.

In D126291#3547142 , @awarzynski 
wrote:

> In D126291#3547023 , @rovka wrote:
>
>> With this patch in place, we still need to add `-Xlinker -subsystem:console' 
>> in order to compile a simple 'Hello World' to run from the console.
>
> Is this behavior consistent with "clang.exe"? Also, any clue why is this 
> needed? Some documentation here 
> .
>  I've scanned it and am no wiser :/

Yep, it is consistent with clang. I tried running both `clang-cl.exe` and 
`clang.exe` on a `hello.cpp` and in both cases I get a civilized error from lld 
saying "lld-link: error: subsystem must be defined". 
I've read those docs too and I think the main takeaway is that it sets the 
entry point for the program. There's a nice table 

 that suggests that passing in `/subsystem:console` ultimately leads to `main` 
being called, which is definitely what we want, since that's what we're linking 
in via `Fortran_main`.
Now, it could be the case that for Fortran we could hardcode the subsystem 
since people probably (?!) don't write kernel mode drivers or boot applications 
in Fortran, but I'm not so sure about the GUI stuff (i.e. the windows 
subsystem). Since I don't know enough about these things, I'd rather leave 
users the option to use whatever subsystem they like (and hope things won't 
break just because we're linking in `Fortran_main.lib`). I'd love to hear more 
opinions though.


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

https://reviews.llvm.org/D126291

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


[PATCH] D126291: [flang][Driver] Update link job on windows

2022-06-01 Thread Diana Picus via Phabricator via cfe-commits
rovka updated this revision to Diff 433318.
rovka added a comment.

Updated comment in `linker-flags.f90` test


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

https://reviews.llvm.org/D126291

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/MSVC.cpp
  flang/test/Driver/linker-flags-windows.f90
  flang/test/Driver/linker-flags.f90

Index: flang/test/Driver/linker-flags.f90
===
--- flang/test/Driver/linker-flags.f90
+++ flang/test/Driver/linker-flags.f90
@@ -5,8 +5,8 @@
 ! NOTE: The additional linker flags tested here are currently only specified for
 ! GNU and Darwin. The following line will make sure that this test is skipped on
 ! Windows. If you are running this test on a yet another platform and it is
-! failing for you, please either update the following or (preferably) update the
-! linker invocation accordingly.
+! failing for you, please either update the following or (preferably)
+! create a similar test for your platform.
 ! UNSUPPORTED: system-windows
 
 !
Index: flang/test/Driver/linker-flags-windows.f90
===
--- /dev/null
+++ flang/test/Driver/linker-flags-windows.f90
@@ -0,0 +1,24 @@
+! Verify that the Fortran runtime libraries are present in the linker
+! invocation. These libraries are added on top of other standard runtime
+! libraries that the Clang driver will include.
+
+! NOTE: The additional linker flags tested here are currently specified in
+! clang/lib/Driver/Toolchains/MSVC.cpp.
+! REQUIRES: system-windows
+
+! RUN: %flang -### %S/Inputs/hello.f90 2>&1 | FileCheck %s
+
+! Compiler invocation to generate the object file
+! CHECK-LABEL: {{.*}} "-emit-obj"
+! CHECK-SAME:  "-o" "[[object_file:.*]]" {{.*}}Inputs/hello.f90
+
+! Linker invocation to generate the executable
+! NOTE: This check should also match if the default linker is lld-link.exe
+! CHECK-LABEL: link.exe
+! CHECK-NOT: libcmt
+! CHECK-NOT: oldnames
+! CHECK-SAME: Fortran_main.lib
+! CHECK-SAME: FortranRuntime.lib
+! CHECK-SAME: FortranDecimal.lib
+! CHECK-SAME: "[[object_file]]"
+
Index: clang/lib/Driver/ToolChains/MSVC.cpp
===
--- clang/lib/Driver/ToolChains/MSVC.cpp
+++ clang/lib/Driver/ToolChains/MSVC.cpp
@@ -81,7 +81,7 @@
 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
-  !C.getDriver().IsCLMode()) {
+  !C.getDriver().IsCLMode() && !C.getDriver().IsFlangMode()) {
 CmdArgs.push_back("-defaultlib:libcmt");
 CmdArgs.push_back("-defaultlib:oldnames");
   }
@@ -130,6 +130,11 @@
   Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
   }
 
+  if (C.getDriver().IsFlangMode()) {
+tools::addFortranRuntimeLibraryPath(TC, Args, CmdArgs);
+tools::addFortranRuntimeLibs(TC, CmdArgs);
+  }
+
   // Add the compiler-rt library directories to libpath if they exist to help
   // the linker find the various sanitizer, builtin, and profiling runtimes.
   for (const auto &LibPath : TC.getLibraryPaths()) {
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -599,7 +599,7 @@
   // TODO: Make this work unconditionally once Flang is mature enough.
   if (D.IsFlangMode() && Args.hasArg(options::OPT_flang_experimental_exec)) {
 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs);
-addFortranRuntimeLibs(CmdArgs);
+addFortranRuntimeLibs(ToolChain, CmdArgs);
 CmdArgs.push_back("-lm");
   }
 
Index: clang/lib/Driver/ToolChains/Darwin.cpp
===
--- clang/lib/Driver/ToolChains/Darwin.cpp
+++ clang/lib/Driver/ToolChains/Darwin.cpp
@@ -644,7 +644,7 @@
   if (getToolChain().getDriver().IsFlangMode() &&
   Args.hasArg(options::OPT_flang_experimental_exec)) {
 addFortranRuntimeLibraryPath(getToolChain(), Args, CmdArgs);
-addFortranRuntimeLibs(CmdArgs);
+addFortranRuntimeLibs(getToolChain(), CmdArgs);
   }
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
Index: clang/lib/Driver/ToolChains/CommonArgs.h
===
--- clang/lib/Driver/ToolChains/CommonArgs.h
+++ clang/lib/Driver/ToolChains/CommonArgs.h
@@ -121,7 +121,8 @@
   bool IsOffloadingHost = false, bool GompNeedsRT = false);
 
 /// Adds Fortran runtime libraries to \p CmdArgs.
-void addFortranRuntimeLibs(llvm::opt::ArgStringList &CmdArgs);
+void addFortranRuntimeLibs(const ToolChain &TC,
+   llvm::opt::ArgStringList &CmdArgs)

[PATCH] D126299: [Driver] Support linking to compiler-rt for target AVR

2022-06-01 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added inline comments.



Comment at: clang/lib/Driver/ToolChains/AVR.cpp:463
+std::string
+AVRToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
+  StringRef Component, FileType Type,

benshi001 wrote:
> This method decides the file name of compiler-rt, it is expected to be
> 
> libclang_rt.builtins-avrfamily.a, such as
> 
> libclang_rt.builtins-avr51.a
> libclang_rt.builtins-avrtiny.a
> libclang_rt.builtins-avrxmega3.a
This override method is unnecessary, the basic 
`ToolChain::buildCompilerRTBasename` has covered all cases for AVR, since

1. `.lib` suffix can never be generated for avr
2. `libclang_rt.builtins-avr5.a` is unexpected, which should be `
$resource_dir/lib/avr5/libclang_rt.builtins.a`.


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

https://reviews.llvm.org/D126299

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


[PATCH] D126759: [clang][dataflow] Model calls returning optionals

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

Model calls returning optionals


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126759

Files:
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -2150,6 +2150,70 @@
   UnorderedElementsAre(Pair("check-1", "safe"), Pair("check-2", "safe")));
 }
 
+TEST_P(UncheckedOptionalAccessTest, CallReturningOptional) {
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+$ns::$optional MakeOpt();
+
+void target() {
+  $ns::$optional opt = 0;
+  opt = MakeOpt();
+  opt.value();
+  /*[[check-1]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("check-1", "unsafe: input.cc:9:7")));
+
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+const $ns::$optional& MakeOpt();
+
+void target() {
+  $ns::$optional opt = 0;
+  opt = MakeOpt();
+  opt.value();
+  /*[[check-2]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("check-2", "unsafe: input.cc:9:7")));
+
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using IntOpt = $ns::$optional;
+IntOpt MakeOpt();
+
+void target() {
+  IntOpt opt = 0;
+  opt = MakeOpt();
+  opt.value();
+  /*[[check-3]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("check-3", "unsafe: input.cc:10:7")));
+
+  ExpectLatticeChecksFor(
+  R"(
+#include "unchecked_optional_access_test.h"
+
+using IntOpt = $ns::$optional;
+const IntOpt& MakeOpt();
+
+void target() {
+  IntOpt opt = 0;
+  opt = MakeOpt();
+  opt.value();
+  /*[[check-4]]*/
+}
+  )",
+  UnorderedElementsAre(Pair("check-4", "unsafe: input.cc:10:7")));
+}
+
 // FIXME: Add support for:
 // - constructors (copy, move)
 // - assignment operators (default, copy, move)
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -158,6 +158,21 @@
ComparesToSame(integerLiteral(equals(0);
 }
 
+auto possiblyAliasedOptionalType() {
+  return hasUnqualifiedDesugaredType(
+  recordType(hasDeclaration(optionalClass(;
+}
+
+auto possiblyAliasedOrReferencedOptionalType() {
+  return anyOf(possiblyAliasedOptionalType(),
+   referenceType(pointee(possiblyAliasedOptionalType(;
+}
+
+auto isCallReturningOptional() {
+  return callExpr(
+  callee(functionDecl(returns(possiblyAliasedOrReferencedOptionalType();
+}
+
 /// Creates a symbolic value for an `optional` value using `HasValueVal` as the
 /// symbolic value of its "has_value" property.
 StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) {
@@ -320,6 +335,18 @@
   });
 }
 
+void transferCallReturningOptional(const CallExpr *E,
+   const MatchFinder::MatchResult &Result,
+   LatticeTransferState &State) {
+  if (State.Env.getStorageLocation(*E, SkipPast::None) != nullptr)
+return;
+
+  auto &Loc = State.Env.createStorageLocation(*E);
+  State.Env.setStorageLocation(*E, Loc);
+  State.Env.setValue(
+  Loc, createOptionalValue(State.Env, State.Env.makeAtomicBoolValue()));
+}
+
 void assignOptionalValue(const Expr &E, LatticeTransferState &State,
  BoolValue &HasValueVal) {
   if (auto *OptionalLoc =
@@ -545,6 +572,10 @@
   // opt.value_or(X) != X
   .CaseOf(isValueOrNotEqX(), transferValueOrNotEqX)
 
+  // returns optional
+  .CaseOf(isCallReturningOptional(),
+transferCallReturningOptional)
+
   .Build();
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

2022-06-01 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:156
+  private:
+llvm::SmallSet Aux;
+  };

steakhal wrote:
> Have you considered [[ 
> https://www.llvm.org/docs/ProgrammersManual.html#llvm-adt-smallptrset-h | 
> llvm::SmallPtrSet]] ?
Actually, a SmallSet of pointers is transparently implemented with a 
SmallPtrSet.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:56-59
+  const ProgramState *RawSt = State.get();
+  if (AssumeStack.hasCycle(RawSt))
+return {State, State};
+  AssumeStack.push(RawSt);

steakhal wrote:
> Why don't you return `RawSt` on the early return path instead? That seems to 
> contain more information than `State`, right?
> 
> You lookup twice the location of the `RawSt` entry; once in the `hasCycle()` 
> and again in the `push()`.
> I would recommend doing an unconditional `insert()` directly and reusing the 
> returned bool part of the pair to observe if it did actually insert.
> Why don't you return `RawSt` on the early return path instead? That seems to 
> contain more information than `State`, right?
No, `RawSt` contains the same information as `State`.

> You lookup twice the location of the `RawSt` entry; once in the `hasCycle()` 
> and again in the `push()`.
> I would recommend doing an unconditional `insert()` directly and reusing the 
> returned bool part of the pair to observe if it did actually insert.

I am considering to change the container to a `SmallVector` instead. I'd like 
to keep the interface of `hasCycle` and `push` and `pop` because those express 
the intention more clearly. And SmallSet falls back to a simple linear search 
anyway if size is less than N.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

2022-06-01 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 2 inline comments as done.
martong added a comment.

In D126560#3549408 , @steakhal wrote:

> This isn't an NFC change. It's more than a refactor/cosmetic change.

Still, there is no visible change in the behavior, at least that is intended. 
Should it be an NFCi ?

> Please run some benchmarks to validate the assumed performance 
> characteristics.

Yeah I've thought of it, here it is:
F23275670: image.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[clang] b1b86b6 - [Clang][Driver] More explicit message when failing to find sanitizer resource file

2022-06-01 Thread via cfe-commits

Author: serge-sans-paille
Date: 2022-06-01T10:54:20+02:00
New Revision: b1b86b63943305f71e5fb522da168c9dbac1d39d

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

LOG: [Clang][Driver] More explicit message when failing to find sanitizer 
resource file

Compiler-rt doesn't provide support file for cfi on s390x ad ppc64le (at least).
When trying to use the flag, we get a file error.

This is an attempt at making the error more explicit.

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/fsanitize-ignorelist.c

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 618e748da444..1012551651c5 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -212,6 +212,8 @@ def err_drv_invalid_libcxx_deployment : Error<
   "invalid deployment target for -stdlib=libc++ (requires %0 or later)">;
 def err_drv_invalid_argument_to_option : Error<
   "invalid argument '%0' to -%1">;
+def err_drv_missing_sanitizer_ignorelist : Error<
+  "missing sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_ignorelist : Error<
   "malformed sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_coverage_allowlist : Error<

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index b63c6e463706..fbabd1a3e38a 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -168,7 +168,7 @@ static void addDefaultIgnorelists(const Driver &D, 
SanitizerMask Kinds,
 else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
   // If cfi_ignorelist.txt cannot be found in the resource dir, driver
   // should fail.
-  D.Diag(clang::diag::err_drv_no_such_file) << Path;
+  D.Diag(clang::diag::err_drv_missing_sanitizer_ignorelist) << Path;
   }
   validateSpecialCaseListFormat(
   D, IgnorelistFiles, clang::diag::err_drv_malformed_sanitizer_ignorelist,

diff  --git a/clang/test/Driver/fsanitize-ignorelist.c 
b/clang/test/Driver/fsanitize-ignorelist.c
index 17c4f5abcedc..22e8e724be75 100644
--- a/clang/test/Driver/fsanitize-ignorelist.c
+++ b/clang/test/Driver/fsanitize-ignorelist.c
@@ -64,7 +64,7 @@
 
 // If cfi_ignorelist.txt cannot be found in the resource dir, driver should 
fail.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -resource-dir=/dev/null %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-MISSING-CFI-IGNORELIST
-// CHECK-MISSING-CFI-IGNORELIST: error: no such file or directory: 
'{{.*}}cfi_ignorelist.txt'
+// CHECK-MISSING-CFI-IGNORELIST: error: missing sanitizer ignorelist: 
'{{.*}}cfi_ignorelist.txt'
 
 // -fno-sanitize-ignorelist disables checking for cfi_ignorelist.txt in the 
resource dir.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -fno-sanitize-ignorelist -resource-dir=/dev/null %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-MISSING-CFI-NO-IGNORELIST



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


[PATCH] D120484: More explicit message when failing to find a mandatory cfi ressource file

2022-06-01 Thread serge via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb1b86b639433: [Clang][Driver] More explicit message when 
failing to find sanitizer resource… (authored by serge-sans-paille).

Changed prior to commit:
  https://reviews.llvm.org/D120484?vs=433063&id=433323#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120484

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-ignorelist.c


Index: clang/test/Driver/fsanitize-ignorelist.c
===
--- clang/test/Driver/fsanitize-ignorelist.c
+++ clang/test/Driver/fsanitize-ignorelist.c
@@ -64,7 +64,7 @@
 
 // If cfi_ignorelist.txt cannot be found in the resource dir, driver should 
fail.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -resource-dir=/dev/null %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-MISSING-CFI-IGNORELIST
-// CHECK-MISSING-CFI-IGNORELIST: error: no such file or directory: 
'{{.*}}cfi_ignorelist.txt'
+// CHECK-MISSING-CFI-IGNORELIST: error: missing sanitizer ignorelist: 
'{{.*}}cfi_ignorelist.txt'
 
 // -fno-sanitize-ignorelist disables checking for cfi_ignorelist.txt in the 
resource dir.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto 
-fvisibility=default -fno-sanitize-ignorelist -resource-dir=/dev/null %s -### 
2>&1 | FileCheck %s --check-prefix=CHECK-MISSING-CFI-NO-IGNORELIST
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -168,7 +168,7 @@
 else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
   // If cfi_ignorelist.txt cannot be found in the resource dir, driver
   // should fail.
-  D.Diag(clang::diag::err_drv_no_such_file) << Path;
+  D.Diag(clang::diag::err_drv_missing_sanitizer_ignorelist) << Path;
   }
   validateSpecialCaseListFormat(
   D, IgnorelistFiles, clang::diag::err_drv_malformed_sanitizer_ignorelist,
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -212,6 +212,8 @@
   "invalid deployment target for -stdlib=libc++ (requires %0 or later)">;
 def err_drv_invalid_argument_to_option : Error<
   "invalid argument '%0' to -%1">;
+def err_drv_missing_sanitizer_ignorelist : Error<
+  "missing sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_ignorelist : Error<
   "malformed sanitizer ignorelist: '%0'">;
 def err_drv_malformed_sanitizer_coverage_allowlist : Error<


Index: clang/test/Driver/fsanitize-ignorelist.c
===
--- clang/test/Driver/fsanitize-ignorelist.c
+++ clang/test/Driver/fsanitize-ignorelist.c
@@ -64,7 +64,7 @@
 
 // If cfi_ignorelist.txt cannot be found in the resource dir, driver should fail.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto -fvisibility=default -resource-dir=/dev/null %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MISSING-CFI-IGNORELIST
-// CHECK-MISSING-CFI-IGNORELIST: error: no such file or directory: '{{.*}}cfi_ignorelist.txt'
+// CHECK-MISSING-CFI-IGNORELIST: error: missing sanitizer ignorelist: '{{.*}}cfi_ignorelist.txt'
 
 // -fno-sanitize-ignorelist disables checking for cfi_ignorelist.txt in the resource dir.
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=cfi -flto -fvisibility=default -fno-sanitize-ignorelist -resource-dir=/dev/null %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MISSING-CFI-NO-IGNORELIST
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -168,7 +168,7 @@
 else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
   // If cfi_ignorelist.txt cannot be found in the resource dir, driver
   // should fail.
-  D.Diag(clang::diag::err_drv_no_such_file) << Path;
+  D.Diag(clang::diag::err_drv_missing_sanitizer_ignorelist) << Path;
   }
   validateSpecialCaseListFormat(
   D, IgnorelistFiles, clang::diag::err_drv_malformed_sanitizer_ignorelist,
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -212,6 +212,8 @@
   "invalid deployment target for -stdlib=libc++ (requires %0 or later)">;
 def err_drv_invalid_argument_to_option : Error<
   "invalid argument '%0' to -%1">;
+def err_drv_missing_sanitizer_ignorelist : Error<
+  "missing sanitizer ignorelist: '%0'">;
 def err_drv_malforme

[PATCH] D126723: [pseudo] GC GSS nodes, reuse them with a freelist

2022-06-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Nice! I really like the form it goes now.




Comment at: clang-tools-extra/pseudo/include/clang-pseudo/GLR.h:82
 
 // FIXME: Most nodes live a fairly short time, and are simply discarded.
 // Is it worth refcounting them (we have empty padding) and returning to a

This FIXME is done by this patch :)



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:15
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"

an off-topic comment: we only use the function in debug branch code, this will 
trigger the include-cleaner warning in release mode :)

we could warp it with `#ifndef NDEBUG` as well.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:87
 NewHeads.clear();
+MaybeGC();
 glrReduce(PendingReduce, Params,

I would just call it before the `NewHeads.clear()`, and run the `gc` on the 
`NewHeads` directly.

It simplifies the implementation (no need to traverse three pending actions, 
and no duplicated elements in Roots). The downside is that some dead heads 
(heads with no available actions on `Terminal.symbol()`) will not be GCed in 
this run, but I think it is negligible, as those will be GCed in next run.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:391
+  llvm::ArrayRef Parents) {
+  ++NodeCount;
+  Node *Result = new (allocate(Parents.size()))

The NodeCount becomes vague now, we update in both addNode and allocate 
methods, I think we should have two separate counts.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:403
+  ++NodeCount;
+  if (FreeList.size() <= Parents)
+FreeList.resize(Parents + 1);

What's the practical size of the `FreeList`? I think we can just find one, and 
use it as initial default size, to save some cost of resize. 



Comment at: clang-tools-extra/pseudo/unittests/GLRTest.cpp:412
+  EXPECT_EQ(0u, GSStack.gc({AB, C})); // D is already gone.
+  auto *E = GSStack.addNode(0, nullptr, {Root});
+  EXPECT_EQ(3u, GSStack.gc({A, E})); // destroys B, AB, C

nit: since we free D, I think here E will reuse the memory free from D, maybe 
add pointer comparison with `E` and `D` ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126723

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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

2022-06-01 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 433324.
martong edited the summary of this revision.
martong added a comment.

- Use SmallVector in AssumeStack


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1190,7 +1190,6 @@
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
-  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 
@@ -1376,14 +1375,6 @@
 SVal VisitSVal(SVal V) { return V; }
   };
 
-  // A crude way of preventing this function from calling itself from 
evalBinOp.
-  static bool isReentering = false;
-  if (isReentering)
-return V;
-
-  isReentering = true;
   SVal SimplifiedV = Simplifier(State).Visit(V);
-  isReentering = false;
-
   return SimplifiedV;
 }
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -16,6 +16,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/ScopeExit.h"
 
 using namespace clang;
 using namespace ento;
@@ -46,6 +47,19 @@
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeDualImpl(ProgramStateRef &State,
   AssumeFunction &Assume) {
+
+  // Assume functions might recurse (see `reAssume` or `tryRearrange`). During
+  // the recursion the State might not change anymore, that means we reached a
+  // fixpoint.
+  // We avoid infinite recursion of assume calls by checking already visited
+  // States on the stack of assume function calls.
+  const ProgramState *RawSt = State.get();
+  if (AssumeStack.contains(RawSt))
+return {State, State};
+  AssumeStack.push(RawSt);
+  auto AssumeStackBuilder =
+  llvm::make_scope_exit([this]() { AssumeStack.pop(); });
+
   ProgramStateRef StTrue = Assume(true);
 
   if (!StTrue) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/Support/SaveAndRestore.h"
 #include 
 #include 
@@ -144,6 +145,20 @@
   /// but not thread-safe.
   bool NotifyAssumeClients = true;
 
+  /// A helper class to simulate the call stack of nested assume calls.
+  class AssumeStackTy {
+  public:
+void push(const ProgramState *S) { Aux.push_back(S); }
+void pop() { Aux.pop_back(); }
+bool contains(const ProgramState *S) const {
+  return llvm::find(Aux, S) != Aux.end();
+}
+
+  private:
+llvm::SmallVector Aux;
+  };
+  AssumeStackTy AssumeStack;
+
   virtual ProgramStateRef assumeInternal(ProgramStateRef state,
  DefinedSVal Cond, bool Assumption) = 
0;
 


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

[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

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

In D126560#3549570 , @martong wrote:

> In D126560#3549408 , @steakhal 
> wrote:
>
>> This isn't an NFC change. It's more than a refactor/cosmetic change.
>
> Still, there is no visible change in the behavior, at least that is intended. 
> Should it be an NFCi ?
>
>> Please run some benchmarks to validate the assumed performance 
>> characteristics.
>
> Yeah I've thought of it, here it is:
> F23275670: image.png 

Yes, let's go with NFCi.




Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:56-59
+  const ProgramState *RawSt = State.get();
+  if (AssumeStack.hasCycle(RawSt))
+return {State, State};
+  AssumeStack.push(RawSt);

martong wrote:
> steakhal wrote:
> > Why don't you return `RawSt` on the early return path instead? That seems 
> > to contain more information than `State`, right?
> > 
> > You lookup twice the location of the `RawSt` entry; once in the 
> > `hasCycle()` and again in the `push()`.
> > I would recommend doing an unconditional `insert()` directly and reusing 
> > the returned bool part of the pair to observe if it did actually insert.
> > Why don't you return `RawSt` on the early return path instead? That seems 
> > to contain more information than `State`, right?
> No, `RawSt` contains the same information as `State`.
> 
> > You lookup twice the location of the `RawSt` entry; once in the 
> > `hasCycle()` and again in the `push()`.
> > I would recommend doing an unconditional `insert()` directly and reusing 
> > the returned bool part of the pair to observe if it did actually insert.
> 
> I am considering to change the container to a `SmallVector` instead. I'd like 
> to keep the interface of `hasCycle` and `push` and `pop` because those 
> express the intention more clearly. And SmallSet falls back to a simple 
> linear search anyway if size is less than N.
> 
> 
> I'd like to keep the interface of hasCycle and push and pop because those 
> express the intention more clearly.
I disagree. Double lookups are always a code-smell. I insist on this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[PATCH] D107960: [clang][analyzer] Make ReturnPtrRange checker warn at negative index.

2022-06-01 Thread Balázs Kéri via Phabricator via cfe-commits
balazske abandoned this revision.
balazske added a comment.
Herald added a project: All.

With the current main branch the new test passes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107960

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


[PATCH] D126723: [pseudo] GC GSS nodes, reuse them with a freelist

2022-06-01 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:15
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/StringExtras.h"

hokein wrote:
> an off-topic comment: we only use the function in debug branch code, this 
> will trigger the include-cleaner warning in release mode :)
> 
> we could warp it with `#ifndef NDEBUG` as well.
conditional including is ugly and can cause subtle opt-only compile failures.
I'm tempted to add a "keep" pragma but want to think about how to handle this 
case a bit more.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:87
 NewHeads.clear();
+MaybeGC();
 glrReduce(PendingReduce, Params,

hokein wrote:
> I would just call it before the `NewHeads.clear()`, and run the `gc` on the 
> `NewHeads` directly.
> 
> It simplifies the implementation (no need to traverse three pending actions, 
> and no duplicated elements in Roots). The downside is that some dead heads 
> (heads with no available actions on `Terminal.symbol()`) will not be GCed in 
> this run, but I think it is negligible, as those will be GCed in next run.
Oops, I forgot that Pending* are all empty at the beginning of this loop. I 
should probably add an assertion for that.

We can call it right at the top of the loop, yes? It doesn't need to be between 
AddSsteps and NewHeads.clear().

> run the gc on the NewHeads directly
Unfortunately not: the GC naturally consumes the argument (it becomes the stack 
for the DFS) so we need a copy.
We could move the copy into gc() but:
 - this way we can reuse the same vector every time and don't have to allocate
 - soon we'll have error-recovery candidates as additional roots we want to 
pass in



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:391
+  llvm::ArrayRef Parents) {
+  ++NodeCount;
+  Node *Result = new (allocate(Parents.size()))

hokein wrote:
> The NodeCount becomes vague now, we update in both addNode and allocate 
> methods, I think we should have two separate counts.
- Oops, that duplicated ++NodeCount is just a mistake.
- names are vague now, both "NodeCount" and "Allocated" are dubious. Maybe I'll 
rename to `NodesCreated` and `Alive`, WDYT?
- are there actually more metrics we want to record? we have nodes-created, 
currently-live-nodes (Allocated.size()), nodes-destroyed (`NodeCount - 
Allocated.size()`). We could track max-live-node but I think Arena.bytes() is 
fine for our purposes.
- do we want to expose any of those numbers through APIs? I couldn't work out 
what I'd actually do with them.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:403
+  ++NodeCount;
+  if (FreeList.size() <= Parents)
+FreeList.resize(Parents + 1);

hokein wrote:
> What's the practical size of the `FreeList`? I think we can just find one, 
> and use it as initial default size, to save some cost of resize. 
It's whatever the max #parents is - maybe 10 or something?
I don't think it's worth adding a hard-coded guess to save ~1 resize of a 
single vector per parse!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126723

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


[PATCH] D126707: [analyzer][NFC] Move overconstrained check from reAssume to assumeDualImpl

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

LGTM; measure performance implications.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:117-120
   // Make internal constraint solver entities friends so they can access the
   // overconstrained-related functions. We want to keep this API inaccessible
   // for Checkers.
   friend class ConstraintManager;

Shouldn't you remove this as well? Check the friends.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126707

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


[PATCH] D126764: [clang] [ARM] Add __builtin_sponentry like on aarch64

2022-06-01 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo created this revision.
mstorsjo added reviewers: efriedma, zzheng.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
mstorsjo requested review of this revision.
Herald added a project: clang.

This is used for calling the SEH aware setjmp on MinGW.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126764

Files:
  clang/include/clang/Basic/BuiltinsARM.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/builtin-sponentry.c


Index: clang/test/CodeGen/builtin-sponentry.c
===
--- clang/test/CodeGen/builtin-sponentry.c
+++ clang/test/CodeGen/builtin-sponentry.c
@@ -1,8 +1,9 @@
 // RUN: %clang_cc1 -no-opaque-pointers -triple aarch64-windows-gnu -Oz 
-emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -no-opaque-pointers -triple thumbv7-windows-gnu -Oz 
-emit-llvm %s -o - | FileCheck %s
 
 void *test_sponentry(void) {
   return __builtin_sponentry();
 }
-// CHECK-LABEL: define dso_local i8* @test_sponentry()
+// CHECK-LABEL: define dso_local {{(arm_aapcs_vfpcc )?}}i8* @test_sponentry()
 // CHECK: = tail call i8* @llvm.sponentry.p0i8()
 // CHECK: ret i8*
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -7783,6 +7783,11 @@
   AccessKind);
   }
 
+  if (BuiltinID == ARM::BI__builtin_sponentry) {
+llvm::Function *F = CGM.getIntrinsic(Intrinsic::sponentry, 
AllocaInt8PtrTy);
+return Builder.CreateCall(F);
+  }
+
   // Handle MSVC intrinsics before argument evaluation to prevent double
   // evaluation.
   if (Optional MsvcIntId = translateArmToMsvcIntrin(BuiltinID))
Index: clang/include/clang/Basic/BuiltinsARM.def
===
--- clang/include/clang/Basic/BuiltinsARM.def
+++ clang/include/clang/Basic/BuiltinsARM.def
@@ -197,6 +197,9 @@
 BUILTIN(__builtin_arm_wsr64, "vcC*LLUi", "nc")
 BUILTIN(__builtin_arm_wsrp, "vcC*vC*", "nc")
 
+// Misc
+BUILTIN(__builtin_sponentry, "v*", "c")
+
 // Builtins for implementing ACLE MVE intrinsics. (Unlike NEON, these
 // don't need to live in a separate BuiltinsMVE.def, because they
 // aren't included from both here and BuiltinsAArch64.def.)


Index: clang/test/CodeGen/builtin-sponentry.c
===
--- clang/test/CodeGen/builtin-sponentry.c
+++ clang/test/CodeGen/builtin-sponentry.c
@@ -1,8 +1,9 @@
 // RUN: %clang_cc1 -no-opaque-pointers -triple aarch64-windows-gnu -Oz -emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -no-opaque-pointers -triple thumbv7-windows-gnu -Oz -emit-llvm %s -o - | FileCheck %s
 
 void *test_sponentry(void) {
   return __builtin_sponentry();
 }
-// CHECK-LABEL: define dso_local i8* @test_sponentry()
+// CHECK-LABEL: define dso_local {{(arm_aapcs_vfpcc )?}}i8* @test_sponentry()
 // CHECK: = tail call i8* @llvm.sponentry.p0i8()
 // CHECK: ret i8*
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -7783,6 +7783,11 @@
   AccessKind);
   }
 
+  if (BuiltinID == ARM::BI__builtin_sponentry) {
+llvm::Function *F = CGM.getIntrinsic(Intrinsic::sponentry, AllocaInt8PtrTy);
+return Builder.CreateCall(F);
+  }
+
   // Handle MSVC intrinsics before argument evaluation to prevent double
   // evaluation.
   if (Optional MsvcIntId = translateArmToMsvcIntrin(BuiltinID))
Index: clang/include/clang/Basic/BuiltinsARM.def
===
--- clang/include/clang/Basic/BuiltinsARM.def
+++ clang/include/clang/Basic/BuiltinsARM.def
@@ -197,6 +197,9 @@
 BUILTIN(__builtin_arm_wsr64, "vcC*LLUi", "nc")
 BUILTIN(__builtin_arm_wsrp, "vcC*vC*", "nc")
 
+// Misc
+BUILTIN(__builtin_sponentry, "v*", "c")
+
 // Builtins for implementing ACLE MVE intrinsics. (Unlike NEON, these
 // don't need to live in a separate BuiltinsMVE.def, because they
 // aren't included from both here and BuiltinsAArch64.def.)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126723: [pseudo] GC GSS nodes, reuse them with a freelist

2022-06-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:87
 NewHeads.clear();
+MaybeGC();
 glrReduce(PendingReduce, Params,

sammccall wrote:
> hokein wrote:
> > I would just call it before the `NewHeads.clear()`, and run the `gc` on the 
> > `NewHeads` directly.
> > 
> > It simplifies the implementation (no need to traverse three pending 
> > actions, and no duplicated elements in Roots). The downside is that some 
> > dead heads (heads with no available actions on `Terminal.symbol()`) will 
> > not be GCed in this run, but I think it is negligible, as those will be 
> > GCed in next run.
> Oops, I forgot that Pending* are all empty at the beginning of this loop. I 
> should probably add an assertion for that.
> 
> We can call it right at the top of the loop, yes? It doesn't need to be 
> between AddSsteps and NewHeads.clear().
> 
> > run the gc on the NewHeads directly
> Unfortunately not: the GC naturally consumes the argument (it becomes the 
> stack for the DFS) so we need a copy.
> We could move the copy into gc() but:
>  - this way we can reuse the same vector every time and don't have to allocate
>  - soon we'll have error-recovery candidates as additional roots we want to 
> pass in
> Oops, I forgot that Pending* are all empty at the beginning of this loop. I 
> should probably add an assertion for that.

Yes. I would probably do it after glrReduce and glrShift calls.

> We can call it right at the top of the loop, yes? It doesn't need to be 
> between AddSsteps and NewHeads.clear().

Yes, exactly.  We could also do that at the end of the loop.

> > run the gc on the NewHeads directly
> Unfortunately not: the GC naturally consumes the argument (it becomes the 
> stack for the DFS) so we need a copy.
> We could move the copy into gc() but:
>  - this way we can reuse the same vector every time and don't have to allocate
>  - soon we'll have error-recovery candidates as additional roots we want to 
> pass in

oh, I didn't notice that. I think making a copy is fine.




Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:391
+  llvm::ArrayRef Parents) {
+  ++NodeCount;
+  Node *Result = new (allocate(Parents.size()))

sammccall wrote:
> hokein wrote:
> > The NodeCount becomes vague now, we update in both addNode and allocate 
> > methods, I think we should have two separate counts.
> - Oops, that duplicated ++NodeCount is just a mistake.
> - names are vague now, both "NodeCount" and "Allocated" are dubious. Maybe 
> I'll rename to `NodesCreated` and `Alive`, WDYT?
> - are there actually more metrics we want to record? we have nodes-created, 
> currently-live-nodes (Allocated.size()), nodes-destroyed (`NodeCount - 
> Allocated.size()`). We could track max-live-node but I think Arena.bytes() is 
> fine for our purposes.
> - do we want to expose any of those numbers through APIs? I couldn't work out 
> what I'd actually do with them.
> names are vague now, both "NodeCount" and "Allocated" are dubious. Maybe I'll 
> rename to NodesCreated and Alive, WDYT?

Sounds good to me.

> are there actually more metrics we want to record? we have nodes-created, 
> currently-live-nodes (Allocated.size()), nodes-destroyed (NodeCount - 
> Allocated.size()). We could track max-live-node but I think Arena.bytes() is 
> fine for our purposes.

I think these are sufficient, should provide enough details about 
GSS-memory-related information. The other things I will like to record is the 
max-active-heads, but that's a different bit.

> do we want to expose any of those numbers through APIs? I couldn't work out 
> what I'd actually do with them.

I think we should avoid to expose an API per field, we probably just need a 
single API which returns a Stats struct containing all these things. We can do 
it later.





Comment at: clang-tools-extra/pseudo/lib/GLR.cpp:403
+  ++NodeCount;
+  if (FreeList.size() <= Parents)
+FreeList.resize(Parents + 1);

sammccall wrote:
> hokein wrote:
> > What's the practical size of the `FreeList`? I think we can just find one, 
> > and use it as initial default size, to save some cost of resize. 
> It's whatever the max #parents is - maybe 10 or something?
> I don't think it's worth adding a hard-coded guess to save ~1 resize of a 
> single vector per parse!
I would image there will be multiple resize calls, if the path like 
`allocate(1), allocate(3), ..., allocate(max)`, which I think it is practical? 
unless the first call is `allocate(max)` which is unlikely I think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126723

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


[PATCH] D126758: [clang-format] Handle do-while loops for RemoveBracesLLVM

2022-06-01 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/unittests/Format/FormatTest.cpp:25103
 
-  // The following eight test cases are fully-braced versions of the examples 
at
+  // The following nine test cases are fully-braced versions of the examples at
   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-

Nit. To avoid updating it every time we add an example.



Comment at: clang/unittests/Format/FormatTest.cpp:25407-25411
+  verifyFormat("do {\n"
+   "  ++I;\n"
+   "} while (hasMore() && Filter(*I));",
+   "do { ++I; } while (hasMore() && Filter(*I));",
+   Style);

What's the value of testing that newlines are added? That's not really the job 
of Insert/RemoveBraces.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126758

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


[clang] 3ec78d9 - [Clang] NFCI: Add a new bit HasExtraBitfields to FunctionType.

2022-06-01 Thread Sander de Smalen via cfe-commits

Author: Sander de Smalen
Date: 2022-06-01T12:40:33+02:00
New Revision: 3ec78d9ff1b3f430dab27434fe8f9a3790d08808

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

LOG: [Clang] NFCI: Add a new bit HasExtraBitfields to FunctionType.

The FunctionTypeExtraBitfields is currently only available when the
ExceptionSpecificationType == Dynamic, which means that there is no other
way to use or extend the FunctionTypeExtraBitfields independently of the
exception specification type.

This patch adds a new field HasExtraBitfields to specify
whether the prototype has trailing ExtraBitfields.

This patch intends to be NFC and is required for future extension
and use of the ExtraBitfields struct.

Reviewed By: aaron.ballman, erichkeane

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

Added: 


Modified: 
clang/include/clang/AST/Type.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/Type.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 45b75fe7960c3..5784839f4f961 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1624,6 +1624,9 @@ class alignas(8) Type : public ExtQualsTypeCommonBase {
 /// Whether this function has extended parameter information.
 unsigned HasExtParameterInfos : 1;
 
+/// Whether this function has extra bitfields for the prototype.
+unsigned HasExtraBitfields : 1;
+
 /// Whether the function is variadic.
 unsigned Variadic : 1;
 
@@ -3798,13 +3801,12 @@ class FunctionType : public Type {
 
   /// A simple holder for various uncommon bits which do not fit in
   /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
-  /// alignment of subsequent objects in TrailingObjects. You must update
-  /// hasExtraBitfields in FunctionProtoType after adding extra data here.
+  /// alignment of subsequent objects in TrailingObjects.
   struct alignas(void *) FunctionTypeExtraBitfields {
 /// The number of types in the exception specification.
 /// A whole unsigned is not needed here and according to
 /// [implimits] 8 bits would be enough here.
-unsigned NumExceptionType;
+unsigned NumExceptionType = 0;
   };
 
 protected:
@@ -3998,6 +4000,10 @@ class FunctionProtoType final
   Result.ExceptionSpec = ESI;
   return Result;
 }
+
+bool requiresFunctionProtoTypeExtraBitfields() const {
+  return ExceptionSpec.Type == EST_Dynamic;
+}
   };
 
 private:
@@ -4088,16 +4094,13 @@ class FunctionProtoType final
 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
   }
 
-  /// Whether the trailing FunctionTypeExtraBitfields is present.
-  static bool hasExtraBitfields(ExceptionSpecificationType EST) {
-// If the exception spec type is EST_Dynamic then we have > 0 exception
-// types and the exact number is stored in FunctionTypeExtraBitfields.
-return EST == EST_Dynamic;
-  }
-
   /// Whether the trailing FunctionTypeExtraBitfields is present.
   bool hasExtraBitfields() const {
-return hasExtraBitfields(getExceptionSpecType());
+assert((getExceptionSpecType() != EST_Dynamic ||
+FunctionTypeBits.HasExtraBitfields) &&
+   "ExtraBitfields are required for given ExceptionSpecType");
+return FunctionTypeBits.HasExtraBitfields;
+
   }
 
   bool hasExtQualifiers() const {

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 1ee18f913b914..6349d7b7c46f3 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -4451,8 +4451,7 @@ QualType ASTContext::getFunctionTypeInternal(
   QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
   FunctionType::ExceptionType, Expr *, FunctionDecl *,
   FunctionProtoType::ExtParameterInfo, Qualifiers>(
-  NumArgs, EPI.Variadic,
-  FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
+  NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
   ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
   EPI.ExtParameterInfos ? NumArgs : 0,
   EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);

diff  --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index ece4165c51f53..0f168a518707e 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -3213,12 +3213,15 @@ FunctionProtoType::FunctionProtoType(QualType result, 
ArrayRef params,
   FunctionTypeBits.Variadic = epi.Variadic;
   FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
 
-  // Fill in the extra trailing bitfields if present.
-  if (hasExtraBitfields(epi.ExceptionSpec.Type)) {
+  if (epi.requiresFunctionProtoTypeExtraBitfields()) {
+FunctionTypeBits.HasExtraBitfields = true;
 auto &ExtraBits = *getTrailingObjects(

[PATCH] D126642: [Clang] NFCI: Add a new bit HasExtraBitfields to FunctionType.

2022-06-01 Thread Sander de Smalen 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 rG3ec78d9ff1b3: [Clang] NFCI: Add a new bit HasExtraBitfields 
to FunctionType. (authored by sdesmalen).

Changed prior to commit:
  https://reviews.llvm.org/D126642?vs=433140&id=433347#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126642

Files:
  clang/include/clang/AST/Type.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/Type.cpp

Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -3213,12 +3213,15 @@
   FunctionTypeBits.Variadic = epi.Variadic;
   FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
 
-  // Fill in the extra trailing bitfields if present.
-  if (hasExtraBitfields(epi.ExceptionSpec.Type)) {
+  if (epi.requiresFunctionProtoTypeExtraBitfields()) {
+FunctionTypeBits.HasExtraBitfields = true;
 auto &ExtraBits = *getTrailingObjects();
-ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
+ExtraBits = FunctionTypeExtraBitfields();
+  } else {
+FunctionTypeBits.HasExtraBitfields = false;
   }
 
+
   // Fill in the trailing argument array.
   auto *argSlot = getTrailingObjects();
   for (unsigned i = 0; i != getNumParams(); ++i) {
@@ -3229,6 +3232,9 @@
 
   // Fill in the exception type array if present.
   if (getExceptionSpecType() == EST_Dynamic) {
+auto &ExtraBits = *getTrailingObjects();
+ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
+
 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
 auto *exnSlot =
 reinterpret_cast(getTrailingObjects());
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -4451,8 +4451,7 @@
   QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
   FunctionType::ExceptionType, Expr *, FunctionDecl *,
   FunctionProtoType::ExtParameterInfo, Qualifiers>(
-  NumArgs, EPI.Variadic,
-  FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
+  NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
   ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
   EPI.ExtParameterInfos ? NumArgs : 0,
   EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
Index: clang/include/clang/AST/Type.h
===
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -1624,6 +1624,9 @@
 /// Whether this function has extended parameter information.
 unsigned HasExtParameterInfos : 1;
 
+/// Whether this function has extra bitfields for the prototype.
+unsigned HasExtraBitfields : 1;
+
 /// Whether the function is variadic.
 unsigned Variadic : 1;
 
@@ -3798,13 +3801,12 @@
 
   /// A simple holder for various uncommon bits which do not fit in
   /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
-  /// alignment of subsequent objects in TrailingObjects. You must update
-  /// hasExtraBitfields in FunctionProtoType after adding extra data here.
+  /// alignment of subsequent objects in TrailingObjects.
   struct alignas(void *) FunctionTypeExtraBitfields {
 /// The number of types in the exception specification.
 /// A whole unsigned is not needed here and according to
 /// [implimits] 8 bits would be enough here.
-unsigned NumExceptionType;
+unsigned NumExceptionType = 0;
   };
 
 protected:
@@ -3998,6 +4000,10 @@
   Result.ExceptionSpec = ESI;
   return Result;
 }
+
+bool requiresFunctionProtoTypeExtraBitfields() const {
+  return ExceptionSpec.Type == EST_Dynamic;
+}
   };
 
 private:
@@ -4088,16 +4094,13 @@
 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
   }
 
-  /// Whether the trailing FunctionTypeExtraBitfields is present.
-  static bool hasExtraBitfields(ExceptionSpecificationType EST) {
-// If the exception spec type is EST_Dynamic then we have > 0 exception
-// types and the exact number is stored in FunctionTypeExtraBitfields.
-return EST == EST_Dynamic;
-  }
-
   /// Whether the trailing FunctionTypeExtraBitfields is present.
   bool hasExtraBitfields() const {
-return hasExtraBitfields(getExceptionSpecType());
+assert((getExceptionSpecType() != EST_Dynamic ||
+FunctionTypeBits.HasExtraBitfields) &&
+   "ExtraBitfields are required for given ExceptionSpecType");
+return FunctionTypeBits.HasExtraBitfields;
+
   }
 
   bool hasExtQualifiers() const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126642: [Clang] NFCI: Add a new bit HasExtraBitfields to FunctionType.

2022-06-01 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

Thanks for the review and comments @erichkeane and @aaron.ballman!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126642

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


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

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

Hi,

I see crashes like this with this patch:

  clang: 
../../clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h:94:
 clang::ento::PointerToMemberData::PointerToMemberData(const clang::NamedDecl 
*, llvm::ImmutableList): Assertion `D' failed.

Anyhting known or familiar?

Unfortunately I don't have any reproducer to share (yet).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[PATCH] D125323: [RISCV] Add the passthru operand for RVV unmasked segment load IR intrinsics.

2022-06-01 Thread Wang Pengcheng via Phabricator via cfe-commits
pcwang-thead added a comment.

Is there an easy way to update tests? Or we need to add passthru operands 
manually? I will appreciate it if you can tell me. :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125323

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


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

2022-06-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 433351.
hokein marked 3 inline comments as done and an inline comment as not done.
hokein added a comment.

[pseudo] Support annotations in the grammar.

This patch adds annotations in the bnf grammar.

Annotations (which has a form of `[key1=value;key2=value]`) specify extensions,
which can be associated with a grammar symbol or a rule.
It provides a way to inject custom code into the general GLR parser, we will
use it for error recovery and  more freely control the reduce actions.

This patch is part of D126536 , focusing on 
the grammar level.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126536

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/lib/cxx/CMakeLists.txt
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -99,6 +99,14 @@
   EXPECT_LT(ruleFor("x"), ruleFor("_"));
 }
 
+TEST_F(GrammarTest, Annotation) {
+  build(R"bnf(
+_ := IDENTIFIER [guard=override]
+  )bnf");
+  ASSERT_TRUE(Diags.empty());
+  EXPECT_TRUE(G->lookupRule(ruleFor("_")).Guard);
+}
+
 TEST_F(GrammarTest, Diagnostics) {
   build(R"cpp(
 _ := ,_opt
@@ -110,6 +118,8 @@
 # cycle
 a := b
 b := a
+
+_ := IDENTIFIER [guard=override;unknown=value]
   )cpp");
 
   EXPECT_EQ(G->underscore(), id("_"));
@@ -120,7 +130,8 @@
  "Failed to parse 'invalid': no separator :=",
  "Token-like name IDENFIFIE is used as a nonterminal",
  "No rules for nonterminal: IDENFIFIE",
- "The grammar contains a cycle involving symbol a"));
+ "The grammar contains a cycle involving symbol a",
+ "Unknown extension key 'unknown'"));
 }
 
 TEST_F(GrammarTest, FirstAndFollowSets) {
Index: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
===
--- clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
+++ clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
@@ -47,6 +47,9 @@
 // Assemble the name->ID and ID->nonterminal name maps.
 llvm::DenseSet UniqueNonterminals;
 llvm::DenseMap SymbolIds;
+
+llvm::DenseSet UniqueExtensionValues;
+
 for (uint16_t I = 0; I < NumTerminals; ++I)
   SymbolIds.try_emplace(T->Terminals[I], tokenSymbol(tok::TokenKind(I)));
 auto Consider = [&](llvm::StringRef Name) {
@@ -55,8 +58,11 @@
 };
 for (const auto &Spec : Specs) {
   Consider(Spec.Target);
-  for (const RuleSpec::Element &Elt : Spec.Sequence)
+  for (const RuleSpec::Element &Elt : Spec.Sequence) {
 Consider(Elt.Symbol);
+for (const auto& KV : Elt.Extensions)
+   UniqueExtensionValues.insert(KV.second);
+  }
 }
 llvm::for_each(UniqueNonterminals, [&T](llvm::StringRef Name) {
   T->Nonterminals.emplace_back();
@@ -68,6 +74,15 @@
const GrammarTable::Nonterminal &R) {
   return L.Name < R.Name;
 });
+// Add an empty string for the corresponding sentinel none extension.
+T->Extensions.push_back("");
+llvm::for_each(UniqueExtensionValues, [&T](llvm::StringRef Name) {
+  T->Extensions.emplace_back();
+  T->Extensions.back() = Name.str();
+});
+llvm::sort(T->Extensions);
+assert(T->Extensions.front() == "");
+
 // Build name -> ID maps for nonterminals.
 for (SymbolID SID = 0; SID < T->Nonterminals.size(); ++SID)
   SymbolIds.try_emplace(T->Nonterminals[SID].Name, SID);
@@ -87,6 +102,8 @@
 Symbols.push_back(Lookup(Elt.Symbol));
   T->Rules.push_back(Rule(Lookup(Spec.Target), Symbols));
 }
+applyExtension(Specs, *T);
+
 assert(T->Rules.size() < (1 << RuleBits) &&
"Too many rules to fit in RuleID bits!");
 const auto &SymbolOrder = getTopologicalOrder(T.get());
@@ -164,6 +181,9 @@
 llvm::StringRef Target;
 struct Element {
   llvm::StringRef Symbol; // Name of the symbol
+  // Extensions that are associated to the sequence symbol or rule.
+  std::vector>
+  Extensions;
 };
 std::vector Sequence;
 
@@ -204,11 +224,58 @@
   Chunk = Chunk.trim();
   if (Chunk.empty())
 continue; // skip empty
+  if (Chunk.startswith("[") && Chunk.endswith("]")) {
+if (Out.Sequence.empty())
+  continue;
+parseExtension(Chunk, Out.Sequence.back().Extensions);
+continue;
+  }
 
   Out.Sequence.push_back({Chunk});
 }
 return true;
-  }

[PATCH] D126066: [clang] [WIP] Don't plumb access specifier attributes through Parser unnecessarily.

2022-06-01 Thread Martin Böhme via Phabricator via cfe-commits
mboehme abandoned this revision.
mboehme added a comment.

Apologies, I had thoroughly misunderstood how this works. Specifically, what 
wasn't clear to me is that attributes added to the access specifier are added 
to every member below it until the next access specifier. With that, all of 
this code is obviously needed.

I'm using a custom test runner setup that unfortunately happened not to run the 
tests that ended up failing.

Abandoning this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126066

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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

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

- Remove FIXME comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
  clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -320,7 +320,6 @@
   else
 llvm_unreachable("Operation not suitable for unchecked rearrangement!");
 
-  // FIXME: Can we use assume() without getting into an infinite recursion?
   if (LSym == RSym)
 return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
nonloc::ConcreteInt(RInt), ResultTy)
@@ -1190,7 +1189,6 @@
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
-  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 
@@ -1376,14 +1374,6 @@
 SVal VisitSVal(SVal V) { return V; }
   };
 
-  // A crude way of preventing this function from calling itself from 
evalBinOp.
-  static bool isReentering = false;
-  if (isReentering)
-return V;
-
-  isReentering = true;
   SVal SimplifiedV = Simplifier(State).Visit(V);
-  isReentering = false;
-
   return SimplifiedV;
 }
Index: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp
@@ -16,6 +16,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
+#include "llvm/ADT/ScopeExit.h"
 
 using namespace clang;
 using namespace ento;
@@ -46,6 +47,19 @@
 ConstraintManager::ProgramStatePair
 ConstraintManager::assumeDualImpl(ProgramStateRef &State,
   AssumeFunction &Assume) {
+
+  // Assume functions might recurse (see `reAssume` or `tryRearrange`). During
+  // the recursion the State might not change anymore, that means we reached a
+  // fixpoint.
+  // We avoid infinite recursion of assume calls by checking already visited
+  // States on the stack of assume function calls.
+  const ProgramState *RawSt = State.get();
+  if (AssumeStack.contains(RawSt))
+return {State, State};
+  AssumeStack.push(RawSt);
+  auto AssumeStackBuilder =
+  llvm::make_scope_exit([this]() { AssumeStack.pop(); });
+
   ProgramStateRef StTrue = Assume(true);
 
   if (!StTrue) {
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/Support/SaveAndRestore.h"
 #include 
 #include 
@@ -144,6 +145,20 @@
   /// but not thread-safe.
   bool NotifyAssumeClients = true;
 
+  /// A helper class to simulate the call stack of nested assume calls.
+  class AssumeStackTy {
+  public:
+void push(const ProgramState *S) { Aux.push_back(S); }
+void pop() { Aux.pop_back(); }
+bool contains(const ProgramState *S) const {
+  return llvm::find(Aux, S) != Aux.end();
+}
+
+  private:
+llvm::SmallVector Aux;
+  };
+  AssumeStackTy AssumeStack;
+
   virtual ProgramStateRef assumeInternal(ProgramStateRef state,
  DefinedSVal Cond, bool Assumption) = 
0;
 


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -320,7 +320,6 @@
   else
 llvm_unreachable("Operation not suitable for unchecked rearrangement!");
 
-  // FIXME: Can we use assume() without getting into an infinite recursion?
   if (LSym == RSym)
 return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
nonloc::ConcreteInt(RInt), ResultTy)
@@ -1190,7 +1189,6 @@
 
 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
-  V = simplifySVal(state, V);
   if (V.isUnknownOrUndef())
 return nullptr;
 
@@ -1376,14 +1374,6 @@
 SVal VisitSVal(SVal V) { 

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

2022-06-01 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

I addressed comments on the grammar part, (the remaining GLR, pseudo_gen parts 
are not covered yet), I think it would be better them into different patches, 
so that we can land the grammar bit first, then start doing the error recovery 
and guard implementation in parallel.




Comment at: clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h:110
+  Rule(SymbolID Target, llvm::ArrayRef Seq,
+   AttributeID Guard = NoneAttribute);
 

sammccall wrote:
> if this optional and rarely set, I think it's should be a constructor 
> parameter - this constructor could become unwieldy.
> 
> It also forces you to process the attributes before creating the Rule, and 
> reading the code doing it afterwards seems more natural.
I suppose you mean we should drop the Guard parameter in the constructor, yeah, 
that sounds good to me, and simplifies the BNF parsing bit.



Comment at: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp:52
+llvm::DenseSet UniqueAttrKeys;
+llvm::DenseSet UniqueAttrValues = {""};
+llvm::DenseMap AttrValueIDs;

sammccall wrote:
> why ""?
This was for the sentinel default 0 attribute value.



Comment at: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp:62
+auto ConsiderAttrValue = [&](llvm::StringRef AttrValueName) {
+  if (!AttrValueIDs.count(AttrValueName))
+UniqueAttrValues.insert(AttrValueName);

sammccall wrote:
> AttrValueIDs never seems to get populated, so I'm not sure this works.
oops, this part of code wasn't fully cleaned up. AttrValueIDs is not needed 
indeed. 



Comment at: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp:119
+
+for (const auto& AttrKeyAndValue : Elt.Attributes) {
+  switch(AttrKeyAndValue.first) {

sammccall wrote:
> sammccall wrote:
> > This doesn't seem worth diagnosing to me - it seems stylistically weird but 
> > not really a problem to put a guard wherever.
> maybe another function to pull out here?
> applyAttribute(StringRef Name, StringRef Value, AttributeID ValueID, Rule&, 
> Element&)
sounds good, move the extension bits to a dedicate `applyExtension`.



Comment at: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp:119
+
+for (const auto& AttrKeyAndValue : Elt.Attributes) {
+  switch(AttrKeyAndValue.first) {

hokein wrote:
> sammccall wrote:
> > sammccall wrote:
> > > This doesn't seem worth diagnosing to me - it seems stylistically weird 
> > > but not really a problem to put a guard wherever.
> > maybe another function to pull out here?
> > applyAttribute(StringRef Name, StringRef Value, AttributeID ValueID, Rule&, 
> > Element&)
> sounds good, move the extension bits to a dedicate `applyExtension`.
> This doesn't seem worth diagnosing to me - it seems stylistically weird but 
> not really a problem to put a guard wherever.

It is valid in syntax level, but not in semantic level, I think this is 
confusing -- the bnf parser doesn't emit any warning on this usage, just 
silently ignore them (grammar writer might think the grammar is correct, guard 
should work even putting it in the middle of the rules).

On the other hand, as you mentioned, grammar file is not user-faced, and we're 
the current authors, it seems ok to not do it (in favour of simplicity) right 
now (we might need to reconsider improving it there are new grammar 
contributors).





Comment at: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp:254
 continue; // skip empty
+  if (Chunk.startswith("[") && Chunk.endswith("]")) {
+if (Out.Sequence.empty()) {

sammccall wrote:
> Again, I don't think we should be aiming to provide nice diagnostics for each 
> possible way we could get this wrong - the grammar here is part of the 
> pseudo-parser, not user input.
fair enough, but we should keep minimal critical diagnostics at least to avoid 
shooting ourself in the foot. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126536

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


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

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

remove a left-out change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126536

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Grammar.h
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -99,6 +99,14 @@
   EXPECT_LT(ruleFor("x"), ruleFor("_"));
 }
 
+TEST_F(GrammarTest, Annotation) {
+  build(R"bnf(
+_ := IDENTIFIER [guard=override]
+  )bnf");
+  ASSERT_TRUE(Diags.empty());
+  EXPECT_TRUE(G->lookupRule(ruleFor("_")).Guard);
+}
+
 TEST_F(GrammarTest, Diagnostics) {
   build(R"cpp(
 _ := ,_opt
@@ -110,6 +118,8 @@
 # cycle
 a := b
 b := a
+
+_ := IDENTIFIER [guard=override;unknown=value]
   )cpp");
 
   EXPECT_EQ(G->underscore(), id("_"));
@@ -120,7 +130,8 @@
  "Failed to parse 'invalid': no separator :=",
  "Token-like name IDENFIFIE is used as a nonterminal",
  "No rules for nonterminal: IDENFIFIE",
- "The grammar contains a cycle involving symbol a"));
+ "The grammar contains a cycle involving symbol a",
+ "Unknown extension key 'unknown'"));
 }
 
 TEST_F(GrammarTest, FirstAndFollowSets) {
Index: clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
===
--- clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
+++ clang-tools-extra/pseudo/lib/grammar/GrammarBNF.cpp
@@ -47,6 +47,9 @@
 // Assemble the name->ID and ID->nonterminal name maps.
 llvm::DenseSet UniqueNonterminals;
 llvm::DenseMap SymbolIds;
+
+llvm::DenseSet UniqueExtensionValues;
+
 for (uint16_t I = 0; I < NumTerminals; ++I)
   SymbolIds.try_emplace(T->Terminals[I], tokenSymbol(tok::TokenKind(I)));
 auto Consider = [&](llvm::StringRef Name) {
@@ -55,8 +58,11 @@
 };
 for (const auto &Spec : Specs) {
   Consider(Spec.Target);
-  for (const RuleSpec::Element &Elt : Spec.Sequence)
+  for (const RuleSpec::Element &Elt : Spec.Sequence) {
 Consider(Elt.Symbol);
+for (const auto& KV : Elt.Extensions)
+   UniqueExtensionValues.insert(KV.second);
+  }
 }
 llvm::for_each(UniqueNonterminals, [&T](llvm::StringRef Name) {
   T->Nonterminals.emplace_back();
@@ -68,6 +74,15 @@
const GrammarTable::Nonterminal &R) {
   return L.Name < R.Name;
 });
+// Add an empty string for the corresponding sentinel none extension.
+T->Extensions.push_back("");
+llvm::for_each(UniqueExtensionValues, [&T](llvm::StringRef Name) {
+  T->Extensions.emplace_back();
+  T->Extensions.back() = Name.str();
+});
+llvm::sort(T->Extensions);
+assert(T->Extensions.front() == "");
+
 // Build name -> ID maps for nonterminals.
 for (SymbolID SID = 0; SID < T->Nonterminals.size(); ++SID)
   SymbolIds.try_emplace(T->Nonterminals[SID].Name, SID);
@@ -87,6 +102,8 @@
 Symbols.push_back(Lookup(Elt.Symbol));
   T->Rules.push_back(Rule(Lookup(Spec.Target), Symbols));
 }
+applyExtension(Specs, *T);
+
 assert(T->Rules.size() < (1 << RuleBits) &&
"Too many rules to fit in RuleID bits!");
 const auto &SymbolOrder = getTopologicalOrder(T.get());
@@ -164,6 +181,9 @@
 llvm::StringRef Target;
 struct Element {
   llvm::StringRef Symbol; // Name of the symbol
+  // Extensions that are associated to the sequence symbol or rule.
+  std::vector>
+  Extensions;
 };
 std::vector Sequence;
 
@@ -204,11 +224,58 @@
   Chunk = Chunk.trim();
   if (Chunk.empty())
 continue; // skip empty
+  if (Chunk.startswith("[") && Chunk.endswith("]")) {
+if (Out.Sequence.empty())
+  continue;
+parseExtension(Chunk, Out.Sequence.back().Extensions);
+continue;
+  }
 
   Out.Sequence.push_back({Chunk});
 }
 return true;
-  };
+  }
+
+  bool parseExtension(
+  llvm::StringRef Content,
+  std::vector> &Out) {
+assert(Content.startswith("[") && Content.endswith("]"));
+for (llvm::StringRef ExtText :
+ llvm::split(Content.drop_front().drop_back(), ';')) {
+  auto KV = ExtText.split('=');
+  if (KV.first == ExtText) { // no separator in Line
+Diagnostics.push_back(
+llvm::formatv("Failed to parse extension '{0}': no separator =",
+  ExtText)
+.str());
+retur

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

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

In D126198#3549790 , @uabelho wrote:

> Hi,
>
> I see crashes like this with this patch:
>
>   clang: 
> ../../clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h:94:
>  clang::ento::PointerToMemberData::PointerToMemberData(const clang::NamedDecl 
> *, llvm::ImmutableList): Assertion `D' failed.
>
> Anyhting known or familiar?
>
> Unfortunately I don't have any reproducer to share (yet).

Reproducer:

  clang -cc1 -analyze -analyzer-checker=core bbi-70461.C

on bbi-70461.C being

  class B{
  };
  
  class D: public B{
  };
  
  int f(int D::* pd);
  
  int test(void)
  {
int B::* pb = 0;
  
return f(pb);
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126198

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


[clang-tools-extra] 94552f0 - [pseudo] Build inc files when cxx.bnf changes.

2022-06-01 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-06-01T13:48:09+02:00
New Revision: 94552f02163a348d7b5a4001e0e719b1e617a5d2

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

LOG: [pseudo] Build inc files when cxx.bnf changes.

Add the cxx.bnf file as a dependency of custom gen commands, so that the
inc files can be rebuilt when cxx.bnf changes.

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/CMakeLists.txt 
b/clang-tools-extra/pseudo/include/CMakeLists.txt
index 3bf9709c2bed..7f64897a96f5 100644
--- a/clang-tools-extra/pseudo/include/CMakeLists.txt
+++ b/clang-tools-extra/pseudo/include/CMakeLists.txt
@@ -17,7 +17,7 @@ add_custom_command(OUTPUT ${cxx_symbols_inc}
  --emit-symbol-list
  -o ${cxx_symbols_inc}
COMMENT "Generating nonterminal symbol file for cxx grammar..."
-   DEPENDS ${pseudo_gen_target}
+   DEPENDS ${pseudo_gen_target} ${cxx_bnf}
VERBATIM)
 
 set(cxx_bnf_inc ${CMAKE_CURRENT_BINARY_DIR}/CXXBNF.inc)
@@ -27,7 +27,7 @@ add_custom_command(OUTPUT ${cxx_bnf_inc}
  --emit-grammar-content
  -o ${cxx_bnf_inc}
COMMENT "Generating bnf string file for cxx grammar..."
-   DEPENDS ${pseudo_gen_target}
+   DEPENDS ${pseudo_gen_target} ${cxx_bnf}
VERBATIM)
 
 # add_custom_command does not create a new target, we need to deine a target



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


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:140-146
   /// A flag to indicate that clients should be notified of assumptions.
   /// By default this is the case, but sometimes this needs to be restricted
   /// to avoid infinite recursions within the ConstraintManager.
   ///
   /// Note that this flag allows the ConstraintManager to be re-entrant,
   /// but not thread-safe.
   bool NotifyAssumeClients = true;

This hunk is probably also superfluous. With tracking the assume stack below, 
it should be safe to call `assume` even from `evalAssume`. But, I'd rather 
remove that in a subsequent patch, because `checkNull`s behavior is dependent 
on that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[PATCH] D126758: [clang-format] Handle do-while loops for RemoveBracesLLVM

2022-06-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126758

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


[PATCH] D116638: [clang-format] Fix ignoring JavaScriptWrapImport when ColumnWidth: 0

2022-06-01 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

@stasm thank you for taking it on, "Commandeer" the revision via the Revision 
actions.


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

https://reviews.llvm.org/D116638

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


[PATCH] D126183: Implement soft reset of the diagnostics engine.

2022-06-01 Thread Tapasweni Pathak via Phabricator via cfe-commits
tapaswenipathak updated this revision to Diff 433362.
tapaswenipathak added a comment.

this should be green. :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126183

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/test/Interpreter/error-recovery-pragmas.cpp
  clang/tools/clang-repl/ClangRepl.cpp
  clang/unittests/Basic/DiagnosticTest.cpp

Index: clang/unittests/Basic/DiagnosticTest.cpp
===
--- clang/unittests/Basic/DiagnosticTest.cpp
+++ clang/unittests/Basic/DiagnosticTest.cpp
@@ -14,6 +14,15 @@
 using namespace llvm;
 using namespace clang;
 
+void clang::DiagnosticsTestHelper(DiagnosticsEngine &diag) {
+  unsigned delayedDiagID = 0U;
+
+  EXPECT_EQ(diag.DelayedDiagID, delayedDiagID);
+  EXPECT_FALSE(diag.DiagStates.empty());
+  EXPECT_TRUE(diag.DiagStatesByLoc.empty());
+  EXPECT_TRUE(diag.DiagStateOnPushStack.empty());
+}
+
 namespace {
 
 // Check that DiagnosticErrorTrap works with SuppressAllDiagnostics.
@@ -71,6 +80,32 @@
 EXPECT_EQ(Diags.getNumWarnings(), FatalsAsError);
   }
 }
+
+// Check that soft RESET works as intended
+TEST(DiagnosticTest, softReset) {
+  DiagnosticsEngine Diags(new DiagnosticIDs(), new DiagnosticOptions,
+  new IgnoringDiagConsumer());
+
+  unsigned numWarnings = 0U, numErrors = 0U;
+
+  Diags.Reset(true);
+  // Check For ErrorOccurred and TrapNumErrorsOccurred
+  EXPECT_FALSE(Diags.hasErrorOccurred());
+  EXPECT_FALSE(Diags.hasFatalErrorOccurred());
+  EXPECT_FALSE(Diags.hasUncompilableErrorOccurred());
+  // Check for UnrecoverableErrorOccurred and TrapNumUnrecoverableErrorsOccurred
+  EXPECT_FALSE(Diags.hasUnrecoverableErrorOccurred());
+
+  EXPECT_EQ(Diags.getNumWarnings(), numWarnings);
+  EXPECT_EQ(Diags.getNumErrors(), numErrors);
+
+  // Check for private variables of DiagnosticsEngine differentiating soft reset
+  DiagnosticsTestHelper(Diags);
+
+  EXPECT_FALSE(Diags.isDiagnosticInFlight());
+  EXPECT_TRUE(Diags.isLastDiagnosticIgnored());
+}
+
 TEST(DiagnosticTest, diagnosticError) {
   DiagnosticsEngine Diags(new DiagnosticIDs(), new DiagnosticOptions,
   new IgnoringDiagConsumer());
Index: clang/tools/clang-repl/ClangRepl.cpp
===
--- clang/tools/clang-repl/ClangRepl.cpp
+++ clang/tools/clang-repl/ClangRepl.cpp
@@ -49,6 +49,23 @@
   exit(GenCrashDiag ? 70 : 1);
 }
 
+// If we are running with -verify a report has to be returned as unsuccess.
+// This is relevant especially for the test suite.
+static int checkDiagErrors(const clang::CompilerInstance *CI) {
+  unsigned Errs = CI->getDiagnostics().getClient()->getNumErrors();
+  if (CI->getDiagnosticOpts().VerifyDiagnostics) {
+// If there was an error that came from the verifier we must return 1 as
+// an exit code for the process. This will make the test fail as expected.
+clang::DiagnosticConsumer *Client = CI->getDiagnostics().getClient();
+Client->EndSourceFile();
+Errs = Client->getNumErrors();
+
+// The interpreter expects BeginSourceFile/EndSourceFiles to be balanced.
+Client->BeginSourceFile(CI->getLangOpts(), &CI->getPreprocessor());
+  }
+  return Errs ? EXIT_FAILURE : EXIT_SUCCESS;
+}
+
 llvm::ExitOnError ExitOnErr;
 int main(int argc, const char **argv) {
   ExitOnErr.setBanner("clang-repl: ");
@@ -104,5 +121,5 @@
 
   llvm::llvm_shutdown();
 
-  return 0;
+  return checkDiagErrors(Interp->getCompilerInstance());
 }
Index: clang/test/Interpreter/error-recovery-pragmas.cpp
===
--- /dev/null
+++ clang/test/Interpreter/error-recovery-pragmas.cpp
@@ -0,0 +1,7 @@
+// RUN: cat %s | clang-repl -Xcc -Xclang -Xcc -verify
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wmultichar"
+// Reset should not delete #pragmas
+error; // expected-error {{a type specifier is required for all declarations}}
+void no_diag_multichar(void) { char c = (char)'ab'; }
+quit
Index: clang/lib/Interpreter/IncrementalParser.cpp
===
--- clang/lib/Interpreter/IncrementalParser.cpp
+++ clang/lib/Interpreter/IncrementalParser.cpp
@@ -198,7 +198,7 @@
 }
 
 // FIXME: Do not reset the pragma handlers.
-Diags.Reset();
+Diags.Reset(true);
 return llvm::make_error("Parsing failed.",
std::error_code());
   }
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -130,7 +130,7 @@
   return true;
 }
 
-void DiagnosticsEngine::Reset() {
+void DiagnosticsEngine::Reset(bool soft /*=false*/) {
   ErrorOccurred = false;
   UncompilableErrorOcc

[PATCH] D126759: [clang][dataflow] Model calls returning optionals

2022-06-01 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126759

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


[PATCH] D126707: [analyzer][NFC] Move overconstrained check from reAssume to assumeDualImpl

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



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h:117-120
   // Make internal constraint solver entities friends so they can access the
   // overconstrained-related functions. We want to keep this API inaccessible
   // for Checkers.
   friend class ConstraintManager;

steakhal wrote:
> Shouldn't you remove this as well? Check the friends.
No, it is the `ConstraintManager` which checks the overconstrained property (in 
`assumeDualImpl`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126707

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


[PATCH] D126365: [git-clang-format] Stop ignoring changes for files with space in path

2022-06-01 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.

Ok, I'm not blocking this patch. I'll take a look to see whether we can add 
some tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126365

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


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

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

Thanks @NoQ!

The change in behavior is indeed what I was mentioning in the summary. After 
discussing it with a colleague, it seemed to us that pointing to a more precise 
range where the object is allocated was an improvement. I understand your point 
about pointing at something that is nearer to the assignment, but in that case, 
wouldn't it make sense to point at the whole assignment?

  id obj1 = (__bridge_transfer id)CFCreateSomething(); // 
expected-warning{{never read}}
  ^~~~

We already detect the presence of a constructor, but to skip the report 
altogether as constructors could have undetected side effects.


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

https://reviews.llvm.org/D126534

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


[clang] f951a6b - Fix potentially uninitialized memory

2022-06-01 Thread Mikhail Goncharov via cfe-commits

Author: Mikhail Goncharov
Date: 2022-06-01T15:31:37+02:00
New Revision: f951a6b2f37baf6ae832318fcca9ba4121c29529

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

LOG: Fix potentially uninitialized memory

For 
https://github.com/llvm/llvm-project/commit/7d76d6095880f34914d85d876b260cc4a4ea640d

Added: 


Modified: 
clang/tools/driver/driver.cpp

Removed: 




diff  --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index c9aee57d92cf4..d361457f8cecd 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -505,7 +505,9 @@ int main(int Argc, const char **Argv) {
   bool IsCrash = false;
   Driver::CommandStatus CommandStatus = Driver::CommandStatus::Ok;
   // Pretend the first command failed if ReproStatus is Always.
-  const Command *FailingCommand = &*C->getJobs().begin();
+  const Command *FailingCommand = nullptr;
+  if (!C->getJobs().empty())
+FailingCommand = &*C->getJobs().begin();
   if (C && !C->containsError()) {
 SmallVector, 4> FailingCommands;
 Res = TheDriver.ExecuteCompilation(*C, FailingCommands);
@@ -542,8 +544,9 @@ int main(int Argc, const char **Argv) {
   // crash, but only if we're crashing due to FORCE_CLANG_DIAGNOSTICS_CRASH.
   if (::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"))
 llvm::dbgs() << llvm::getBugReportMsg();
-  if (TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
-*C, *FailingCommand))
+  if (FailingCommand != nullptr &&
+TheDriver.maybeGenerateCompilationDiagnostics(CommandStatus, ReproLevel,
+  *C, *FailingCommand))
 Res = 1;
 
   Diags.getClient()->finish();



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


[PATCH] D126651: [clang-diff] Fix getStmtValue when dealing with wide chars

2022-06-01 Thread Kaining Zhong via Phabricator via cfe-commits
PRESIDENT810 updated this revision to Diff 433375.
PRESIDENT810 added a comment.

Refactored some code and add support of U16 & U32 characters, as well as tests 
for them.


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

https://reviews.llvm.org/D126651

Files:
  clang/lib/Tooling/ASTDiff/ASTDiff.cpp
  clang/test/Tooling/clang-diff-ast.cpp


Index: clang/test/Tooling/clang-diff-ast.cpp
===
--- clang/test/Tooling/clang-diff-ast.cpp
+++ clang/test/Tooling/clang-diff-ast.cpp
@@ -51,6 +51,30 @@
 return 0;
   }
 
+  const wchar_t *fooWide(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return L"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
+  const char16_t *fooU16(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return u"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
+  const char32_t *fooU32(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return U"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
   // CHECK: AccessSpecDecl: public(
 public:
   int not_initialized;
Index: clang/lib/Tooling/ASTDiff/ASTDiff.cpp
===
--- clang/lib/Tooling/ASTDiff/ASTDiff.cpp
+++ clang/lib/Tooling/ASTDiff/ASTDiff.cpp
@@ -16,6 +16,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/PriorityQueue.h"
+#include "llvm/Support/ConvertUTF.h"
 
 #include 
 #include 
@@ -463,8 +464,39 @@
   }
   if (auto *D = dyn_cast(S))
 return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
-  if (auto *String = dyn_cast(S))
+  if (auto *String = dyn_cast(S)) {
+if (String->isWide()) {
+  unsigned int wsize = String->getByteLength() / 
String->getCharByteWidth();
+  const auto *temp =
+  reinterpret_cast(String->getBytes().data());
+  std::wstring wstr(temp, wsize);
+  std::string str;
+  if (!convertWideToUTF8(wstr, str))
+return "";
+  return str;
+}
+if (String->isUTF16()) {
+  unsigned int usize = String->getByteLength() / 
String->getCharByteWidth();
+  const auto *temp =
+  reinterpret_cast(String->getBytes().data());
+  ArrayRef u16str(temp, usize);
+  std::string str;
+  if (!convertUTF16ToUTF8String(u16str, str))
+return "";
+  return str;
+}
+if (String->isUTF32()) {
+  unsigned int usize = String->getByteLength() / 
String->getCharByteWidth();
+  const auto *temp =
+  reinterpret_cast(String->getBytes().data());
+  ArrayRef u32str(temp, usize);
+  std::string str;
+  if (!convertUTF32ToUTF8String(u32str, str))
+return "";
+  return str;
+}
 return std::string(String->getString());
+  }
   if (auto *B = dyn_cast(S))
 return B->getValue() ? "true" : "false";
   return "";


Index: clang/test/Tooling/clang-diff-ast.cpp
===
--- clang/test/Tooling/clang-diff-ast.cpp
+++ clang/test/Tooling/clang-diff-ast.cpp
@@ -51,6 +51,30 @@
 return 0;
   }
 
+  const wchar_t *fooWide(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return L"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
+  const char16_t *fooU16(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return u"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
+  const char32_t *fooU32(int i) {
+if (i == 0)
+  // CHECK: StringLiteral: foo(
+  return U"foo";
+// CHECK-NOT: ImplicitCastExpr
+return 0;
+  }
+
   // CHECK: AccessSpecDecl: public(
 public:
   int not_initialized;
Index: clang/lib/Tooling/ASTDiff/ASTDiff.cpp
===
--- clang/lib/Tooling/ASTDiff/ASTDiff.cpp
+++ clang/lib/Tooling/ASTDiff/ASTDiff.cpp
@@ -16,6 +16,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/PriorityQueue.h"
+#include "llvm/Support/ConvertUTF.h"
 
 #include 
 #include 
@@ -463,8 +464,39 @@
   }
   if (auto *D = dyn_cast(S))
 return getRelativeName(D->getDecl(), getEnclosingDeclContext(AST, S));
-  if (auto *String = dyn_cast(S))
+  if (auto *String = dyn_cast(S)) {
+if (String->isWide()) {
+  unsigned int wsize = String->getByteLength() / String->getCharByteWidth();
+  const auto *temp =
+  reinterpret_cast(String->getBytes().data());
+  std::wstring wstr(temp, wsize);
+  std::string str;
+  if (!convertWideToUTF8(wstr, str))
+return "";
+  return str;
+}
+if (String->isUTF16()) {
+  unsigned int usize = String->getByteLength() / String->getCharByteWidth();
+  const auto *temp =
+  reinterpret_cast(String->getBytes().data());
+  ArrayRef u16str(temp, usize);
+  std::string str;
+  if (!convertUTF16ToUTF8String

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

2022-06-01 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn added a comment.

>> On targets that support static rounding mode (like RISCV) dynamic and 
>> constant rounding modes may be different and the behavior changes if default 
>> mode is replaced by dynamic.
>
> Whether a target supports static rounding modes on floating-point 
> instructions is completely irrelevant.  The user-visible behavior must be the 
> same either way.  If a target doesn't have specialized instructions, the code 
> generator can save/restore the rounding mode.  This should be transparent to 
> the user; the user can't read the rounding mode in between the save and 
> restore.  (We already do this sort of rounding mode manipulation on x86, to 
> implement float-to-int conversion on targets without SSE.)

The rounding mode argument to the constrained intrinsic is a hint; it tells the 
intrinsic what rounding mode has been set via the normal rounding mode changing 
mechanism. Constrained intrinsics don't change the rounding mode. I guess we 
could weaken that by adding "... except if absolutely required" to account for 
the float-to-int sans SSE case, but the principle applies.

Because of the requirement that the rounding mode be changed already, I don't 
see how instructions with static rounding modes are generally interesting. 
Perhaps a target will learn to recognize that a sequence of instructions can 
use the static rounding in the instructions and elide a change of rounding mode 
around the sequence? I don't know how common that would be in practice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D62574: Add support for target-configurable address spaces.

2022-06-01 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added a comment.

I've been away from LLVM development for a while, and sadly this patch has 
languished a bit.

I don't think there were any strong objections to its inclusion, though. If 
there is still interest in reviewing this, I could try to rebase the patch (or 
something resembling it) onto the latest main and see if it still works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D62574

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


[PATCH] D75277: [WebAssembly] Remove restriction on main name mangling

2022-06-01 Thread Sam Clegg via Phabricator via cfe-commits
sbc100 updated this revision to Diff 433386.
sbc100 added a comment.

- feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D75277

Files:
  clang/lib/AST/Mangle.cpp
  clang/lib/CodeGen/CodeGenModule.cpp


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -555,10 +555,8 @@
 CodeGenFunction(*this).EmitCfiCheckStub();
   }
   emitAtAvailableLinkGuard();
-  if (Context.getTargetInfo().getTriple().isWasm() &&
-  !Context.getTargetInfo().getTriple().isOSEmscripten()) {
+  if (Context.getTargetInfo().getTriple().isWasm())
 EmitMainVoidAlias();
-  }
 
   if (getTriple().isAMDGPU()) {
 // Emit reference of __amdgpu_device_library_preserve_asan_functions to
@@ -6357,8 +6355,10 @@
   // new-style no-argument main is in used.
   if (llvm::Function *F = getModule().getFunction("main")) {
 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
-F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
-  addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
+
F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
+  auto *GA = llvm::GlobalAlias::create("__main_void", F);
+  GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
+}
   }
 }
 
Index: clang/lib/AST/Mangle.cpp
===
--- clang/lib/AST/Mangle.cpp
+++ clang/lib/AST/Mangle.cpp
@@ -70,9 +70,7 @@
 
   // On wasm, the argc/argv form of "main" is renamed so that the startup code
   // can call it with the correct function signature.
-  // On Emscripten, users may be exporting "main" and expecting to call it
-  // themselves, so we can't mangle it.
-  if (Triple.isWasm() && !Triple.isOSEmscripten())
+  if (Triple.isWasm())
 if (const FunctionDecl *FD = dyn_cast(ND))
   if (FD->isMain() && FD->hasPrototype() && FD->param_size() == 2)
 return CCM_WasmMainArgcArgv;


Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -555,10 +555,8 @@
 CodeGenFunction(*this).EmitCfiCheckStub();
   }
   emitAtAvailableLinkGuard();
-  if (Context.getTargetInfo().getTriple().isWasm() &&
-  !Context.getTargetInfo().getTriple().isOSEmscripten()) {
+  if (Context.getTargetInfo().getTriple().isWasm())
 EmitMainVoidAlias();
-  }
 
   if (getTriple().isAMDGPU()) {
 // Emit reference of __amdgpu_device_library_preserve_asan_functions to
@@ -6357,8 +6355,10 @@
   // new-style no-argument main is in used.
   if (llvm::Function *F = getModule().getFunction("main")) {
 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
-F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
-  addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
+F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) {
+  auto *GA = llvm::GlobalAlias::create("__main_void", F);
+  GA->setVisibility(llvm::GlobalValue::HiddenVisibility);
+}
   }
 }
 
Index: clang/lib/AST/Mangle.cpp
===
--- clang/lib/AST/Mangle.cpp
+++ clang/lib/AST/Mangle.cpp
@@ -70,9 +70,7 @@
 
   // On wasm, the argc/argv form of "main" is renamed so that the startup code
   // can call it with the correct function signature.
-  // On Emscripten, users may be exporting "main" and expecting to call it
-  // themselves, so we can't mangle it.
-  if (Triple.isWasm() && !Triple.isOSEmscripten())
+  if (Triple.isWasm())
 if (const FunctionDecl *FD = dyn_cast(ND))
   if (FD->isMain() && FD->hasPrototype() && FD->param_size() == 2)
 return CCM_WasmMainArgcArgv;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126560: [analyzer][NFC] SimpleSValBuilder simplification: Remove superfluous workaround code and track Assume call stack rather

2022-06-01 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:21
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/Support/SaveAndRestore.h"

Unused.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:140-146
   /// A flag to indicate that clients should be notified of assumptions.
   /// By default this is the case, but sometimes this needs to be restricted
   /// to avoid infinite recursions within the ConstraintManager.
   ///
   /// Note that this flag allows the ConstraintManager to be re-entrant,
   /// but not thread-safe.
   bool NotifyAssumeClients = true;

martong wrote:
> This hunk is probably also superfluous. With tracking the assume stack below, 
> it should be safe to call `assume` even from `evalAssume`. But, I'd rather 
> remove that in a subsequent patch, because `checkNull`s behavior is dependent 
> on that.
Oh, I haven't thought about that. Thanks. Feel free to do in a followup!



Comment at: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h:154
+bool contains(const ProgramState *S) const {
+  return llvm::find(Aux, S) != Aux.end();
+}

Use `llvm::is_contained()` instead.



Comment at: clang/lib/StaticAnalyzer/Core/ConstraintManager.cpp:60
+  AssumeStack.push(RawSt);
+  auto AssumeStackBuilder =
+  llvm::make_scope_exit([this]() { AssumeStack.pop(); });

Don't we call these 'Guards'?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126560

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


[clang] 3a07280 - [analyzer] Fix wrong annotation of PointerToMemberData

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

Author: Balazs Benics
Date: 2022-06-01T16:12:54+02:00
New Revision: 3a07280290564e294c957c94c918a6680714b417

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

LOG: [analyzer] Fix wrong annotation of PointerToMemberData

Unfortunately I don't have a reproducer for this.
Reported by @mikaelholmen!

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

Added: 


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

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
index 457247bcdf553..59bfbe3dea77b 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
@@ -90,9 +90,7 @@ class PointerToMemberData : public llvm::FoldingSetNode {
 public:
   PointerToMemberData(const NamedDecl *D,
   llvm::ImmutableList L)
-  : D(D), L(L) {
-assert(D);
-  }
+  : D(D), L(L) {}
 
   using iterator = llvm::ImmutableList::iterator;
 
@@ -104,7 +102,7 @@ class PointerToMemberData : public llvm::FoldingSetNode {
 
   void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, D, L); }
 
-  LLVM_ATTRIBUTE_RETURNS_NONNULL
+  /// It might return null.
   const NamedDecl *getDeclaratorDecl() const { return D; }
 
   llvm::ImmutableList getCXXBaseList() const {



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


[PATCH] D126719: [clang-cl] Add support for /kernel

2022-06-01 Thread Stephen Long via Phabricator via cfe-commits
steplong updated this revision to Diff 433389.
steplong added a comment.
Herald added a subscriber: ormris.

- Reject /kernel and /arch combinations for x64 and x86


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126719

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/OSTargets.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cl-zc.cpp

Index: clang/test/Driver/cl-zc.cpp
===
--- clang/test/Driver/cl-zc.cpp
+++ clang/test/Driver/cl-zc.cpp
@@ -24,6 +24,28 @@
 // RUN: %clang_cl /c /std:c++17 -### /Zc:alignedNew- -- %s 2>&1 | FileCheck -check-prefix=ALIGNED-NEW-OFF %s
 // ALIGNED-NEW-OFF-NOT: "-faligned-allocation"
 
+// RUN: %clang_cl /c -### /kernel -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-NO-RTTI,KERNEL-NO-EXCEPTIONS %s
+// KERNEL-NO-RTTI: "-fno-rtti"
+// KERNEL-NO-EXCEPTIONS-NOT: "-fcxx-exceptions" "-fexceptions"
+
+// RUN: %clang_cl /c -### --target=i686-pc-windows-msvc /kernel /arch:SSE -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-SSE %s
+// RUN: %clang_cl /c -### --target=i686-pc-windows-msvc /kernel /arch:SSE2 -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-SSE2 %s
+// RUN: %clang_cl /c -### --target=i686-pc-windows-msvc /kernel /arch:AVX -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-AVX %s
+// RUN: %clang_cl /c -### --target=i686-pc-windows-msvc /kernel /arch:AVX2 -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-AVX2 %s
+// RUN: %clang_cl /c -### --target=i686-pc-windows-msvc /kernel /arch:AVX512 -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-AVX512 %s
+// KERNEL-SSE: error: invalid argument '/arch:SSE' not allowed with '/kernel'
+// KERNEL-SSE2: error: invalid argument '/arch:SSE2' not allowed with '/kernel'
+// KERNEL-AVX: error: invalid argument '/arch:AVX' not allowed with '/kernel'
+// KERNEL-AVX2: error: invalid argument '/arch:AVX2' not allowed with '/kernel'
+// KERNEL-AVX512: error: invalid argument '/arch:AVX512' not allowed with '/kernel'
+
+// RUN: %clang_cl /c -### --target=x86_64-pc-windows-msvc /kernel /arch:AVX -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-X64-AVX %s
+// RUN: %clang_cl /c -### --target=x86_64-pc-windows-msvc /kernel /arch:AVX2 -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-X64-AVX2 %s
+// RUN: %clang_cl /c -### --target=x86_64-pc-windows-msvc /kernel /arch:AVX512 -- %s 2>&1 | FileCheck -check-prefixes=KERNEL-X64-AVX512 %s
+// KERNEL-X64-AVX: error: invalid argument '/arch:AVX' not allowed with '/kernel'
+// KERNEL-X64-AVX2: error: invalid argument '/arch:AVX2' not allowed with '/kernel'
+// KERNEL-X64-AVX512: error: invalid argument '/arch:AVX512' not allowed with '/kernel'
+
 // RUN: %clang_cl /c -### -- %s 2>&1 | FileCheck -check-prefix=STRICTSTRINGS-DEFAULT %s
 // STRICTSTRINGS-DEFAULT-NOT: -Werror=c++11-compat-deprecated-writable-strings
 // RUN: %clang_cl /c -### /Zc:strictStrings -- %s 2>&1 | FileCheck -check-prefix=STRICTSTRINGS-ON %s
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7458,6 +7458,12 @@
 EH.NoUnwindC = true;
   }
 
+  if (Args.hasArg(options::OPT__SLASH_kernel)) {
+EH.Synch = false;
+EH.NoUnwindC = false;
+EH.Asynch = false;
+  }
+
   return EH;
 }
 
@@ -7602,6 +7608,28 @@
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT__SLASH_kernel)) {
+   llvm::Triple::ArchType Arch = getToolChain().getArch();
+   std::vector Values =
+   Args.getAllArgValues(options::OPT__SLASH_arch);
+   if (!Values.empty()) {
+ std::vector UnsupportedArches;
+ if (Arch == llvm::Triple::x86)
+   UnsupportedArches = {"SSE", "SSE2", "AVX", "AVX2", "AVX512"};
+ else if (Arch == llvm::Triple::x86_64)
+   UnsupportedArches = {"AVX", "AVX2", "AVX512"};
+
+ for (auto &UnsupportedArch : UnsupportedArches) {
+   auto It = find(Values.begin(), Values.end(), UnsupportedArch);
+   if (It != Values.end())
+ D.Diag(diag::err_drv_argument_not_allowed_with)
+ << std::string("/arch:").append(UnsupportedArch) << "/kernel";
+ }
+   }
+
+   CmdArgs.push_back("-fno-rtti");
+ }
+
   Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
   Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
   if (MostGeneralArg && BestCaseArg)
@@ -7671,6 +7699,9 @@
 CmdArgs.push_back("msvc");
   }
 
+  if (Args.hasArg(options::OPT__SLASH_kernel))
+CmdArgs.push_back("-fms-kernel");
+
   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
 StringRef GuardArgs = A->getValue();
 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
Index: clang/lib/Basic/Targets/OSTargets.cpp
===
--- clang/lib/Basic/Targets/OSTargets.cp

[PATCH] D126779: [analyzer] Fix assertion in simplifySymbolCast

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

Added a new test code that fails an assertion in the baseline.
That is because `getAPSIntType` works only with integral types.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126779

Files:
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/test/Analysis/produce-symbolcast_x86.cpp


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((double) ((reg_$0) / 30))}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((double) 
((reg_$0) / 30)))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) 
((double) ((reg_$0) / 30}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1078,6 +1078,11 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support cast from non-integers.
+  // E.g (char)(double)(double x) -> (char)(double x)
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory &BVF = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);


Index: clang/test/Analysis/produce-symbolcast_x86.cpp
===
--- clang/test/Analysis/produce-symbolcast_x86.cpp
+++ clang/test/Analysis/produce-symbolcast_x86.cpp
@@ -11,6 +11,15 @@
 template 
 void clang_analyzer_dump(T);
 
+void test_double(int n) {
+  double D = n / 30;
+  clang_analyzer_dump(D); // expected-warning{{(double) ((double) ((reg_$0) / 30))}}
+  char C = D;
+  clang_analyzer_dump(C); // expected-warning{{(char) ((double) ((double) ((reg_$0) / 30)))}}
+  int I = C; // assertion should not fail here!
+  clang_analyzer_dump(I); // expected-warning{{(int) ((char) ((double) ((double) ((reg_$0) / 30}}
+}
+
 void test_schar(schar x) {
   clang_analyzer_dump(x); // expected-warning{{reg_$0}}
 
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -1078,6 +1078,11 @@
   SymbolRef RootSym = cast(SE)->getOperand();
   QualType RT = RootSym->getType().getCanonicalType();
 
+  // FIXME support cast from non-integers.
+  // E.g (char)(double)(double x) -> (char)(double x)
+  if (!RT->isIntegralOrEnumerationType())
+return makeNonLoc(SE, T, CastTy);
+
   BasicValueFactory &BVF = getBasicValueFactory();
   APSIntType CTy = BVF.getAPSIntType(CastTy);
   APSIntType TTy = BVF.getAPSIntType(T);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126664: Expand definition deprecation warning to include constexpr statements.

2022-06-01 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google updated this revision to Diff 433395.
luken-google added a comment.

Add release note.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126664

Files:
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126664: Expand definition deprecation warning to include constexpr statements.

2022-06-01 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google added a comment.

Thanks for the review! I do need someone to commit on my behalf. Please commit 
with name "Luke Nihlen" and email address "lu...@google.com".


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126664

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


[PATCH] D126707: [analyzer][NFC] Move overconstrained check from reAssume to assumeDualImpl

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

In D126707#3549677 , @steakhal wrote:

> LGTM; measure performance implications.

Seems like there are no implications (or within the error margin).

F23278565: image.png 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126707

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


[PATCH] D126780: [clang-tidy] `bugprone-use-after-move`: Fix handling of moves in lambda captures

2022-06-01 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Previously, we were treating a move in the lambda capture as if it happened
within the body of the lambda, not within the function that defines the lambda.

This fixes the same bug as https://reviews.llvm.org/D119165 (which it appears
may have been abandoned by the author?) but does so more simply.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126780

Files:
  clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -416,6 +416,13 @@
 auto lambda = [&]() { a.foo(); };
 std::move(a);
   }
+  {
+A a;
+auto lambda = [a = std::move(a)] { a.foo(); };
+a.foo();
+// CHECK-NOTES: [[@LINE-1]]:5: warning: 'a' used after it was moved
+// CHECK-NOTES: [[@LINE-3]]:24: note: move occurred here
+  }
 }
 
 // Use-after-moves are detected in uninstantiated templates if the moved type
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -400,7 +400,8 @@
   auto CallMoveMatcher =
   callExpr(callee(functionDecl(hasName("::std::move"))), 
argumentCountIs(1),
hasArgument(0, declRefExpr().bind("arg")),
-   anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")),
+   anyOf(hasAncestor(compoundStmt(
+ hasParent(lambdaExpr().bind("containing-lambda",
  hasAncestor(functionDecl().bind("containing-func"))),
unless(inDecltypeOrTemplateArg()),
// try_emplace is a common maybe-moving function that returns a


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -416,6 +416,13 @@
 auto lambda = [&]() { a.foo(); };
 std::move(a);
   }
+  {
+A a;
+auto lambda = [a = std::move(a)] { a.foo(); };
+a.foo();
+// CHECK-NOTES: [[@LINE-1]]:5: warning: 'a' used after it was moved
+// CHECK-NOTES: [[@LINE-3]]:24: note: move occurred here
+  }
 }
 
 // Use-after-moves are detected in uninstantiated templates if the moved type
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -400,7 +400,8 @@
   auto CallMoveMatcher =
   callExpr(callee(functionDecl(hasName("::std::move"))), argumentCountIs(1),
hasArgument(0, declRefExpr().bind("arg")),
-   anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")),
+   anyOf(hasAncestor(compoundStmt(
+ hasParent(lambdaExpr().bind("containing-lambda",
  hasAncestor(functionDecl().bind("containing-func"))),
unless(inDecltypeOrTemplateArg()),
// try_emplace is a common maybe-moving function that returns a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D119165: [clang-tidy] Add processing lambda captures at bugprone-use-after-move check

2022-06-01 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added inline comments.
Herald added a project: All.



Comment at: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp:403
hasArgument(0, declRefExpr().bind("arg")),
-   anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")),
- hasAncestor(functionDecl().bind("containing-func"))),

mboehme wrote:
> I believe this can be done more simply.
> 
> IIUC, the root of the problem is that a std::move() in a lambda capture is 
> being associated with the lambda, when in fact it should be associated with 
> the function that contains the lambda.
> 
> This is because the `hasAncestor(lambdaExpr())` matches not just a 
> `std::move` inside the body of the lambda, but also in captures.
> 
> I believe this can be solved simply by changing this line so that it only 
> matches a `std::move` inside the body of the lambda, i.e. something like this:
> 
> ```
> hasAncestor(compoundStmt(hasParent(lambdaExpr().bind("containing-lambda"
> ```
> 
> This would then no longer match a `std::move` in a capture; the existing 
> logic would instead associate it with the function that contains the lambda.
> ```
It appears that this works:

https://reviews.llvm.org/D126780


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119165

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


[PATCH] D126781: [CodeGen] Correctly handle weak symbols in the codegen

2022-06-01 Thread Jun Zhang via Phabricator via cfe-commits
junaire created this revision.
junaire added reviewers: v.g.vassilev, rjmccall.
Herald added a project: All.
junaire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann 
Signed-off-by: Jun Zhang 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D126781

Files:
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/ModuleBuilder.cpp
  clang/unittests/Interpreter/InterpreterTest.cpp

Index: clang/unittests/Interpreter/InterpreterTest.cpp
===
--- clang/unittests/Interpreter/InterpreterTest.cpp
+++ clang/unittests/Interpreter/InterpreterTest.cpp
@@ -248,4 +248,22 @@
   EXPECT_EQ(42, fn(NewA));
 }
 
+TEST(InterpreterTest, InlineDecls) {
+  Args ExtraArgs = {"-Xclang", "-diagnostic-log-file", "-Xclang", "-"};
+
+  // Create the diagnostic engine with unowned consumer.
+  std::string DiagnosticOutput;
+  llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput);
+  auto DiagPrinter = std::make_unique(
+  DiagnosticsOS, new DiagnosticOptions());
+
+  auto Interp = createInterpreter(ExtraArgs, DiagPrinter.get());
+
+  auto R1 = Interp->Parse("inline int foo() { return 42;}");
+  EXPECT_TRUE(!!R1);
+
+  auto R2 = Interp->Parse("int x = foo()");
+  EXPECT_TRUE(!!R2);
+}
+
 } // end anonymous namespace
Index: clang/lib/CodeGen/ModuleBuilder.cpp
===
--- clang/lib/CodeGen/ModuleBuilder.cpp
+++ clang/lib/CodeGen/ModuleBuilder.cpp
@@ -133,8 +133,38 @@
 llvm::Module *StartModule(llvm::StringRef ModuleName,
   llvm::LLVMContext &C) {
   assert(!M && "Replacing existing Module?");
+
+  assert(OldBuilder->EmittedDeferredDecls.empty() &&
+ "Still have (unmerged) EmittedDeferredDecls deferred decls");
+
+  std::unique_ptr OldBuilder;
+  OldBuilder.swap(Builder);
+
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
   Initialize(*Ctx);
+
+  assert(OldBuilder->getDeferredDeclsToEmit().empty() &&
+ "Should have emitted all decls deferred to emit.");
+  assert(Builder->DeferredDecls.empty() &&
+ "Newly created module should not have deferred decls");
+
+  Builder->getDeferredDecls().swap(OldBuilder->getDeferredDecls());
+
+  assert(Builder->getDeferredVTables().empty() &&
+ "Newly created module should not have deferred vtables");
+
+  Builder->getDeferredVTables().swap(OldBuilder->getDeferredVTables());
+
+  assert(Builder->getMangledDeclNames().empty() &&
+ "Newly created module should not have mangled decl names");
+  assert(Builder->getManglings().empty() &&
+ "Newly created module should not have manglings");
+
+  Builder->getManglings() = std::move(OldBuilder->getManglings());
+
+  assert(OldBuilder->WeakRefReferences.empty() &&
+ "Not all WeakRefRefs have been applied");
+
   return M.get();
 }
 
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -339,11 +339,30 @@
   /// yet.
   llvm::DenseMap DeferredDecls;
 
+  /// Decls that were DeferredDecls and have now been emitted.
+  llvm::DenseMap EmittedDeferredDecls;
+
+  void addEmittedDeferredDecl(GlobalDecl GD) {
+bool IsAFunction = isa(GD.getDecl());
+const VarDecl *VD = IsAFunction ? nullptr : dyn_cast(GD.getDecl());
+assert((IsAFunction || VD) && "Unexpected Decl type!");
+llvm::GlobalValue::LinkageTypes L =
+IsAFunction
+? getFunctionLinkage(GD)
+: getLLVMLinkageVarDefinition(
+  VD, isTypeConstant(VD->getType(), /*ExcludeCtor=*/false));
+if (llvm::GlobalValue::isLinkOnceLinkage(L) ||
+llvm::GlobalValue::isWeakLinkage(L)) {
+  EmittedDeferredDecls[getMangledName(GD)] = GD;
+}
+  }
+
   /// This is a list of deferred decls which we have seen that *are* actually
   /// referenced. These get code generated when the module is done.
   std::vector DeferredDeclsToEmit;
   void addDeferredDeclToEmit(GlobalDecl GD) {
 DeferredDeclsToEmit.emplace_back(GD);
+addEmittedDeferredDecl(GD);
   }
 
   /// List of alias we have emitted. Used to make sure that what they point to
@@ -1477,6 +1496,34 @@
   void printPostfixForExternalizedDecl(llvm::raw_ostream &OS,
const Decl

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

2022-06-01 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam updated this revision to Diff 433401.
saiislam added a comment.

Added the multi-entry logic in libomptarget. Yet to move the image 
compatibility testing to plugin.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124525

Files:
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.cpp
  clang/tools/clang-linker-wrapper/OffloadWrapper.h
  clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
  openmp/libomptarget/include/omptarget.h
  openmp/libomptarget/include/rtl.h
  openmp/libomptarget/src/exports
  openmp/libomptarget/src/interface.cpp
  openmp/libomptarget/src/rtl.cpp

Index: openmp/libomptarget/src/rtl.cpp
===
--- openmp/libomptarget/src/rtl.cpp
+++ openmp/libomptarget/src/rtl.cpp
@@ -13,6 +13,7 @@
 #include "rtl.h"
 #include "device.h"
 #include "private.h"
+//#include "llvm/OffloadArch/OffloadArch.h"
 
 #include 
 #include 
@@ -20,6 +21,8 @@
 #include 
 #include 
 #include 
+// It's strange we do not have llvm tools for openmp runtime, so we use stat
+#include 
 
 // List of all plugins that can support offloading.
 static const char *RTLNames[] = {
@@ -351,18 +354,127 @@
 initRTLonce(R);
 }
 
+/// Query runtime capabilities of this system by calling offload-arch -c
+/// offload_arch_output_buffer is persistant storage returned by this
+/// __tgt_get_active_offload_env.
+static void
+__tgt_get_active_offload_env(__tgt_active_offload_env *active_env,
+ char *offload_arch_output_buffer,
+ size_t offload_arch_output_buffer_size) {
+
+  // If OFFLOAD_ARCH_OVERRIDE env varible is present then use its value instead
+  // of querying it using LLVMOffloadArch library.
+  if (char *OffloadArchEnvVar = getenv("OFFLOAD_ARCH_OVERRIDE")) {
+if (OffloadArchEnvVar) {
+  active_env->capabilities = OffloadArchEnvVar;
+  return;
+}
+  }
+  // Qget runtime capabilities of this system with libLLVMOffloadArch.a
+  // if (int rc = getRuntimeCapabilities(offload_arch_output_buffer,
+  // offload_arch_output_buffer_size))
+  //   return;
+  // active_env->capabilities = offload_arch_output_buffer;
+  // return;
+}
+
+std::vector _splitstrings(char *input, const char *sep) {
+  std::vector split_strings;
+  std::string s(input);
+  std::string delimiter(sep);
+  size_t pos = 0;
+  while ((pos = s.find(delimiter)) != std::string::npos) {
+if (pos != 0)
+  split_strings.push_back(s.substr(0, pos));
+s.erase(0, pos + delimiter.length());
+  }
+  if (s.length() > 1)
+split_strings.push_back(s.substr(0, s.length()));
+  return split_strings;
+}
+
+static bool _ImageIsCompatibleWithEnv(__tgt_image_info *image_info,
+  __tgt_active_offload_env *active_env) {
+  // get_image_info will return null if no image information was registered.
+  // If no image information, assume application built with old compiler and
+  // check each image.
+  if (!(image_info && image_info->image_info_version == 1))
+return true;
+
+  if (!active_env->capabilities)
+return false;
+
+  // Each runtime requirement for the compiled image is stored in
+  // the image_info->offload_arch (TargetID) string.
+  // Each runtime capability obtained from "offload-arch -c" is stored in
+  // actvie_env->capabilities (TargetID) string.
+  // If every requirement has a matching capability, then the image
+  // is compatible with active environment
+
+  std::vector reqs = _splitstrings(image_info->offload_arch, ":");
+  std::vector caps = _splitstrings(active_env->capabilities, ":");
+
+  bool is_compatible = true;
+  for (auto req : reqs) {
+bool missing_capability = true;
+for (auto capability : caps)
+  if (capability == req)
+missing_capability = false;
+if (missing_capability) {
+  DP("Image requires %s but runtime capability %s is missing.\n",
+ image_info->offload_arch, req.c_str());
+  is_compatible = false;
+}
+  }
+  return is_compatible;
+}
+
 void RTLsTy::RegisterLib(__tgt_bin_desc *desc) {
+
+  __tgt_device_image *newDeviceImages =
+  new __tgt_device_image[desc->NumDeviceImages];
+
+  for (int32_t i = 0; i < desc->NumDeviceImages; ++i) {
+newDeviceImages[i].EntriesBegin = desc->DeviceImages[i].EntriesBegin;
+newDeviceImages[i].EntriesEnd = desc->DeviceImages[i].EntriesEnd;
+newDeviceImages[i].ImageStart = desc->DeviceImages[i].ImageStart;
+newDeviceImages[i].ImageEnd = desc->DeviceImages[i].ImageEnd;
+newDeviceImages[i].ImageInfo = nullptr;
+// TODO : delete(desc->DeviceImages[i]);
+  }
+
+  desc->DeviceImages = static_cast<__tgt_device_image *>(newDeviceImages);
+
+  this->RegisterLibV2(desc);
+}
+
+#define MAX_CAPS_STR_SIZE 1024
+void RTLsTy::RegisterLibV2(__tgt_bin_desc *desc) {
+
+  // Get the c

[PATCH] D126664: Expand definition deprecation warning to include constexpr statements.

2022-06-01 Thread Luke Nihlen via Phabricator via cfe-commits
luken-google updated this revision to Diff 433404.
luken-google added a comment.

Squash commit to include original changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126664

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CXX/basic/basic.def/p2.cpp


Index: clang/test/CXX/basic/basic.def/p2.cpp
===
--- clang/test/CXX/basic/basic.def/p2.cpp
+++ clang/test/CXX/basic/basic.def/p2.cpp
@@ -5,4 +5,9 @@
 static constexpr int n = 0;
   };
   const int A::n; // expected-warning {{deprecated}}
+
+  struct B {
+static constexpr int m = 0;
+  };
+  constexpr int B::m; // expected-warning {{deprecated}}
 }
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -4508,15 +4508,15 @@
   }
 
   // C++ doesn't have tentative definitions, so go right ahead and check here.
-  if (getLangOpts().CPlusPlus &&
-  New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  if (getLangOpts().CPlusPlus) {
 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
 Old->getCanonicalDecl()->isConstexpr()) {
   // This definition won't be a definition any more once it's been merged.
   Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
-} else if (VarDecl *Def = Old->getDefinition()) {
-  if (checkVarDeclRedefinition(Def, New))
+} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  VarDecl *Def = Old->getDefinition();
+  if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/test/CXX/basic/basic.def/p2.cpp
===
--- clang/test/CXX/basic/basic.def/p2.cpp
+++ clang/test/CXX/basic/basic.def/p2.cpp
@@ -5,4 +5,9 @@
 static constexpr int n = 0;
   };
   const int A::n; // expected-warning {{deprecated}}
+
+  struct B {
+static constexpr int m = 0;
+  };
+  constexpr int B::m; // expected-warning {{deprecated}}
 }
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -4508,15 +4508,15 @@
   }
 
   // C++ doesn't have tentative definitions, so go right ahead and check here.
-  if (getLangOpts().CPlusPlus &&
-  New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  if (getLangOpts().CPlusPlus) {
 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
 Old->getCanonicalDecl()->isConstexpr()) {
   // This definition won't be a definition any more once it's been merged.
   Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
-} else if (VarDecl *Def = Old->getDefinition()) {
-  if (checkVarDeclRedefinition(Def, New))
+} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  VarDecl *Def = Old->getDefinition();
+  if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125323: [RISCV] Add the passthru operand for RVV unmasked segment load IR intrinsics.

2022-06-01 Thread Zakk Chen via Phabricator via cfe-commits
khchen added a comment.

In D125323#3549794 , @pcwang-thead 
wrote:

> Is there an easy way to update tests? Or we need to add passthru operands 
> manually? I will appreciate it if you can tell me. :-)

use sed to do replacement.
ex.

  #!/bin/bash
  set -x
  
  for var in "$@"
  do
sed -i 's/declare {\([^,]\+\),[^,]\+} \(.*\)(\([0-9a-z*]\+\)/declare 
{\1,\1} \2(\1,\1, \3/g' $var
sed -i 's/declare {\([^,]\+\),[^,]\+,[^,]\+} \(.*\)(\([0-9a-z*]\+\)/declare 
{\1,\1,\1} \2(\1,\1,\1, \3/g' $var
sed -i 's/declare {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/declare {\1,\1,\1,\1} \2(\1,\1,\1,\1, \3/g' $var
sed -i 's/declare {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/declare {\1,\1,\1,\1,\1} \2(\1,\1,\1,\1,\1, \3/g' $var
sed -i 's/declare {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/declare {\1,\1,\1,\1,\1,\1} \2(\1,\1,\1,\1,\1,\1, \3/g' 
$var
sed -i 's/declare {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/declare {\1,\1,\1,\1,\1,\1,\1} \2(\1,\1,\1,\1,\1,\1,\1, 
\3/g' $var
sed -i 's/declare 
{\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/declare {\1,\1,\1,\1,\1,\1,\1,\1} 
\2(\1,\1,\1,\1,\1,\1,\1,\1, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+} \(.*\)(\([0-9a-z*]\+\)/call {\1,\1} 
\2(\1 undef, \1 undef, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+,[^,]\+} \(.*\)(\([0-9a-z*]\+\)/call 
{\1,\1,\1} \2(\1 undef, \1 undef, \1 undef, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/call {\1,\1,\1,\1} \2(\1 undef, \1 undef, \1 undef, \1 
undef, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/call {\1,\1,\1,\1,\1} \2(\1 undef, \1 undef, \1 undef, 
\1 undef, \1 undef, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/call {\1,\1,\1,\1,\1,\1} \2(\1 undef, \1 undef, \1 
undef, \1 undef, \1 undef, \1 undef, \3/g' $var
sed -i 's/call {\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/call {\1,\1,\1,\1,\1,\1,\1} \2(\1 undef, \1 undef, \1 
undef, \1 undef, \1 undef, \1 undef, \1 undef, \3/g' $var
sed -i 's/call 
{\([^,]\+\),[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+,[^,]\+} 
\(.*\)(\([0-9a-z*]\+\)/call {\1,\1,\1,\1,\1,\1,\1,\1} \2(\1 undef, \1 undef ,\1 
undef ,\1 undef, \1 undef ,\1 undef, \1 undef, \1 undef, \
  3/g' $var
  done


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125323

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


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

2022-06-01 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D124753#3546608 , @python3kgae 
wrote:

> In D124753#3545779 , @Anastasia 
> wrote:
>
>> From the current change it seems to me that what you need to be testing is a 
>> just that the frontend options are being passed correctly? This should then 
>> be a driver test with `-###` checking for the options to be set for the 
>> frontend invocation...
>
> There's already a driver test with '-###' in 
> https://reviews.llvm.org/D124751#change-af6Z62NjlfGb

This test doesn't seem to correspond to the change being added as you are 
changing the command-line flags. You don't actually add/generate any attributes 
in this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124753

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


[PATCH] D122150: [clang][analyzer] Add checker for bad use of 'errno'.

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



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:554
+CmdLineOptionhttps://reviews.llvm.org/D122150/new/

https://reviews.llvm.org/D122150

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


[PATCH] D124752: [HLSL] clang codeGen for HLSLShaderAttr.

2022-06-01 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

LGTM! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124752

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


[clang] 1f6ea2a - Expand definition deprecation warning to include constexpr statements.

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

Author: Luke Nihlen
Date: 2022-06-01T11:31:07-04:00
New Revision: 1f6ea2a37c4393a2147cb82c8fe7966a2f690e24

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

LOG: Expand definition deprecation warning to include constexpr statements.

Clang currently warns on definitions downgraded to declarations
with a const modifier, but not for a constexpr modifier. This patch
updates the warning logic to warn on both inputs, and adds a test to
check the additional case as well.

See also: https://bugs.chromium.org/p/chromium/issues/detail?id=1284718

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/test/CXX/basic/basic.def/p2.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6453f4b302d8b..83db2a7cd38b6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@ Improvements to Clang's diagnostics
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index d68d1f3ff070d..f349a86ec2dac 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4508,15 +4508,15 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   }
 
   // C++ doesn't have tentative definitions, so go right ahead and check here.
-  if (getLangOpts().CPlusPlus &&
-  New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  if (getLangOpts().CPlusPlus) {
 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
 Old->getCanonicalDecl()->isConstexpr()) {
   // This definition won't be a definition any more once it's been merged.
   Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
-} else if (VarDecl *Def = Old->getDefinition()) {
-  if (checkVarDeclRedefinition(Def, New))
+} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  VarDecl *Def = Old->getDefinition();
+  if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
   }

diff  --git a/clang/test/CXX/basic/basic.def/p2.cpp 
b/clang/test/CXX/basic/basic.def/p2.cpp
index 598a79a8a3d7d..ccb7a66cff8f0 100644
--- a/clang/test/CXX/basic/basic.def/p2.cpp
+++ b/clang/test/CXX/basic/basic.def/p2.cpp
@@ -5,4 +5,9 @@ namespace {
 static constexpr int n = 0;
   };
   const int A::n; // expected-warning {{deprecated}}
+
+  struct B {
+static constexpr int m = 0;
+  };
+  constexpr int B::m; // expected-warning {{deprecated}}
 }



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


[PATCH] D126664: Expand definition deprecation warning to include constexpr statements.

2022-06-01 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1f6ea2a37c43: Expand definition deprecation warning to 
include constexpr statements. (authored by luken-google, committed by 
aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126664

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CXX/basic/basic.def/p2.cpp


Index: clang/test/CXX/basic/basic.def/p2.cpp
===
--- clang/test/CXX/basic/basic.def/p2.cpp
+++ clang/test/CXX/basic/basic.def/p2.cpp
@@ -5,4 +5,9 @@
 static constexpr int n = 0;
   };
   const int A::n; // expected-warning {{deprecated}}
+
+  struct B {
+static constexpr int m = 0;
+  };
+  constexpr int B::m; // expected-warning {{deprecated}}
 }
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -4508,15 +4508,15 @@
   }
 
   // C++ doesn't have tentative definitions, so go right ahead and check here.
-  if (getLangOpts().CPlusPlus &&
-  New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  if (getLangOpts().CPlusPlus) {
 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
 Old->getCanonicalDecl()->isConstexpr()) {
   // This definition won't be a definition any more once it's been merged.
   Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
-} else if (VarDecl *Def = Old->getDefinition()) {
-  if (checkVarDeclRedefinition(Def, New))
+} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  VarDecl *Def = Old->getDefinition();
+  if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -


Index: clang/test/CXX/basic/basic.def/p2.cpp
===
--- clang/test/CXX/basic/basic.def/p2.cpp
+++ clang/test/CXX/basic/basic.def/p2.cpp
@@ -5,4 +5,9 @@
 static constexpr int n = 0;
   };
   const int A::n; // expected-warning {{deprecated}}
+
+  struct B {
+static constexpr int m = 0;
+  };
+  constexpr int B::m; // expected-warning {{deprecated}}
 }
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -4508,15 +4508,15 @@
   }
 
   // C++ doesn't have tentative definitions, so go right ahead and check here.
-  if (getLangOpts().CPlusPlus &&
-  New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  if (getLangOpts().CPlusPlus) {
 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
 Old->getCanonicalDecl()->isConstexpr()) {
   // This definition won't be a definition any more once it's been merged.
   Diag(New->getLocation(),
diag::warn_deprecated_redundant_constexpr_static_def);
-} else if (VarDecl *Def = Old->getDefinition()) {
-  if (checkVarDeclRedefinition(Def, New))
+} else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
+  VarDecl *Def = Old->getDefinition();
+  if (Def && checkVarDeclRedefinition(Def, New))
 return;
 }
   }
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@
   suggest ``#else`` as an alternative. ``#elifdef`` and ``#elifndef`` are only
   suggested when in C2x or C++2b mode. Fixes
   `Issue 51598 `_.
+- The ``-Wdeprecated`` diagnostic will now warn on out-of-line ``constexpr``
+  declarations downgraded to definitions in C++1z, in addition to the
+  existing warning on out-of-line ``const`` declarations.
 
 Non-comprehensive list of changes in this release
 -
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D126660: [OpenCL] Reword unknown extension pragma diagnostic

2022-06-01 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.
This revision is now accepted and ready to land.

Ok, makes sense! Thanks!

Btw I was thinking we should provide some way for developers to know what 
extensions are being supported either through documentation or by querying 
clang somehow? I am guessing documentation would be easier to implement but 
harder to keep in sync?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126660

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


[clang] 872f744 - Fix std::has_unique_object_representations for _BitInt types with padding bits

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

Author: Mital Ashok
Date: 2022-06-01T11:34:40-04:00
New Revision: 872f74440f3c8b749d90384a23caa894068504f9

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

LOG: Fix std::has_unique_object_representations for _BitInt types with padding 
bits

"std::has_unique_object_representations<_BitInt(N)>" was always true,
even if the type has padding bits (since the trait assumes all integer
types have no padding bits). The standard has an explicit note that
this should not hold for types with padding bits.

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

Added: 
clang/test/SemaCXX/has_unique_object_reps_bitint.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ASTContext.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 83db2a7cd38b6..b58f856800493 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -158,6 +158,8 @@ Bug Fixes
 - Implement `CWG 2394 `_: Const class members
   may be initialized with a defaulted default constructor under the same
   conditions it would be allowed for a const object elsewhere.
+- ``__has_unique_object_representations`` no longer reports that ``_BitInt`` 
types
+  have unique object representations if they have padding bits.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 6349d7b7c46f3..eab6c34bb8f1a 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -2684,7 +2684,11 @@ getSubobjectSizeInBits(const FieldDecl *Field, const 
ASTContext &Context) {
 if (!RD->isUnion())
   return structHasUniqueObjectRepresentations(Context, RD);
   }
-  if (!Field->getType()->isReferenceType() &&
+
+  // A _BitInt type may not be unique if it has padding bits
+  // but if it is a bitfield the padding bits are not used.
+  bool IsBitIntType = Field->getType()->isBitIntType();
+  if (!Field->getType()->isReferenceType() && !IsBitIntType &&
   !Context.hasUniqueObjectRepresentations(Field->getType()))
 return llvm::None;
 
@@ -2692,9 +2696,17 @@ getSubobjectSizeInBits(const FieldDecl *Field, const 
ASTContext &Context) {
   Context.toBits(Context.getTypeSizeInChars(Field->getType()));
   if (Field->isBitField()) {
 int64_t BitfieldSize = Field->getBitWidthValue(Context);
-if (BitfieldSize > FieldSizeInBits)
+if (IsBitIntType) {
+  if ((unsigned)BitfieldSize >
+  cast(Field->getType())->getNumBits())
+return llvm::None;
+} else if (BitfieldSize > FieldSizeInBits) {
   return llvm::None;
+}
 FieldSizeInBits = BitfieldSize;
+  } else if (IsBitIntType &&
+ !Context.hasUniqueObjectRepresentations(Field->getType())) {
+return llvm::None;
   }
   return FieldSizeInBits;
 }
@@ -2792,8 +2804,13 @@ bool ASTContext::hasUniqueObjectRepresentations(QualType 
Ty) const {
 return false;
 
   // All integrals and enums are unique.
-  if (Ty->isIntegralOrEnumerationType())
+  if (Ty->isIntegralOrEnumerationType()) {
+// Except _BitInt types that have padding bits.
+if (const auto *BIT = dyn_cast(Ty))
+  return getTypeSize(BIT) == BIT->getNumBits();
+
 return true;
+  }
 
   // All other pointers are unique.
   if (Ty->isPointerType())

diff  --git a/clang/test/SemaCXX/has_unique_object_reps_bitint.cpp 
b/clang/test/SemaCXX/has_unique_object_reps_bitint.cpp
new file mode 100644
index 0..83190d006030e
--- /dev/null
+++ b/clang/test/SemaCXX/has_unique_object_reps_bitint.cpp
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify 
-std=c++17 -Wno-bitfield-width %s
+//  expected-no-diagnostics
+
+static_assert(__has_unique_object_representations(_BitInt(8)));
+static_assert(__has_unique_object_representations(unsigned _BitInt(8)));
+static_assert(__has_unique_object_representations(_BitInt(sizeof(int) * 8u)));
+// sizeof(_BitInt(24)) may be 4 to align it to the next greater integer type, 
in which case it would have 8 padding bits.
+static_assert(__has_unique_object_representations(_BitInt(24)) == 
(sizeof(_BitInt(24)) == 3));
+
+static_assert(!__has_unique_object_representations(_BitInt(7)));
+static_assert(!__has_unique_object_representations(unsigned _BitInt(7)));
+static_assert(!__has_unique_object_representations(_BitInt(2)));
+static_assert(!__has_unique_object_representations(unsigned _BitInt(1)));
+
+template 
+constexpr bool check() {
+  if constexpr (N <= __BITINT_MAXWIDTH__) {
+static_assert(__has_unique_object_representations(_BitInt(N)) == 
(sizeof(_BitInt(N)) * 8u == N));
+static_assert(__has_unique_object_representations(unsigned _BitInt(N)) == 
(sizeof(unsigned _BitInt(N)) * 8u 

[PATCH] D125802: Fix std::has_unique_object_representations for _BitInt types with padding bits

2022-06-01 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG872f74440f3c: Fix std::has_unique_object_representations for 
_BitInt types with padding bits (authored by MitalAshok, committed by 
aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125802

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ASTContext.cpp
  clang/test/SemaCXX/has_unique_object_reps_bitint.cpp

Index: clang/test/SemaCXX/has_unique_object_reps_bitint.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/has_unique_object_reps_bitint.cpp
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fsyntax-only -verify -std=c++17 -Wno-bitfield-width %s
+//  expected-no-diagnostics
+
+static_assert(__has_unique_object_representations(_BitInt(8)));
+static_assert(__has_unique_object_representations(unsigned _BitInt(8)));
+static_assert(__has_unique_object_representations(_BitInt(sizeof(int) * 8u)));
+// sizeof(_BitInt(24)) may be 4 to align it to the next greater integer type, in which case it would have 8 padding bits.
+static_assert(__has_unique_object_representations(_BitInt(24)) == (sizeof(_BitInt(24)) == 3));
+
+static_assert(!__has_unique_object_representations(_BitInt(7)));
+static_assert(!__has_unique_object_representations(unsigned _BitInt(7)));
+static_assert(!__has_unique_object_representations(_BitInt(2)));
+static_assert(!__has_unique_object_representations(unsigned _BitInt(1)));
+
+template 
+constexpr bool check() {
+  if constexpr (N <= __BITINT_MAXWIDTH__) {
+static_assert(__has_unique_object_representations(_BitInt(N)) == (sizeof(_BitInt(N)) * 8u == N));
+static_assert(__has_unique_object_representations(unsigned _BitInt(N)) == (sizeof(unsigned _BitInt(N)) * 8u == N));
+  }
+  return true;
+}
+
+template 
+constexpr bool do_check = (check() && ...);
+
+static_assert(do_check<2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18>);
+static_assert(do_check<15, 16, 17, 23, 24, 25, 31, 32, 33>);
+static_assert(do_check<39, 40, 41, 47, 48, 49>);
+static_assert(do_check<127, 128, 129, 255, 256, 257, 383, 384, 385>);
+
+template 
+struct in_struct {
+  _BitInt(N) x;
+  static constexpr bool check() {
+return __has_unique_object_representations(in_struct) == __has_unique_object_representations(_BitInt(N));
+  }
+};
+
+static_assert(in_struct<8>::check());
+static_assert(in_struct<7>::check());
+
+struct bit_fields_1 {
+  _BitInt(7) x : 7;
+  unsigned _BitInt(1) y : 1;
+};
+
+static_assert(__has_unique_object_representations(bit_fields_1) == (sizeof(bit_fields_1) == 1));
+
+struct bit_fields_2 {
+  _BitInt(8) x : 7;
+};
+
+static_assert(!__has_unique_object_representations(bit_fields_2));
+
+struct bit_fields_3 {
+  _BitInt(15) x : 8;
+};
+
+static_assert(__has_unique_object_representations(bit_fields_3) == (sizeof(bit_fields_3) == 1));
+
+#if __BITINT_MAXWIDTH__ >= 129
+struct bit_fields_4 {
+  _BitInt(129) x : 128;
+};
+
+static_assert(__has_unique_object_representations(bit_fields_4) == (sizeof(bit_fields_4) == 128 / 8));
+#endif
+
+struct bit_fields_5 {
+  _BitInt(2) x : 8;
+};
+
+static_assert(!__has_unique_object_representations(bit_fields_5));
+
+template 
+struct ref_member {
+  _BitInt(N) & x;
+};
+
+struct int_ref_member {
+  int &x;
+};
+
+static_assert(__has_unique_object_representations(ref_member<7>) == __has_unique_object_representations(ref_member<8>));
+static_assert(__has_unique_object_representations(ref_member<8>) == __has_unique_object_representations(int_ref_member));
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -2684,7 +2684,11 @@
 if (!RD->isUnion())
   return structHasUniqueObjectRepresentations(Context, RD);
   }
-  if (!Field->getType()->isReferenceType() &&
+
+  // A _BitInt type may not be unique if it has padding bits
+  // but if it is a bitfield the padding bits are not used.
+  bool IsBitIntType = Field->getType()->isBitIntType();
+  if (!Field->getType()->isReferenceType() && !IsBitIntType &&
   !Context.hasUniqueObjectRepresentations(Field->getType()))
 return llvm::None;
 
@@ -2692,9 +2696,17 @@
   Context.toBits(Context.getTypeSizeInChars(Field->getType()));
   if (Field->isBitField()) {
 int64_t BitfieldSize = Field->getBitWidthValue(Context);
-if (BitfieldSize > FieldSizeInBits)
+if (IsBitIntType) {
+  if ((unsigned)BitfieldSize >
+  cast(Field->getType())->getNumBits())
+return llvm::None;
+} else if (BitfieldSize > FieldSizeInBits) {
   return llvm::None;
+}
 FieldSizeInBits = BitfieldSize;
+  } else if (IsBitIntType &&
+ !Context.hasUniqueObjectRepresentations(Field->getType())) {
+return llvm::None;
   }
   return FieldSizeInBits;
 }
@@ -2792,8 +2804,13 @@
 retur

[PATCH] D126660: [OpenCL] Reword unknown extension pragma diagnostic

2022-06-01 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added a comment.

In D126660#3550356 , @Anastasia wrote:

> Ok, makes sense! Thanks!
>
> Btw I was thinking we should provide some way for developers to know what 
> extensions are being supported either through documentation or by querying 
> clang somehow? I am guessing documentation would be easier to implement but 
> harder to keep in sync?

I agree that would be nice to have.  That would also enable us to distinguish 
valid pragmaless extensions from garbage (e.g. mistyped extensions), and would 
also help `-cl-ext` parsing/diagnosing for example.  But that would require us 
to maintain a list of extensions inside Clang, which I believe is what we 
wanted to move away from (especially for extensions that only add library-like 
functionality)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126660

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


[PATCH] D125400: [clang][Analyzer] Add errno state to standard functions modeling.

2022-06-01 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125400

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


[PATCH] D119646: [clang] Allow consteval functions in default arguments

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

LGTM as well, but please add a release note about the bug fix (and reference 
the issue it closes).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119646

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


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

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126559

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


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

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

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120290

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


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

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126578

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


[PATCH] D126758: [clang-format] Handle do-while loops for RemoveBracesLLVM

2022-06-01 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:25103
 
-  // The following eight test cases are fully-braced versions of the examples 
at
+  // The following nine test cases are fully-braced versions of the examples at
   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-

curdeius wrote:
> Nit. To avoid updating it every time we add an example.
Yep. I will also remove the numbering on the examples.



Comment at: clang/unittests/Format/FormatTest.cpp:25407-25411
+  verifyFormat("do {\n"
+   "  ++I;\n"
+   "} while (hasMore() && Filter(*I));",
+   "do { ++I; } while (hasMore() && Filter(*I));",
+   Style);

curdeius wrote:
> What's the value of testing that newlines are added? That's not really the 
> job of Insert/RemoveBraces.
This was from the actual llvm-project source. I used it not because I wanted to 
test the insertion of newlines, but because I fixed some insert/remove braces 
bugs related to whether the braces were wrapped.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126758

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


[PATCH] D126758: [clang-format] Handle do-while loops for RemoveBracesLLVM

2022-06-01 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 433432.
owenpan added a comment.

Removed the numbering of the examples from the coding standards.


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

https://reviews.llvm.org/D126758

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25100,12 +25100,12 @@
   FormatStyle Style = getLLVMStyle();
   Style.RemoveBracesLLVM = true;
 
-  // The following eight test cases are fully-braced versions of the examples at
+  // The following test cases are fully-braced versions of the examples at
   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
   // statement-bodies-of-if-else-loop-statements".
 
-  // 1. Omit the braces, since the body is simple and clearly associated with
-  // the if.
+  // Omit the braces since the body is simple and clearly associated with the
+  // `if`.
   verifyFormat("if (isa(D))\n"
"  handleFunctionDecl(D);\n"
"else if (isa(D))\n"
@@ -25117,7 +25117,7 @@
"}",
Style);
 
-  // 2. Here we document the condition itself and not the body.
+  // Here we document the condition itself and not the body.
   verifyFormat("if (isa(D)) {\n"
"  // It is necessary that we explain the situation with this\n"
"  // surprisingly long comment, so it would be unclear\n"
@@ -25125,32 +25125,29 @@
"  // the scope of the `if`.\n"
"  // Because the condition is documented, we can't really\n"
"  // hoist this comment that applies to the body above the\n"
-   "  // if.\n"
+   "  // `if`.\n"
"  handleOtherDecl(D);\n"
"}",
Style);
 
-  // 3. Use braces on the outer `if` to avoid a potential dangling else
+  // Use braces on the outer `if` to avoid a potential dangling `else`
   // situation.
   verifyFormat("if (isa(D)) {\n"
-   "  for (auto *A : D.attrs())\n"
-   "if (shouldProcessAttr(A))\n"
-   "  handleAttr(A);\n"
+   "  if (shouldProcessAttr(A))\n"
+   "handleAttr(A);\n"
"}",
"if (isa(D)) {\n"
-   "  for (auto *A : D.attrs()) {\n"
-   "if (shouldProcessAttr(A)) {\n"
-   "  handleAttr(A);\n"
-   "}\n"
+   "  if (shouldProcessAttr(A)) {\n"
+   "handleAttr(A);\n"
"  }\n"
"}",
Style);
 
-  // 4. Use braces for the `if` block to keep it uniform with the else block.
+  // Use braces for the `if` block to keep it uniform with the `else` block.
   verifyFormat("if (isa(D)) {\n"
"  handleFunctionDecl(D);\n"
"} else {\n"
-   "  // In this else case, it is necessary that we explain the\n"
+   "  // In this `else` case, it is necessary that we explain the\n"
"  // situation with this surprisingly long comment, so it\n"
"  // would be unclear without the braces whether the\n"
"  // following statement is in the scope of the `if`.\n"
@@ -25158,9 +25155,9 @@
"}",
Style);
 
-  // 5. This should also omit braces.  The `for` loop contains only a single
+  // This should also omit braces. The `for` loop contains only a single
   // statement, so it shouldn't have braces.  The `if` also only contains a
-  // single simple statement (the for loop), so it also should omit braces.
+  // single simple statement (the `for` loop), so it also should omit braces.
   verifyFormat("if (isa(D))\n"
"  for (auto *A : D.attrs())\n"
"handleAttr(A);",
@@ -25171,18 +25168,26 @@
"}",
Style);
 
-  // 6. Use braces for the outer `if` since the nested `for` is braced.
+  // Use braces for a `do-while` loop and its enclosing statement.
+  verifyFormat("if (Tok->is(tok::l_brace)) {\n"
+   "  do {\n"
+   "Tok = Tok->Next;\n"
+   "  } while (Tok);\n"
+   "}",
+   Style);
+
+  // Use braces for the outer `if` since the nested `for` is braced.
   verifyFormat("if (isa(D)) {\n"
"  for (auto *A : D.attrs()) {\n"
-   "// In this for loop body, it is necessary that we explain\n"
-   "// the situation with this surprisingly long comment,\n"
-   "// forcing braces on the `for` block.\n"
+   "// In this `for` loop body, it is necessary that we\n"
+   "// explain the situation with this surprisingly long\n

[PATCH] D126291: [flang][Driver] Update link job on windows

2022-06-01 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added a comment.

While the test passes now, I still get `LINK : fatal error LNK1561: entry point 
must be defined` when trying to actually link. Isn't it expected to not work 
yet?

Linking with `lld-link.exe` does work. objdump says there is a `_QQmain` 
symbol, why does lld consider this to be the entry point?


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

https://reviews.llvm.org/D126291

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


[clang] a5b056f - [MSVC] Fix pragma alloc_text failing for C files

2022-06-01 Thread Stephen Long via cfe-commits

Author: Stephen Long
Date: 2022-06-01T09:39:46-07:00
New Revision: a5b056fe49a991c65e665468f1a681965f41b137

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

LOG: [MSVC] Fix pragma alloc_text failing for C files

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

Reviewed By: rnk, aaron.ballman

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

Added: 
clang/test/Sema/pragma-ms-alloc-text.c

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

Removed: 




diff  --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 9681117abe424..4560bb060a4aa 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -763,7 +763,7 @@ void Sema::ActOnPragmaMSAllocText(
 }
 
 DeclContext *DC = ND->getDeclContext();
-if (!DC->isExternCContext()) {
+if (getLangOpts().CPlusPlus && !DC->isExternCContext()) {
   Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
   return;
 }

diff  --git a/clang/test/Sema/pragma-ms-alloc-text.c 
b/clang/test/Sema/pragma-ms-alloc-text.c
new file mode 100644
index 0..a5f2e9f11dce2
--- /dev/null
+++ b/clang/test/Sema/pragma-ms-alloc-text.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+void foo();
+#pragma alloc_text("hello", foo) // expected-no-diagnostics
+void foo() {}
+
+static void foo1();
+#pragma alloc_text("hello", foo1) // expected-no-diagnostics
+void foo1() {}

diff  --git a/clang/test/Sema/pragma-ms-alloc-text.cpp 
b/clang/test/Sema/pragma-ms-alloc-text.cpp
index e1fb0ab4b2538..931b152fe78cc 100644
--- a/clang/test/Sema/pragma-ms-alloc-text.cpp
+++ b/clang/test/Sema/pragma-ms-alloc-text.cpp
@@ -34,3 +34,9 @@ void foo4() {}
 void foo5();// expected-note {{previous declaration is here}}
 #pragma alloc_text(c, foo5) // expected-error {{'#pragma alloc_text' is 
applicable only to functions with C linkage}}
 extern "C" void foo5() {}   // expected-error {{declaration of 'foo5' has a 
diff erent language linkage}}
+
+extern "C" {
+static void foo6();
+#pragma alloc_text(c, foo6) // no-warning
+void foo6() {}
+}



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


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

2022-06-01 Thread Stephen Long via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa5b056fe49a9: [MSVC] Fix pragma alloc_text failing for C 
files (authored by steplong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126559

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


Index: clang/test/Sema/pragma-ms-alloc-text.cpp
===
--- clang/test/Sema/pragma-ms-alloc-text.cpp
+++ clang/test/Sema/pragma-ms-alloc-text.cpp
@@ -34,3 +34,9 @@
 void foo5();// expected-note {{previous declaration is here}}
 #pragma alloc_text(c, foo5) // expected-error {{'#pragma alloc_text' is 
applicable only to functions with C linkage}}
 extern "C" void foo5() {}   // expected-error {{declaration of 'foo5' has a 
different language linkage}}
+
+extern "C" {
+static void foo6();
+#pragma alloc_text(c, foo6) // no-warning
+void foo6() {}
+}
Index: clang/test/Sema/pragma-ms-alloc-text.c
===
--- /dev/null
+++ clang/test/Sema/pragma-ms-alloc-text.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+void foo();
+#pragma alloc_text("hello", foo) // expected-no-diagnostics
+void foo() {}
+
+static void foo1();
+#pragma alloc_text("hello", foo1) // expected-no-diagnostics
+void foo1() {}
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -763,7 +763,7 @@
 }
 
 DeclContext *DC = ND->getDeclContext();
-if (!DC->isExternCContext()) {
+if (getLangOpts().CPlusPlus && !DC->isExternCContext()) {
   Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
   return;
 }


Index: clang/test/Sema/pragma-ms-alloc-text.cpp
===
--- clang/test/Sema/pragma-ms-alloc-text.cpp
+++ clang/test/Sema/pragma-ms-alloc-text.cpp
@@ -34,3 +34,9 @@
 void foo5();// expected-note {{previous declaration is here}}
 #pragma alloc_text(c, foo5) // expected-error {{'#pragma alloc_text' is applicable only to functions with C linkage}}
 extern "C" void foo5() {}   // expected-error {{declaration of 'foo5' has a different language linkage}}
+
+extern "C" {
+static void foo6();
+#pragma alloc_text(c, foo6) // no-warning
+void foo6() {}
+}
Index: clang/test/Sema/pragma-ms-alloc-text.c
===
--- /dev/null
+++ clang/test/Sema/pragma-ms-alloc-text.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
+
+void foo();
+#pragma alloc_text("hello", foo) // expected-no-diagnostics
+void foo() {}
+
+static void foo1();
+#pragma alloc_text("hello", foo1) // expected-no-diagnostics
+void foo1() {}
Index: clang/lib/Sema/SemaAttr.cpp
===
--- clang/lib/Sema/SemaAttr.cpp
+++ clang/lib/Sema/SemaAttr.cpp
@@ -763,7 +763,7 @@
 }
 
 DeclContext *DC = ND->getDeclContext();
-if (!DC->isExternCContext()) {
+if (getLangOpts().CPlusPlus && !DC->isExternCContext()) {
   Diag(Loc, diag::err_pragma_alloc_text_c_linkage);
   return;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e5ece11 - [analyzer][NFC] Add test for 3a07280290564e294c957c94c918a6680714b417

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

Author: Balazs Benics
Date: 2022-06-01T18:53:19+02:00
New Revision: e5ece11e761a8b31b700249e46cf05590330ebc7

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

LOG: [analyzer][NFC] Add test for 3a07280290564e294c957c94c918a6680714b417

I'm adding a test demonstraing that the issue reported by @mikaelholmen
is fixed.

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

Added: 


Modified: 
clang/test/Analysis/pointer-to-member.cpp

Removed: 




diff  --git a/clang/test/Analysis/pointer-to-member.cpp 
b/clang/test/Analysis/pointer-to-member.cpp
index e1b4d0c11949c..a1adaa719617e 100644
--- a/clang/test/Analysis/pointer-to-member.cpp
+++ b/clang/test/Analysis/pointer-to-member.cpp
@@ -310,3 +310,13 @@ void test() {
 }
 } // namespace testStaticCasting
 
+namespace D126198 {
+class Base {};
+class Derived : public Base {};
+int foo(int Derived::*);
+
+int test() {
+  int Base::*p = nullptr;
+  return foo(p); // no-crash
+}
+} // namespace D126198



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


[PATCH] D102122: Support warn_unused_result on typedefs

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

In D102122#3544655 , @dblaikie wrote:

> How's this look now, then?

I think it's heading in the right direction.

> One drawback is the built-in attribute warnings that mention which entities 
> the attribute is valid on will mention typedefs even when the user uses a 
> spelling that wouldn't be valid there - so the user might try it there, then 
> get the follow-on warning (totally open to wordsmithing that warning, too - 
> just placeholder words - also made it part of the same group as the 
> warn_unused_result warning itself - if you disable that warning, then 
> presumably you don't care about the warning being in the wrong place either, 
> to some extent).

Yeah, that is a drawback -- we don't have a spelling-specific set of subjects 
currently. I had a plan to address that at some point by introducing more data 
into the subject list so you could do something like:

  def WarnUnusedResult : InheritableAttr {
let Spellings = [CXX11<"", "nodiscard", 201907>,
 C2x<"", "nodiscard", 201904>,
 CXX11<"clang", "warn_unused_result">,
 GCC<"warn_unused_result">];
let Subjects = SubjectList<
 SubjectsFor<[ObjCMethod, Enum, Record, 
FunctionLike, TypedefName], [GNU<"warn_unused_result">, CXX11<"clang", 
"warn_unused_result">]>,
 SubjectsFor<[ObjCMethod, Enum, Record, 
FunctionLike], [CXX11<"", "nodiscard">, C2x<"", "nodiscard">, CXX11<"gnu", 
"warn_unused_result">]>,
   >;
...
  }

But that's complicated (as this attribute demonstrates!). This is a case 
where we want HALF of a spelling to apply to some subjects (the GNU spelling 
half of the `GCC` spelling) and the other half to apply to other subjects (the 
C++ spelling half of the `GCC` spelling).

I think for right now, I think it's okay for us to have the slightly degraded 
diagnostic behavior. If it turns into user confusion in practice, we can 
improve the diagnostics at that point. WDYT?




Comment at: clang/include/clang/Basic/Attr.td:2945
C2x<"", "nodiscard", 201904>,
CXX11<"clang", "warn_unused_result">,
GCC<"warn_unused_result">];

Oops, it looks like we support this spelling in C++ but not in C (not your bug, 
just an observation): https://godbolt.org/z/1hPq6coba



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:8733-8734
+def warn_unused_result_typedef_unsupported_spelling : Warning<
+  "warn_unused_result on typedefs only supported with gnu or clang scoped "
+  "standard spelling">, InGroup;
 def warn_unused_volatile : Warning<

It's a bit more wordy, but I think it's more clear as well. Also, this makes it 
more clear that the attribute is being ignored (and groups it under that 
grouping as well).

(Definitely need to adjust for 80 col limits.)



Comment at: clang/lib/AST/Expr.cpp:1525-1527
+  if (const auto *TD = getCallReturnType(Ctx)->getAs())
+if (const auto *A = TD->getDecl()->getAttr())
+  return A;

rsmith wrote:
> This should loop over `TypedefType` sugar; the attribute could be in a nested 
> typedef.
I agree with Richard here. I think this is needed for a case like:
```
typedef int foo __attribute__((warn_unused_result));
typedef foo foob;

foob func();

int main() {
  func(); // Still want to be barked at here
}
```
But this example brings up an interesting question of expectations. What's your 
intuition on how this should behave?
```
typedef int foo __attribute__((warn_unused_result));
typedef foo *foo_ptr;

foo_ptr func();

int main() {
  func(); // Bark? Silence? Other?
}
```
FWIW, my initial inclination was that this would diagnose the call to `func()` 
but now I'm second-guessing that, hence the question about type composition in 
a typedef.



Comment at: clang/test/SemaCXX/warn-unused-result.cpp:259
+namespace unused_typedef_result {
+[[clang::warn_unused_result]] typedef void *a;
+a af1();

I think you should also have a test for `[[gnu::warn_unused_result]]` to show 
that we didn't touch the behavior of that vendor-specific spelling.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102122

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


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

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

LGTM! Please wait a day or two before landing in case @jyknight has additional 
comments, though. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126324

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


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

2022-06-01 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

> Constrained intrinsics don't change the rounding mode.

The standard text for FENV_ROUND requires that when we see a floating point 
operation, we have to perform it using the specified rounding mode.  
"floating-point operators [...] shall be evaluated according to the specified 
constant rounding mode (as though no constant mode was specified and the 
corresponding dynamic rounding mode had been established by a call to 
fesetround)".  Like you've noted, we don't have any way to represent that 
directly in LLVM IR.  So the frontend probably needs to emit code to modify the 
rounding mode.

> Because of the requirement that the rounding mode be changed already, I don't 
> see how instructions with static rounding modes are generally interesting. 
> Perhaps a target will learn to recognize that a sequence of instructions can 
> use the static rounding in the instructions and elide a change of rounding 
> mode around the sequence? I don't know how common that would be in practice.

If you're using FENV_ROUND, presumably sequences involving rounding mode 
changes become more common.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126364

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


[PATCH] D120540: [Driver] Enable to use C++20 modules standalone by -fcxx-modules

2022-06-01 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

This patch broke a whole bunch tests in the LLDB testsuite. I'm trying to 
figure out what exactly the semantics of the change are, particularly on 
Darwin, where `-fmodules` doesn't imply `-fcxx-modules`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120540

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


[PATCH] D120540: [Driver] Enable to use C++20 modules standalone by -fcxx-modules

2022-06-01 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/44167/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120540

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


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

2022-06-01 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

I'm in the middle of upstreaming PS5 support and I still didn't think of 
this... doh!




Comment at: clang/lib/Driver/ToolChains/Clang.cpp:5588
 
+  bool DefaultedSMFArePOD = !RawTriple.isPS4() && !RawTriple.isOSDarwin();
+

`isPS4()` => `isPS()` please.  This should be in effect for both PS4 and PS5.



Comment at: clang/test/Driver/clang_f_opts.c:602
+// RUN: %clang -### %s 2>&1 | FileCheck 
--check-prefix=CHECK-DEFAULTED-SMF-ARE-POD %s
+// RUN: %clang -### %s -target x86_64-scei-ps4 2>&1 | FileCheck 
--check-prefix=CHECK-NO-DEFAULTED-SMF-ARE-POD %s
+// RUN: %clang -### %s -target x86_64-scei-ps4 -fdefaulted-smf-are-pod 2>&1 | 
FileCheck --check-prefix=CHECK-DEFAULTED-SMF-ARE-POD %s

Please duplicate this line with `-target x86_64-sie-ps5`
(no need to duplicate both)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119051

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


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

2022-06-01 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added a comment.

In D124753#3550337 , @Anastasia wrote:

> In D124753#3546608 , @python3kgae 
> wrote:
>
>> In D124753#3545779 , @Anastasia 
>> wrote:
>>
>>> From the current change it seems to me that what you need to be testing is 
>>> a just that the frontend options are being passed correctly? This should 
>>> then be a driver test with `-###` checking for the options to be set for 
>>> the frontend invocation...
>>
>> There's already a driver test with '-###' in 
>> https://reviews.llvm.org/D124751#change-af6Z62NjlfGb
>
> This test doesn't seem to correspond to the change being added as you are 
> changing the command-line flags. You don't actually add/generate any 
> attributes in this patch.

Sorry to make things confusing. I should not split default value for -E option 
as a separate PR :(

There's dxc_E.hlsl (https://reviews.llvm.org/D124751#change-af6Z62NjlfGb) in 
https://reviews.llvm.org/D124751 where the -E option is added.
dxc_E.hlsl will test -E option translated into -hlsl-entry for cc1.

There was a test for codeGen of -E option in https://reviews.llvm.org/D124752, 
but I removed it because it is to almost the same as 
https://reviews.llvm.org/D124752#change-w4NWvaT68Dhk which test codeGen for 
ShaderAttr.

And the entry_default.hlsl in current PR test codeGen for the default main and 
-E option.

I can add a separate codeGen test for -E option if that's what you thought is 
missing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124753

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


  1   2   3   >