[PATCH] D93600: [clangd] When querying drivers by binary, look in PATH too

2020-12-22 Thread Giulio Girardi via Phabricator via cfe-commits
rapgenic updated this revision to Diff 313259.

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

https://reviews.llvm.org/D93600

Files:
  clang-tools-extra/clangd/QueryDriverDatabase.cpp
  clang-tools-extra/clangd/test/system-include-extractor.test


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -3,21 +3,24 @@
 # The mock driver below is a shell script:
 # REQUIRES: shell
 
+# Create a bin directory to store the mock-driver and add it to the path
+# RUN: mkdir -p %t.dir/bin
+# RUN: export PATH=%t.dir/bin:$PATH
 # Generate a mock-driver that will print %temp_dir%/my/dir and
 # %temp_dir%/my/dir2 as include search paths.
-# RUN: echo '#!/bin/sh' >> %t.dir/my_driver.sh
-# RUN: echo '[ "$0" = "%t.dir/my_driver.sh" ] || exit' >> %t.dir/my_driver.sh
-# RUN: echo 'args="$*"' >> %t.dir/my_driver.sh
-# RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> %t.dir/my_driver.sh
-# RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> 
%t.dir/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> 
%t.dir/my_driver.sh
-# RUN: echo 'echo line to ignore >&2' >> %t.dir/my_driver.sh
-# RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/my_driver.sh
-# RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/my_driver.sh
-# RUN: echo 'echo %t.dir/my/dir/ >&2' >> %t.dir/my_driver.sh
-# RUN: echo 'echo %t.dir/my/dir2/ >&2' >> %t.dir/my_driver.sh
-# RUN: echo 'printf "End of search list.\r\n" >&2' >> %t.dir/my_driver.sh
-# RUN: chmod +x %t.dir/my_driver.sh
+# RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
+# RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo 'echo %t.dir/my/dir/ >&2' >> %t.dir/bin/my_driver.sh
+# RUN: echo 'echo %t.dir/my/dir2/ >&2' >> %t.dir/bin/my_driver.sh
+# RUN: echo 'printf "End of search list.\r\n" >&2' >> %t.dir/bin/my_driver.sh
+# RUN: chmod +x %t.dir/bin/my_driver.sh
 
 # Create header files my/dir/a.h and my/dir2/b.h
 # RUN: mkdir -p %t.dir/my/dir
@@ -27,7 +30,7 @@
 
 # Generate a compile_commands.json that will query the mock driver we've
 # created. Which should add a.h and b.h into include search path.
-# RUN: echo '[{"directory": "%/t.dir", "command": "%/t.dir/my_driver.sh 
the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": 
"the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "my_driver.sh the-file.cpp 
-nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": 
"the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # RUN: sed -e "s|INPUT_DIR|%/t.dir|g" %s > %t.test.1
 # On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
Index: clang-tools-extra/clangd/QueryDriverDatabase.cpp
===
--- clang-tools-extra/clangd/QueryDriverDatabase.cpp
+++ clang-tools-extra/clangd/QueryDriverDatabase.cpp
@@ -136,10 +136,21 @@
 }
 
 llvm::Optional
-extractSystemIncludesAndTarget(PathRef Driver, llvm::StringRef Lang,
+extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
+   llvm::StringRef Lang,
llvm::ArrayRef CommandLine,
const llvm::Regex &QueryDriverRegex) {
   trace::Span Tracer("Extract system includes and target");
+
+  if (!llvm::sys::path::is_absolute(Driver)) {
+auto DriverProgram = llvm::sys::findProgramByName(Driver);
+if (DriverProgram) {
+  vlog("System include extraction: driver {0} expanded to {1}", Driver,
+   *DriverProgram);
+  Driver = *DriverProgram;
+}
+  }
+
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", Lang);
 
@@ -332,7 +343,11 @@
 }
 
 llvm::SmallString<128> Driver(Cmd->CommandLine.front());
-llvm::sys::fs::make_absolute(Cmd->Directory, Driver);
+if (!llvm::none_of(Driver,
+   [](char C) { return llvm::sys::path::is_separator(C); 
}))
+  // Driver is a not a single executable name but instead a path (either
+  // relative or absolute).
+  llvm::sys::fs::make_absolute(Cmd->Directory, Driver);
 
 i

[PATCH] D93600: [clangd] When querying drivers by binary, look in PATH too

2020-12-22 Thread Giulio Girardi via Phabricator via cfe-commits
rapgenic marked 3 inline comments as done.
rapgenic added a comment.

I think I have fixed what you asked!

About the test, I thought it would be reasonable to test the three cases 
separately, however I cannot get it to work with a single test file (I think 
it's some problem with the generated files). Should I duplicate it or is there 
any way to do it better?

Sorry for my trivial question, but I'm still learning to navigate the 
codebase...


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

https://reviews.llvm.org/D93600

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


[PATCH] D93679: [clang[cli] Port getAllArgumentValues to the marshalling infrastructure

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93679

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -335,7 +335,8 @@
 Option::OptionClass OptClass,
 unsigned TableIndex,
 const std::vector &Values) {
-  if (OptClass == Option::OptionClass::CommaJoinedClass) {
+  switch (OptClass) {
+  case Option::CommaJoinedClass: {
 std::string CommaJoinedValue;
 for (const std::string &Value : Values) {
   if (&Value != &Values.front())
@@ -344,9 +345,17 @@
 }
 denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
   TableIndex, CommaJoinedValue);
-  } else if (OptClass == Option::OptionClass::JoinedClass) {
+break;
+  }
+  case Option::JoinedClass:
+  case Option::SeparateClass:
+  case Option::JoinedOrSeparateClass:
 for (const std::string &Value : Values)
   denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
+break;
+  default:
+llvm_unreachable("Cannot denormalize an option with option class "
+ "incompatible with string vector denormalization.");
   }
 }
 
@@ -1001,8 +1010,6 @@
 }
   }
 
-  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
-
   // Basic Block Sections implies Function Sections.
   Opts.FunctionSections =
   Args.hasArg(OPT_ffunction_sections) ||
@@ -1132,10 +1139,6 @@
 }
 Opts.LinkBitcodeFiles.push_back(F);
   }
-  Opts.SanitizeCoverageAllowlistFiles =
-  Args.getAllArgValues(OPT_fsanitize_coverage_allowlist);
-  Opts.SanitizeCoverageBlocklistFiles =
-  Args.getAllArgValues(OPT_fsanitize_coverage_blocklist);
   Opts.SSPBufferSize =
   getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
 
@@ -1217,8 +1220,6 @@
 }
   }
 
-  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
-  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
   bool NeedLocTracking = false;
 
   if (!Opts.OptRecordFile.empty())
@@ -1292,8 +1293,6 @@
   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
 
-  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
-
   // Parse -fsanitize-recover= arguments.
   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
   parseSanitizerKinds("-fsanitize-recover=",
@@ -1305,16 +1304,11 @@
 
   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
 
-  Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
-
-  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
-
   return Success;
 }
 
 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
   ArgList &Args) {
-  Opts.Targets = Args.getAllArgValues(OPT_MT);
   if (Args.hasArg(OPT_show_includes)) {
 // Writing both /showIncludes and preprocessor output to stdout
 // would produce interleaved output, so use stderr for /showIncludes.
@@ -1492,7 +1486,6 @@
   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
-  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
   if (Args.hasArg(OPT_verify))
 Opts.VerifyPrefixes.push_back("expected");
   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
@@ -1539,8 +1532,6 @@
   Opts.MessageLength =
   getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags);
 
-  Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ);
-
   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
 
@@ -1737,8 +1728,6 @@
   }
 
   Opts.Plugins = Args.getAllArgValues(OPT_load);
-  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
-  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
   // Only the -fmodule-file= form.
@@ -1747,7 +1736,6 @@
 if (Val.find('=') == StringRef::npos)
   Opts.ModuleFiles.push_back(std::string(Val));
   }
-  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
   Opts.AllowPCMWithCompi

[PATCH] D84673: Port DiagnosticOpts to new option parsing system

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 commandeered this revision.
jansvoboda11 added a reviewer: dang.
jansvoboda11 added a comment.

Taking over this patch, as Daniel is no longer involved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84673

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


[PATCH] D93452: [clangd] Trim memory periodically

2020-12-22 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

I feel like we need some kind of entry for this in release notes given how much 
of an issue it is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93452

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


[PATCH] D84924: [clang-tidy] Added command line option `fix-notes`

2020-12-22 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D84924#2466564 , @aaron.ballman 
wrote:

> Agreed, but I don't think the current behavior in this patch is cautious 
> enough. I like that we have to specify "please apply fixits from notes" 
> explicitly. I think that's the right behavior we want. But if there are 
> multiple fixits attached to the notes for a diagnostic, I don't think we 
> should assume that the first fix-it is the correct one to apply -- I think 
> the user should have to manually pick the variant they want in that case. So 
> I think the behavior should be to apply the fixits from notes if there's only 
> a single fixit to be applied. WDYT?

I can agree with that, One thing I like about using clangd is it will show you 
all available fixes, letting you pick and choose.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84924

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


[PATCH] D86844: [LoopDeletion] Allows deletion of possibly infinite side-effect free loops

2020-12-22 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added inline comments.



Comment at: clang/test/Misc/loop-opt-setup.c:26
 
 // Check br i1 to make sure the loop is gone, there will still be a label 
branch for the infinite loop.
 // CHECK-LABEL: Helper

This comment needs updating, there's no loop there now. Or better, add a 
run-line with a C standard version that does not have the forward progress 
guarantee, e.g. `-std=c99` and one with an explicit standard that has it and 
have different check lines for the 2 cases.



Comment at: llvm/test/Other/loop-deletion-printer.ll:17
 
-define void @deleteme() {
+define void @deleteme() willreturn {
 entry:

Is this change related to the patch? Same for the other test changes that just 
add `willreturn`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86844

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


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru updated this revision to Diff 313271.
sylvestre.ledru added a comment.

Error only on Windows


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/test/CodeGen/X86/stack-clash-large.ll


Index: llvm/test/CodeGen/X86/stack-clash-large.ll
===
--- llvm/test/CodeGen/X86/stack-clash-large.ll
+++ llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,5 +1,7 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-32 %s 
+; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
+; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3077,12 +3077,15 @@
   }
 }
 
-static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
- ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
+ const ArgList &Args, ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (!EffectiveTriple.isOSLinux())
+  if (EffectiveTriple.isOSWindows()) {
+D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
+<< EffectiveTriple.getOSName();
 return;
+  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5551,7 +5554,7 @@
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(TC, Args, CmdArgs);
+  RenderSCPOptions(D, TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -273,6 +273,8 @@
 : Error<"%0 is not supported with -fembed-bitcode">;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
+def err_drv_stack_clash_protection_unsupported_on_toolchain : Error<
+  "-fstack-clash-protection is not supported on %0">;
 
 def err_drv_invalid_malign_branch_EQ : Error<
   "invalid argument '%0' to -malign-branch=; each element must be one of: %1">;


Index: llvm/test/CodeGen/X86/stack-clash-large.ll
===
--- llvm/test/CodeGen/X86/stack-clash-large.ll
+++ llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,5 +1,7 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck -check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck -check-prefix=CHECK-X86-32 %s 
+; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck -check-prefix=CHECK-X86-64 %s
+; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck -check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3077,12 +3077,15 @@
   }
 }
 
-static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
- ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
+ const ArgList &Args, ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (!EffectiveTriple.isOSLinux())
+  if (EffectiveTriple.isOSWindows()) {
+D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
+<< EffectiveTriple.getOSName();
 return;
+  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5551,7 +5554,7 @@
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(TC, Args, CmdArgs);
+  RenderSCPOptions(D, TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/c

[PATCH] D84924: [clang-tidy] Added command line option `fix-notes`

2020-12-22 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 313272.
njames93 added a comment.

Only apply fixes from notes if there is exactly one fix found in them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84924

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang-tools-extra/clang-tidy/ClangTidy.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
  
clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp
  clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/index.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
  clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp

Index: clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/alternative-fixes.cpp
@@ -1,9 +1,10 @@
-// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t
+// RUN: %check_clang_tidy %s "llvm-namespace-comment,clang-diagnostic-*" %t -- --fix-notes
 void foo(int a) {
   if (a = 1) {
-  // CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
-  // CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
-  // CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
-  // CHECK-FIXES: if ((a = 1)) {
+// CHECK-NOTES: [[@LINE-1]]:9: warning: using the result of an assignment as a condition without parentheses [clang-diagnostic-parentheses]
+// CHECK-NOTES: [[@LINE-2]]:9: note: place parentheses around the assignment to silence this warning
+// CHECK-NOTES: [[@LINE-3]]:9: note: use '==' to turn this assignment into an equality comparison
+// As we have 2 conflicting fixes in notes, don't apply any fix.
+// CHECK-FIXES: if (a = 1) {
   }
 }
Index: clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-unused-using-decls.cpp
@@ -81,7 +81,6 @@
 // eol-comments aren't removed (yet)
 using n::A; // A
 // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'A' is unused
-// CHECK-MESSAGES: :[[@LINE-2]]:10: note: remove the using
 // CHECK-FIXES: {{^}}// A
 using n::B;
 using n::C;
Index: clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
===
--- clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
+++ clang-tools-extra/test/clang-tidy/checkers/misc-definitions-in-headers.hpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s misc-definitions-in-headers %t
+// RUN: %check_clang_tidy %s misc-definitions-in-headers %t -- --fix-notes
 
 int f() {
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: function 'f' defined in a header file; function definitions in header files can lead to ODR violations [misc-definitions-in-headers]
Index: clang-tools-extra/docs/clang-tidy/index.rst
===
--- clang-tools-extra/docs/clang-tidy/index.rst
+++ clang-tools-extra/docs/clang-tidy/index.rst
@@ -173,6 +173,11 @@
  errors were found. If compiler errors have
  attached fix-its, clang-tidy will apply them as
  well.
+--fix-notes- 
+ If a warning has no fix, but one of the 
+ notes attached which contain fixes, apply the
+ fixes found in there. Specifying this flag will
+ implicitly enable the `--fix` flag.
 --format-style=-
  Style for formatting code around applied fixes:
- 'none' (default) turns off formatting
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -67,6 +67,10 @@
 Improvements to clang-tidy
 --
 
+ - Added command line option `--fix-notes` to apply fixes found in notes
+   attached to warnings. These are typically c

[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread serge via Phabricator via cfe-commits
serge-sans-paille accepted this revision.
serge-sans-paille 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/D92245/new/

https://reviews.llvm.org/D92245

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


[clang] 4d59c8f - -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2020-12-22T12:06:08+01:00
New Revision: 4d59c8fdb955ea0d668b854f467e12bce05a8857

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

LOG: -fstack-clash-protection: Return an actual error when used on unsupported 
OS

$ clang-12: error: -fstack-clash-protection is not supported on Windows or Mac 
OS X

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/ToolChains/Clang.cpp
llvm/test/CodeGen/X86/stack-clash-large.ll

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index e92a4bf1dac5..736950b0abb1 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -273,6 +273,8 @@ def err_drv_unsupported_embed_bitcode
 : Error<"%0 is not supported with -fembed-bitcode">;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
+def err_drv_stack_clash_protection_unsupported_on_toolchain : Error<
+  "-fstack-clash-protection is not supported on %0">;
 
 def err_drv_invalid_malign_branch_EQ : Error<
   "invalid argument '%0' to -malign-branch=; each element must be one of: %1">;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 300ab6e815e2..c04b350dae7d 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3067,12 +3067,15 @@ static void RenderSSPOptions(const Driver &D, const 
ToolChain &TC,
   }
 }
 
-static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
- ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
+ const ArgList &Args, ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (!EffectiveTriple.isOSLinux())
+  if (EffectiveTriple.isOSWindows()) {
+D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
+<< EffectiveTriple.getOSName();
 return;
+  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5550,7 +5553,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(TC, Args, CmdArgs);
+  RenderSCPOptions(D, TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign

diff  --git a/llvm/test/CodeGen/X86/stack-clash-large.ll 
b/llvm/test/CodeGen/X86/stack-clash-large.ll
index dd53cd8f6964..7deae310f617 100644
--- a/llvm/test/CodeGen/X86/stack-clash-large.ll
+++ b/llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,5 +1,7 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-32 %s 
+; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
+; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 



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


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Sylvestre Ledru 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 rG4d59c8fdb955: -fstack-clash-protection: Return an actual 
error when used on unsupported OS (authored by sylvestre.ledru).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Clang.cpp
  llvm/test/CodeGen/X86/stack-clash-large.ll


Index: llvm/test/CodeGen/X86/stack-clash-large.ll
===
--- llvm/test/CodeGen/X86/stack-clash-large.ll
+++ llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,5 +1,7 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-32 %s 
+; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
+; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3067,12 +3067,15 @@
   }
 }
 
-static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
- ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
+ const ArgList &Args, ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (!EffectiveTriple.isOSLinux())
+  if (EffectiveTriple.isOSWindows()) {
+D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
+<< EffectiveTriple.getOSName();
 return;
+  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5550,7 +5553,7 @@
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(TC, Args, CmdArgs);
+  RenderSCPOptions(D, TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -273,6 +273,8 @@
 : Error<"%0 is not supported with -fembed-bitcode">;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
+def err_drv_stack_clash_protection_unsupported_on_toolchain : Error<
+  "-fstack-clash-protection is not supported on %0">;
 
 def err_drv_invalid_malign_branch_EQ : Error<
   "invalid argument '%0' to -malign-branch=; each element must be one of: %1">;


Index: llvm/test/CodeGen/X86/stack-clash-large.ll
===
--- llvm/test/CodeGen/X86/stack-clash-large.ll
+++ llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,5 +1,7 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck -check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck -check-prefix=CHECK-X86-32 %s 
+; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck -check-prefix=CHECK-X86-64 %s
+; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck -check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -3067,12 +3067,15 @@
   }
 }
 
-static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
- ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
+ const ArgList &Args, ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (!EffectiveTriple.isOSLinux())
+  if (EffectiveTriple.isOSWindows()) {
+D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
+<< EffectiveTriple.getOSName();
 return;
+  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5550,7 +5553,7 @@
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(TC, Args, CmdArgs);
+  RenderSCPOptions(D, TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign
Index: clang/include/clang/Basic/Diagno

[PATCH] D93683: [clangd] Do not take stale definition from the static index.

2020-12-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX created this revision.
Herald added subscribers: usaxena95, kadircet, arphaman.
ArcsinX requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

This is follow up to D93393 .
Without this patch clangd takes the symbol definition from the static index if 
this definition was removed from the dynamic index.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93683

Files:
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -290,6 +290,42 @@
   EXPECT_THAT(lookup(M, {}), UnorderedElementsAre());
 }
 
+TEST(MergeIndexTest, LookupRemovedDefinition) {
+  FileIndex DynamicIndex;
+  FileIndex StaticIndex;
+  MergedIndex Merge(&DynamicIndex, &StaticIndex);
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo definition
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo {};";
+  Test.Filename = "test.cc";
+  auto AST = Test.build();
+  StaticIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Remove Foo definition from test.cc, i.e. build dynamic index for test.cc
+  // without Foo definition.
+  Test.Code = "class Foo;";
+  AST = Test.build();
+  DynamicIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Merged index should not return the symbol definition if this definition
+  // location is inside a file from the dynamic index.
+  LookupRequest LookupReq;
+  LookupReq.IDs = {Foo.ID};
+  std::vector Symbols;
+  Merge.lookup(LookupReq, [&](const Symbol &Sym) { Symbols.push_back(Sym); });
+  ASSERT_EQ(Symbols.size(), 1u);
+  const auto &Sym = Symbols.front();
+  EXPECT_FALSE(Sym.Definition);
+  EXPECT_EQ(std::string(Sym.CanonicalDeclaration.FileURI),
+std::string("unittest:///TestTU.h"));
+}
+
 TEST(MergeIndexTest, FuzzyFind) {
   auto I = MemIndex::build(generateSymbols({"ns::A", "ns::B"}), RefSlab(),
RelationSlab()),
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -76,7 +76,11 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
+  auto DynamicContainsFile = Dynamic->indexedFiles();
   Static->lookup(Req, [&](const Symbol &S) {
+if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+ : S.CanonicalDeclaration.FileURI))
+  return;
 const Symbol *Sym = B.find(S.ID);
 RemainingIDs.erase(S.ID);
 if (!Sym)
Index: clang-tools-extra/clangd/index/FileIndex.cpp
===
--- clang-tools-extra/clangd/index/FileIndex.cpp
+++ clang-tools-extra/clangd/index/FileIndex.cpp
@@ -428,11 +428,17 @@
 // We are using the key received from ShardedIndex, so it should always
 // exist.
 assert(IF);
-PreambleSymbols.update(
-Uri, std::make_unique(std::move(*IF->Symbols)),
-std::make_unique(),
-std::make_unique(std::move(*IF->Relations)),
-/*CountReferences=*/false);
+auto FilePath = URI::resolve(Uri, Path);
+if (FilePath) {
+  PreambleSymbols.update(
+  *FilePath, std::make_unique(std::move(*IF->Symbols)),
+  std::make_unique(),
+  std::make_unique(std::move(*IF->Relations)),
+  /*CountReferences=*/false);
+} else {
+  elog("Update preamble: could not resolve URI {0}: {1}", Uri,
+   FilePath.takeError());
+}
   }
   size_t IndexVersion = 0;
   auto NewIndex =


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -290,6 +290,42 @@
   EXPECT_THAT(lookup(M, {}), UnorderedElementsAre());
 }
 
+TEST(MergeIndexTest, LookupRemovedDefinition) {
+  FileIndex DynamicIndex;
+  FileIndex StaticIndex;
+  MergedIndex Merge(&DynamicIndex, &StaticIndex);
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo definition
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo {};";
+  Test.Filename = "test.cc";
+  auto AST = Test.build();
+  StaticIndex.updateMain(testPath(Test.Filenam

[PATCH] D90157: [analyzer] Rework SValBuilder::evalCast function into maintainable and clear way

2020-12-22 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

Thank to @steakhal for the new tests.
//All// previous result differences have **gone** in `FFMPEG` and `twin` but a 
new //one// **appeared** in `PostgreSQL`.

  /src/common/d2s.c  Line 895 Memory copy function overflows the destination 
buffer alpha.unix.cstring.OutOfBounds
   
   

Here is an original link to the report: 
https://codechecker-demo.eastus.cloudapp.azure.com/Default?run=D90157&items-per-page=100
 (login: demo, pass: demo)

I'm keep going to work on the patch to remove this single difference.


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

https://reviews.llvm.org/D90157

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


[PATCH] D93683: [clangd] Do not take stale definition from the static index.

2020-12-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX added reviewers: sammccall, kadircet.
ArcsinX added a comment.

I also want to propose the similar patch for fuzzyFind() (as a part of this 
patch or a separate one), but I faced the following problem:

`Test.cpp`

  #define FOO 1

This example creates empty dynamic index for main file symbols and static index 
for preamble symbols (`FOO`). The location of `FOO` is inside `Test.cpp`, so 
(according to the logic that the static index could be stale) we should toss 
`FOO` from the static index (i.e. preamble symbols), but this behaviour is 
incorrect... Any advice?




Comment at: clang-tools-extra/clangd/index/FileIndex.cpp:434
+  PreambleSymbols.update(
+  *FilePath, std::make_unique(std::move(*IF->Symbols)),
+  std::make_unique(),

We do not need this change to fix behaviour for removed definition, but this is 
the only one place where we use URI instead of path as a key.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93683

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


[clang-tools-extra] 4b3633c - [clangd] Reuse buffer for JSONTransport::sendMessage

2020-12-22 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-12-22T11:30:56Z
New Revision: 4b3633cf2cb67220763494427f6db250bbd87494

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

LOG: [clangd] Reuse buffer for JSONTransport::sendMessage

Allocate a Buffer in the JSONTransport to be used when sending messages to the 
client.
This gets reused each time a message is sent, reducing in fewer malloc, which 
is always a bonus.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/JSONTransport.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/JSONTransport.cpp 
b/clang-tools-extra/clangd/JSONTransport.cpp
index eb5a83882b2b..662e5df4e27b 100644
--- a/clang-tools-extra/clangd/JSONTransport.cpp
+++ b/clang-tools-extra/clangd/JSONTransport.cpp
@@ -126,13 +126,13 @@ class JSONTransport : public Transport {
   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
   void sendMessage(llvm::json::Value Message) {
-std::string S;
-llvm::raw_string_ostream OS(S);
+OutputBuffer.clear();
+llvm::raw_svector_ostream OS(OutputBuffer);
 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
-OS.flush();
-Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
+Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
+<< OutputBuffer;
 Out.flush();
-vlog(">>> {0}\n", S);
+vlog(">>> {0}\n", OutputBuffer);
   }
 
   // Read raw string messages from input stream.
@@ -143,6 +143,7 @@ class JSONTransport : public Transport {
   llvm::Optional readDelimitedMessage();
   llvm::Optional readStandardMessage();
 
+  llvm::SmallVector OutputBuffer;
   std::FILE *In;
   llvm::raw_ostream &Out;
   llvm::raw_ostream &InMirror;



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


[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::sendMessage

2020-12-22 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4b3633cf2cb6: [clangd] Reuse buffer for 
JSONTransport::sendMessage (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

Files:
  clang-tools-extra/clangd/JSONTransport.cpp


Index: clang-tools-extra/clangd/JSONTransport.cpp
===
--- clang-tools-extra/clangd/JSONTransport.cpp
+++ clang-tools-extra/clangd/JSONTransport.cpp
@@ -126,13 +126,13 @@
   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
   void sendMessage(llvm::json::Value Message) {
-std::string S;
-llvm::raw_string_ostream OS(S);
+OutputBuffer.clear();
+llvm::raw_svector_ostream OS(OutputBuffer);
 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
-OS.flush();
-Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
+Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
+<< OutputBuffer;
 Out.flush();
-vlog(">>> {0}\n", S);
+vlog(">>> {0}\n", OutputBuffer);
   }
 
   // Read raw string messages from input stream.
@@ -143,6 +143,7 @@
   llvm::Optional readDelimitedMessage();
   llvm::Optional readStandardMessage();
 
+  llvm::SmallVector OutputBuffer;
   std::FILE *In;
   llvm::raw_ostream &Out;
   llvm::raw_ostream &InMirror;


Index: clang-tools-extra/clangd/JSONTransport.cpp
===
--- clang-tools-extra/clangd/JSONTransport.cpp
+++ clang-tools-extra/clangd/JSONTransport.cpp
@@ -126,13 +126,13 @@
   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
   void sendMessage(llvm::json::Value Message) {
-std::string S;
-llvm::raw_string_ostream OS(S);
+OutputBuffer.clear();
+llvm::raw_svector_ostream OS(OutputBuffer);
 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
-OS.flush();
-Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
+Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
+<< OutputBuffer;
 Out.flush();
-vlog(">>> {0}\n", S);
+vlog(">>> {0}\n", OutputBuffer);
   }
 
   // Read raw string messages from input stream.
@@ -143,6 +143,7 @@
   llvm::Optional readDelimitedMessage();
   llvm::Optional readStandardMessage();
 
+  llvm::SmallVector OutputBuffer;
   std::FILE *In;
   llvm::raw_ostream &Out;
   llvm::raw_ostream &InMirror;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This seems to break all tests on all platforms: 
http://45.33.8.238/linux/35854/step_7.txt

As far as I can tell, RenderSCPOptions is called unconditinoally and the error 
message is emitted at its start, before any Args.hasFlag checks -- so it's 
emitted every time a windows triple is passed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

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


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Also, rnk's comment above wasn't addressed as far as I can tell.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

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


[clang] 00065d5 - Revert "-fstack-clash-protection: Return an actual error when used on unsupported OS"

2020-12-22 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2020-12-22T06:51:19-05:00
New Revision: 00065d5cbd02b0f3fccb34881b58bcd0852b3970

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

LOG: Revert "-fstack-clash-protection: Return an actual error when used on 
unsupported OS"

This reverts commit 4d59c8fdb955ea0d668b854f467e12bce05a8857.
Breaks tens of thousands of tests, and had pending review comments, see
comments on https://reviews.llvm.org/D92245 (and e.g.
http://lab.llvm.org:8011/#/builders/109/builds/5236 for failures).

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/ToolChains/Clang.cpp
llvm/test/CodeGen/X86/stack-clash-large.ll

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 736950b0abb1..e92a4bf1dac5 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -273,8 +273,6 @@ def err_drv_unsupported_embed_bitcode
 : Error<"%0 is not supported with -fembed-bitcode">;
 def err_drv_bitcode_unsupported_on_toolchain : Error<
   "-fembed-bitcode is not supported on versions of iOS prior to 6.0">;
-def err_drv_stack_clash_protection_unsupported_on_toolchain : Error<
-  "-fstack-clash-protection is not supported on %0">;
 
 def err_drv_invalid_malign_branch_EQ : Error<
   "invalid argument '%0' to -malign-branch=; each element must be one of: %1">;

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index c04b350dae7d..300ab6e815e2 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3067,15 +3067,12 @@ static void RenderSSPOptions(const Driver &D, const 
ToolChain &TC,
   }
 }
 
-static void RenderSCPOptions(const Driver &D, const ToolChain &TC,
- const ArgList &Args, ArgStringList &CmdArgs) {
+static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
+ ArgStringList &CmdArgs) {
   const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
 
-  if (EffectiveTriple.isOSWindows()) {
-D.Diag(diag::err_drv_stack_clash_protection_unsupported_on_toolchain)
-<< EffectiveTriple.getOSName();
+  if (!EffectiveTriple.isOSLinux())
 return;
-  }
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
   !EffectiveTriple.isPPC64())
@@ -5553,7 +5550,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
 
   RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
-  RenderSCPOptions(D, TC, Args, CmdArgs);
+  RenderSCPOptions(TC, Args, CmdArgs);
   RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
 
   // Translate -mstackrealign

diff  --git a/llvm/test/CodeGen/X86/stack-clash-large.ll 
b/llvm/test/CodeGen/X86/stack-clash-large.ll
index 7deae310f617..dd53cd8f6964 100644
--- a/llvm/test/CodeGen/X86/stack-clash-large.ll
+++ b/llvm/test/CodeGen/X86/stack-clash-large.ll
@@ -1,7 +1,5 @@
 ; RUN: llc -mtriple=x86_64-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s 
 ; RUN: llc -mtriple=i686-linux-android < %s | FileCheck 
-check-prefix=CHECK-X86-32 %s 
-; RUN: llc -mtriple=x86_64-unknown-freebsd < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
-; RUN: llc -mtriple=x86_64-pc-linux-gnu < %s | FileCheck 
-check-prefix=CHECK-X86-64 %s
 
 define i32 @foo() local_unnamed_addr #0 {
 



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


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

reverted in 00065d5cbd02b0f3fccb34881b58bcd0852b3970 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

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


[PATCH] D92245: -fstack-clash-protection: Return an actual error when used on unsupported OS

2020-12-22 Thread Sylvestre Ledru via Phabricator via cfe-commits
sylvestre.ledru added a comment.

Thanks for the revert!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92245

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


[clang] 3b879fc - [ASTMatchers] Traverse-ignore range-for implementation details

2020-12-22 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2020-12-22T12:09:32Z
New Revision: 3b879fc97305849026db0e856920d318fadbc04b

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

LOG: [ASTMatchers] Traverse-ignore range-for implementation details

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

Added: 


Modified: 
clang/include/clang/AST/RecursiveASTVisitor.h
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 61e524793ec7..1426e569eabe 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -468,6 +468,8 @@ template  class RecursiveASTVisitor {
   DEF_TRAVERSE_TMPL_INST(Function)
 #undef DEF_TRAVERSE_TMPL_INST
 
+  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
+
 private:
   // These are helper methods used by more than one Traverse* method.
   bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
@@ -497,7 +499,6 @@ template  class RecursiveASTVisitor {
   bool VisitOMPClauseWithPreInit(OMPClauseWithPreInit *Node);
   bool VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *Node);
 
-  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
   bool PostVisitStmt(Stmt *S);
 };
 

diff  --git a/clang/lib/ASTMatchers/ASTMatchFinder.cpp 
b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
index cc9537144524..762885fa0052 100644
--- a/clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -463,6 +463,22 @@ class MatchASTVisitor : public 
RecursiveASTVisitor,
   bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit);
   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL);
 
+  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue) {
+if (auto *RF = dyn_cast(S)) {
+  for (auto *SubStmt : RF->children()) {
+if (SubStmt == RF->getInit() || SubStmt == RF->getLoopVarStmt() ||
+SubStmt == RF->getRangeInit() || SubStmt == RF->getBody()) {
+  TraverseStmt(SubStmt, Queue);
+} else {
+  ASTNodeNotSpelledInSourceScope RAII(this, true);
+  TraverseStmt(SubStmt, Queue);
+}
+  }
+  return true;
+}
+return RecursiveASTVisitor::dataTraverseNode(S, Queue);
+  }
+
   // Matches children or descendants of 'Node' with 'BaseMatcher'.
   bool memoizedMatchesRecursively(const DynTypedNode &Node, ASTContext &Ctx,
   const DynTypedMatcher &Matcher,

diff  --git a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
index 10d2d6ec3916..a3a3a911b85c 100644
--- a/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ b/clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2580,6 +2580,31 @@ struct CtorInitsNonTrivial : NonTrivial
 EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
+  {
+auto M = binaryOperator(hasOperatorName("!="));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = unaryOperator(hasOperatorName("++"));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__range";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__begin";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__end";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
 
   Code = R"cpp(
   void rangeFor()



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


[PATCH] D93596: [ASTMatchers] Traverse-ignore range-for implementation details

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b879fc97305: [ASTMatchers] Traverse-ignore range-for 
implementation details (authored by stephenkelly).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93596

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp


Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2580,6 +2580,31 @@
 EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
+  {
+auto M = binaryOperator(hasOperatorName("!="));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = unaryOperator(hasOperatorName("++"));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__range";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__begin";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__end";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
 
   Code = R"cpp(
   void rangeFor()
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -463,6 +463,22 @@
   bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit);
   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL);
 
+  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue) {
+if (auto *RF = dyn_cast(S)) {
+  for (auto *SubStmt : RF->children()) {
+if (SubStmt == RF->getInit() || SubStmt == RF->getLoopVarStmt() ||
+SubStmt == RF->getRangeInit() || SubStmt == RF->getBody()) {
+  TraverseStmt(SubStmt, Queue);
+} else {
+  ASTNodeNotSpelledInSourceScope RAII(this, true);
+  TraverseStmt(SubStmt, Queue);
+}
+  }
+  return true;
+}
+return RecursiveASTVisitor::dataTraverseNode(S, Queue);
+  }
+
   // Matches children or descendants of 'Node' with 'BaseMatcher'.
   bool memoizedMatchesRecursively(const DynTypedNode &Node, ASTContext &Ctx,
   const DynTypedMatcher &Matcher,
Index: clang/include/clang/AST/RecursiveASTVisitor.h
===
--- clang/include/clang/AST/RecursiveASTVisitor.h
+++ clang/include/clang/AST/RecursiveASTVisitor.h
@@ -468,6 +468,8 @@
   DEF_TRAVERSE_TMPL_INST(Function)
 #undef DEF_TRAVERSE_TMPL_INST
 
+  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
+
 private:
   // These are helper methods used by more than one Traverse* method.
   bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
@@ -497,7 +499,6 @@
   bool VisitOMPClauseWithPreInit(OMPClauseWithPreInit *Node);
   bool VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *Node);
 
-  bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
   bool PostVisitStmt(Stmt *S);
 };
 


Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2580,6 +2580,31 @@
 EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
 EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
+  {
+auto M = binaryOperator(hasOperatorName("!="));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = unaryOperator(hasOperatorName("++"));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesName("__range";
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = declStmt(hasSingleDecl(varDecl(matchesNa

[PATCH] D93688: [ASTMatchers] Ensure that we can match inside lambdas

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire created this revision.
steveire added a reviewer: aaron.ballman.
steveire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Because we don't know in ASTMatchFinder whether we're matching in AsIs
or IgnoreUnlessSpelledInSource mode, we need to traverse the lambda
twice, but store whether we're matching in nodes spelled in source or
not.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93688

Files:
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3065,6 +3065,18 @@
   traverse(TK_IgnoreUnlessSpelledInSource,
functionDecl(hasName("func14"), hasDescendant(floatLiteral(,
   langCxx20OrLater()));
+
+  Code = R"cpp(
+void foo() {
+auto l = [](int i) {
+if (i) return;
+};
+}
+)cpp";
+
+  EXPECT_TRUE(matches(Code, traverse(TK_AsIs, ifStmt(;
+  EXPECT_TRUE(
+  matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, ifStmt(;
 }
 
 TEST(IgnoringImpCasts, MatchesImpCasts) {
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -293,6 +293,10 @@
   Finder->IsMatchingInASTNodeNotSpelledInSource())
 return false;
 
+  if (!Finder->isTraversalIgnoringImplicitNodes() &&
+  Finder->IsMatchingInASTNodeNotAsIs())
+return false;
+
   auto N =
   Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
 
@@ -317,6 +321,10 @@
   Finder->IsMatchingInASTNodeNotSpelledInSource())
 return false;
 
+  if (!Finder->isTraversalIgnoringImplicitNodes() &&
+  Finder->IsMatchingInASTNodeNotAsIs())
+return false;
+
   auto N =
   Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
 
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -475,6 +475,57 @@
 }
   }
   return true;
+} else if (auto *LE = dyn_cast(S)) {
+
+  for (unsigned I = 0, N = LE->capture_size(); I != N; ++I) {
+const auto *C = LE->capture_begin() + I;
+{
+  // C->isExplicit();
+  TraverseLambdaCapture(LE, C, LE->capture_init_begin()[I]);
+}
+  }
+
+  {
+ASTNodeNotSpelledInSourceScope RAII(this, true);
+TraverseDecl(LE->getLambdaClass());
+  }
+  {
+ASTNodeNotAsIsSourceScope RAII(this, true);
+
+// We need to poke around to find the bits that might be explicitly
+// written.
+TypeLoc TL = LE->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
+FunctionProtoTypeLoc Proto = TL.getAsAdjusted();
+
+if (auto *TPL = LE->getTemplateParameterList()) {
+  for (NamedDecl *D : *TPL) {
+TraverseDecl(D);
+  }
+  if (Expr *RequiresClause = TPL->getRequiresClause()) {
+TraverseStmt(RequiresClause);
+  }
+}
+
+if (LE->hasExplicitParameters()) {
+  // Visit parameters.
+  for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
+TraverseDecl(Proto.getParam(I));
+}
+
+auto *T = Proto.getTypePtr();
+for (const auto &E : T->exceptions())
+  TraverseType(E);
+
+if (Expr *NE = T->getNoexceptExpr())
+  TraverseStmt(NE, Queue);
+
+if (LE->hasExplicitResultType())
+  TraverseTypeLoc(Proto.getReturnLoc());
+TraverseStmt(LE->getTrailingRequiresClause());
+
+TraverseStmt(LE->getBody());
+  }
+  return true;
 }
 return RecursiveASTVisitor::dataTraverseNode(S, Queue);
   }
@@ -617,6 +668,9 @@
   bool IsMatchingInASTNodeNotSpelledInSource() const override {
 return TraversingASTNodeNotSpelledInSource;
   }
+  bool IsMatchingInASTNodeNotAsIs() const override {
+return TraversingASTNodeNotAsIs;
+  }
 
   bool TraverseTemplateInstantiations(ClassTemplateDecl *D) {
 ASTNodeNotSpelledInSourceScope RAII(this, true);
@@ -638,6 +692,7 @@
 
 private:
   bool TraversingASTNodeNotSpelledInSource = false;
+  bool TraversingASTNodeNotAsIs = false;
   bool TraversingASTChildrenNotSpelledInSource = false;
 
   struct ASTNodeNotSpelledInSourceScope {
@@ -654,6 +709,18 @@
 bool MB;
   };
 
+  struct ASTNodeNotAsIsSourceScope {
+ASTNodeNotAsIsSourceScope(MatchASTVisitor *V, bool B)
+: MV(V), MB(V->TraversingASTNodeNotA

[PATCH] D93626: [clang-format] PR48535 clang-format Incorrectly Removes Space After C Style Cast When Type Is Not a Pointer

2020-12-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay marked an inline comment as done.
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:1976
+   tok::kw_co_yield, tok::equal, tok::kw_delete,
+   tok::kw_sizeof, tok::kw_throw) ||
 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,

HazardyKnusperkeks wrote:
> What's the policy towards unrelated changes?
ideally not, but we try to keep clang-format, clang-formatted.

I'll remove from the patch and apply separately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93626

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


[PATCH] D93626: [clang-format] PR48535 clang-format Incorrectly Removes Space After C Style Cast When Type Is Not a Pointer

2020-12-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 313295.
MyDeveloperDay marked an inline comment as done.
MyDeveloperDay added a comment.

remove unrelated change


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

https://reviews.llvm.org/D93626

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -11989,6 +11989,20 @@
"  do_something((int) i);\n"
"} while (something( ));",
Spaces);
+
+  verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
+  verifyFormat("size_t idx = (size_t) a;", Spaces);
+  verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
+  Spaces.SpaceAfterCStyleCast = false;
+  verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
+  verifyFormat("size_t idx = (size_t)a;", Spaces);
+  verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
 }
 
 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1915,6 +1915,13 @@
 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
   return true;
 
+if (Tok.Next->is(tok::l_paren) &&
+!(Tok.Previous && Tok.Previous->is(tok::identifier) &&
+  Tok.Previous->Previous &&
+  Tok.Previous->Previous->isOneOf(tok::arrowstar, tok::arrow,
+  tok::star)))
+  return true;
+
 if (!Tok.Next->Next)
   return false;
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -11989,6 +11989,20 @@
"  do_something((int) i);\n"
"} while (something( ));",
Spaces);
+
+  verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
+  verifyFormat("size_t idx = (size_t) a;", Spaces);
+  verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
+  Spaces.SpaceAfterCStyleCast = false;
+  verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
+  verifyFormat("size_t idx = (size_t)a;", Spaces);
+  verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
+  verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
 }
 
 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1915,6 +1915,13 @@
 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
   return true;
 
+if (Tok.Next->is(tok::l_paren) &&
+!(Tok.Previous && Tok.Previous->is(tok::identifier) &&
+  Tok.Previous->Previous &&
+  Tok.Previous->Previous->isOneOf(tok::arrowstar, tok::arrow,
+  tok::star)))
+  return true;
+
 if (!Tok.Next->Next)
   return false;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93688: [ASTMatchers] Ensure that we can match inside lambdas

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313296.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93688

Files:
  clang/include/clang/ASTMatchers/ASTMatchersInternal.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/lib/ASTMatchers/ASTMatchersInternal.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3065,6 +3065,33 @@
   traverse(TK_IgnoreUnlessSpelledInSource,
functionDecl(hasName("func14"), hasDescendant(floatLiteral(,
   langCxx20OrLater()));
+
+  Code = R"cpp(
+void foo() {
+int explicit_captured = 0;
+int implicit_captured = 0;
+auto l = [&, explicit_captured](int i) {
+if (i || explicit_captured || implicit_captured) return;
+};
+}
+)cpp";
+
+  EXPECT_TRUE(matches(Code, traverse(TK_AsIs, ifStmt(;
+  EXPECT_TRUE(
+  matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, ifStmt(;
+
+  auto lambdaExplicitCapture = declRefExpr(
+  to(varDecl(hasName("explicit_captured"))), unless(hasAncestor(ifStmt(;
+  auto lambdaImplicitCapture = declRefExpr(
+  to(varDecl(hasName("implicit_captured"))), unless(hasAncestor(ifStmt(;
+
+  EXPECT_TRUE(matches(Code, traverse(TK_AsIs, lambdaExplicitCapture)));
+  EXPECT_TRUE(matches(
+  Code, traverse(TK_IgnoreUnlessSpelledInSource, lambdaExplicitCapture)));
+
+  EXPECT_TRUE(matches(Code, traverse(TK_AsIs, lambdaImplicitCapture)));
+  EXPECT_FALSE(matches(
+  Code, traverse(TK_IgnoreUnlessSpelledInSource, lambdaImplicitCapture)));
 }
 
 TEST(IgnoringImpCasts, MatchesImpCasts) {
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -293,6 +293,10 @@
   Finder->IsMatchingInASTNodeNotSpelledInSource())
 return false;
 
+  if (!Finder->isTraversalIgnoringImplicitNodes() &&
+  Finder->IsMatchingInASTNodeNotAsIs())
+return false;
+
   auto N =
   Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
 
@@ -317,6 +321,10 @@
   Finder->IsMatchingInASTNodeNotSpelledInSource())
 return false;
 
+  if (!Finder->isTraversalIgnoringImplicitNodes() &&
+  Finder->IsMatchingInASTNodeNotAsIs())
+return false;
+
   auto N =
   Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
 
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -475,6 +475,58 @@
 }
   }
   return true;
+} else if (auto *LE = dyn_cast(S)) {
+
+  for (unsigned I = 0, N = LE->capture_size(); I != N; ++I) {
+const auto *C = LE->capture_begin() + I;
+{
+  ASTNodeNotSpelledInSourceScope RAII(
+  this, TraversingASTNodeNotSpelledInSource || !C->isExplicit());
+  TraverseLambdaCapture(LE, C, LE->capture_init_begin()[I]);
+}
+  }
+
+  {
+ASTNodeNotSpelledInSourceScope RAII(this, true);
+TraverseDecl(LE->getLambdaClass());
+  }
+  {
+ASTNodeNotAsIsSourceScope RAII(this, true);
+
+// We need to poke around to find the bits that might be explicitly
+// written.
+TypeLoc TL = LE->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
+FunctionProtoTypeLoc Proto = TL.getAsAdjusted();
+
+if (auto *TPL = LE->getTemplateParameterList()) {
+  for (NamedDecl *D : *TPL) {
+TraverseDecl(D);
+  }
+  if (Expr *RequiresClause = TPL->getRequiresClause()) {
+TraverseStmt(RequiresClause);
+  }
+}
+
+if (LE->hasExplicitParameters()) {
+  // Visit parameters.
+  for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
+TraverseDecl(Proto.getParam(I));
+}
+
+auto *T = Proto.getTypePtr();
+for (const auto &E : T->exceptions())
+  TraverseType(E);
+
+if (Expr *NE = T->getNoexceptExpr())
+  TraverseStmt(NE, Queue);
+
+if (LE->hasExplicitResultType())
+  TraverseTypeLoc(Proto.getReturnLoc());
+TraverseStmt(LE->getTrailingRequiresClause());
+
+TraverseStmt(LE->getBody());
+  }
+  return true;
 }
 return RecursiveASTVisitor::dataTraverseNode(S, Queue);
   }
@@ -617,6 +669,9 @@
   bool IsMatchingInASTNodeNotSpelledInSource() const override {
 return TraversingASTNodeNotSpelledInSource;
   }
+  bool IsMatchingInASTNodeNotAsIs() const overrid

[PATCH] D93490: [clang-format] PR48539 ReflowComments breaks Qt translation comments

2020-12-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 313297.
MyDeveloperDay added a comment.

remove //= and //~


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

https://reviews.llvm.org/D93490

Files:
  clang/lib/Format/BreakableToken.cpp
  clang/unittests/Format/FormatTestComments.cpp


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -702,6 +702,12 @@
"  // long 1 2 3 4 5 6\n"
"}",
getLLVMStyleWithColumns(20)));
+
+  EXPECT_EQ("//: A comment that\n"
+"//: doesn't fit on\n"
+"//: one line",
+format("//: A comment that doesn't fit on one line",
+   getLLVMStyleWithColumns(20)));
 }
 
 TEST_F(FormatTestComments, PreservesHangingIndentInCxxComments) {
Index: clang/lib/Format/BreakableToken.cpp
===
--- clang/lib/Format/BreakableToken.cpp
+++ clang/lib/Format/BreakableToken.cpp
@@ -41,8 +41,8 @@
 
 static StringRef getLineCommentIndentPrefix(StringRef Comment,
 const FormatStyle &Style) {
-  static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", 
"//",
-"//!"};
+  static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///",
+"//",   "//!",  "//:"};
   static const char *const KnownTextProtoPrefixes[] = {"//", "#", "##", "###",
""};
   ArrayRef KnownPrefixes(KnownCStylePrefixes);


Index: clang/unittests/Format/FormatTestComments.cpp
===
--- clang/unittests/Format/FormatTestComments.cpp
+++ clang/unittests/Format/FormatTestComments.cpp
@@ -702,6 +702,12 @@
"  // long 1 2 3 4 5 6\n"
"}",
getLLVMStyleWithColumns(20)));
+
+  EXPECT_EQ("//: A comment that\n"
+"//: doesn't fit on\n"
+"//: one line",
+format("//: A comment that doesn't fit on one line",
+   getLLVMStyleWithColumns(20)));
 }
 
 TEST_F(FormatTestComments, PreservesHangingIndentInCxxComments) {
Index: clang/lib/Format/BreakableToken.cpp
===
--- clang/lib/Format/BreakableToken.cpp
+++ clang/lib/Format/BreakableToken.cpp
@@ -41,8 +41,8 @@
 
 static StringRef getLineCommentIndentPrefix(StringRef Comment,
 const FormatStyle &Style) {
-  static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", "//",
-"//!"};
+  static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///",
+"//",   "//!",  "//:"};
   static const char *const KnownTextProtoPrefixes[] = {"//", "#", "##", "###",
""};
   ArrayRef KnownPrefixes(KnownCStylePrefixes);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c4fc8a2 - [clang-format] NFC keep the code clang-formatted

2020-12-22 Thread via cfe-commits

Author: mydeveloperday
Date: 2020-12-22T12:46:14Z
New Revision: c4fc8a21d1dbfd2e269a59533808913b46faa8ce

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

LOG: [clang-format] NFC keep the code clang-formatted

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
old mode 100644
new mode 100755
index 821b46b75f6b..733ca1e0e852
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1964,9 +1964,9 @@ class AnnotatingParser {
 
 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
tok::comma, tok::semi, tok::kw_return, tok::colon,
-   tok::kw_co_return, tok::kw_co_await, 
tok::kw_co_yield,
-   tok::equal, tok::kw_delete, tok::kw_sizeof,
-   tok::kw_throw) ||
+   tok::kw_co_return, tok::kw_co_await,
+   tok::kw_co_yield, tok::equal, tok::kw_delete,
+   tok::kw_sizeof, tok::kw_throw) ||
 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
TT_UnaryOperator, TT_CastRParen))
   return TT_UnaryOperator;



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


[PATCH] D93626: [clang-format] PR48535 clang-format Incorrectly Removes Space After C Style Cast When Type Is Not a Pointer

2020-12-22 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM now. I tried to find other cases where this change may change the 
behaviour but couldn't. Have you tried applying to some bigger repo and see 
what you get? The best would be a repo with SpaceAfterCStyleCast=true.


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

https://reviews.llvm.org/D93626

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


[PATCH] D91054: [Clang][OpenMP] Frontend work for sections - D89671

2020-12-22 Thread Chirag Khandelwal via Phabricator via cfe-commits
AMDChirag updated this revision to Diff 313303.
AMDChirag marked an inline comment as done.
AMDChirag added a comment.

Updated code according to the changes in LLVM side of things.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91054

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -3546,6 +3546,72 @@
 }
 
 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
+  if (CGM.getLangOpts().OpenMPIRBuilder) {
+llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+using BodyGenCallbackTy = llvm::OpenMPIRBuilder::BGenCallbackTy;
+using FinalizationCallbackTy = llvm::OpenMPIRBuilder::FinalizeCallbackTy;
+
+auto FiniCB = [this](InsertPointTy IP) {
+  OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
+};
+// For now, it is the same as FiniCB, but is called for each of the 
sections
+// Will be updated in the future as required
+auto SectionFiniCB = [this](InsertPointTy IP) {
+  OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
+};
+
+const CapturedStmt *ICS = S.getInnermostCapturedStmt();
+const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
+const auto *CS = dyn_cast(CapturedStmt);
+llvm::SmallVector SectionCBVector;
+llvm::SmallVector SectionFiniCBVector;
+if (CS) {
+  for (const Stmt *SubStmt : CS->children()) {
+auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
+ InsertPointTy CodeGenIP,
+ llvm::BasicBlock &FiniBB) {
+  OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
+ FiniBB);
+  OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP,
+ FiniBB);
+};
+SectionCBVector.push_back(SectionCB);
+SectionFiniCBVector.push_back(SectionFiniCB);
+  }
+} else {
+  auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
+InsertPointTy CodeGenIP,
+llvm::BasicBlock &FiniBB) {
+OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, 
FiniBB);
+OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP,
+   FiniBB);
+  };
+  SectionCBVector.push_back(SectionCB);
+}
+
+// Privatization callback that performs appropriate action for
+// shared/private/firstprivate/lastprivate/copyin/... variables.
+//
+// TODO: This defaults to shared right now.
+auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+ llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
+  // The next line is appropriate only for variables (Val) with the
+  // data-sharing attribute "shared".
+  ReplVal = &Val;
+
+  return CodeGenIP;
+};
+
+CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
+CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
+llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
+AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
+Builder.restoreIP(OMPBuilder.createSections(
+Builder, AllocaIP, SectionCBVector, SectionFiniCBVector, PrivCB, 
FiniCB,
+S.hasCancel(), S.getSingleClause()));
+return;
+  }
   {
 auto LPCRegion =
 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
@@ -5970,7 +6036,9 @@
 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
 // TODO: This check is necessary as we only generate `omp parallel` through
 // the OpenMPIRBuilder for now.
-if (S.getCancelRegion() == OMPD_parallel) {
+if (S.getCancelRegion() == OMPD_parallel ||
+S.getCancelRegion() == OMPD_sections ||
+S.getCancelRegion() == OMPD_section) {
   llvm::Value *IfCondition = nullptr;
   if (IfCond)
 IfCondition = EmitScalarExpr(IfCond,


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -3546,6 +3546,72 @@
 }
 
 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
+  if (CGM.getLangOpts().OpenMPIRBuilder) {
+llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+using BodyGenCallbackTy = llvm::OpenMPIRBuilder::BGenCallbackTy;
+using FinalizationCallbackTy 

[PATCH] D84924: [clang-tidy] Added command line option `fix-notes`

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h:231
+/// If \p AnyFix is true and there is no FixIt attached to the Message,
+/// returns the first FixIt attached to any notes in the message.
+/// If no FixIt is found, returns nullptr.

Comment seems stale.



Comment at: clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp:186
-  // Emit a fix and a fix description of the check;
-  diag(Context.FoundUsingDecl->getLocation(),
-   /*Description=*/"remove the using", DiagnosticIDs::Note)

Should this change be a separate patch?



Comment at: 
clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp:222
 
-  auto ParamDiag =
-  Check->diag(Location,

Same for these changes?



Comment at: clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp:500
+  // --fix-errors and --fix-notes imply --fix.
+  FixBehaviour Behaviour = FixNotes ? FB_FixNotes
+   : (Fix || FixErrors) ? FB_Fix

Might as well fix this clang-format warning.



Comment at: clang-tools-extra/docs/clang-tidy/index.rst:176
  well.
+--fix-notes- 
+ If a warning has no fix, but one of the 

This sort of reads like it may apply fixes from multiple notes. How about: `If 
a warning has no fix, but a single fix can be found through an associated 
diagnostic note, apply the fix. Specifying this flag will implicitly enable the 
'--fix' flag.`

(Note, I also quietly switched from using `` to using '' for quoting -- that 
seems to be the consistent style here.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84924

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


[clang] 63a2481 - [clang][cli] Implement `getAllArgValues` marshalling

2020-12-22 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-22T14:11:16+01:00
New Revision: 63a24816f561a5d8e28ca7054892bd8602618be4

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

LOG: [clang][cli] Implement `getAllArgValues` marshalling

This infrastructure can be used ~30 more command line options.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp
clang/unittests/Frontend/CompilerInvocationTest.cpp
llvm/include/llvm/Option/OptParser.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 82c4e9399d9d..3373984b76ae 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1915,7 +1915,8 @@ def fsystem_module : Flag<["-"], "fsystem-module">, 
Flags<[CC1Option]>,
   MarshallingInfoFlag<"FrontendOpts.IsSystemModule">;
 def fmodule_map_file : Joined<["-"], "fmodule-map-file=">,
   Group, Flags<[NoXarchOption,CC1Option]>, MetaVarName<"">,
-  HelpText<"Load this module map file">;
+  HelpText<"Load this module map file">,
+  MarshallingInfoStringVector<"FrontendOpts.ModuleMapFiles">;
 def fmodule_file : Joined<["-"], "fmodule-file=">,
   Group, Flags<[NoXarchOption,CC1Option]>, 
MetaVarName<"[=]">,
   HelpText<"Specify the mapping of module name to precompiled module file, or 
load a module file if name is omitted.">;

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index fc5fd1547599..d7c1a6ffd600 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -323,6 +323,23 @@ static Optional 
normalizeStringIntegral(OptSpecifier Opt, int,
   return Res;
 }
 
+static Optional>
+normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
+  DiagnosticsEngine &) {
+  return Args.getAllArgValues(Opt);
+}
+
+static void denormalizeStringVector(SmallVectorImpl &Args,
+const char *Spelling,
+CompilerInvocation::StringAllocator SA,
+Option::OptionClass OptClass,
+unsigned TableIndex,
+const std::vector &Values) {
+  for (const std::string &Value : Values) {
+denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
+  }
+}
+
 static Optional normalizeTriple(OptSpecifier Opt, int TableIndex,
  const ArgList &Args,
  DiagnosticsEngine &Diags) {
@@ -1715,7 +1732,6 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, 
ArgList &Args,
   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
-  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
   // Only the -fmodule-file= form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
 StringRef Val = A->getValue();

diff  --git a/clang/unittests/Frontend/CompilerInvocationTest.cpp 
b/clang/unittests/Frontend/CompilerInvocationTest.cpp
index 71e8d0907fc8..5738f7079171 100644
--- a/clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ b/clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -18,6 +18,7 @@ using namespace llvm;
 using namespace clang;
 
 using ::testing::Contains;
+using ::testing::HasSubstr;
 using ::testing::StrEq;
 
 namespace {
@@ -408,6 +409,45 @@ TEST_F(CommandLineTest, JoinedEnumDefault) {
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("legacy";
 }
 
+TEST_F(CommandLineTest, StringVectorEmpty) {
+  const char *Args[] = {""};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getFrontendOpts().ModuleMapFiles.empty());
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+  ASSERT_THAT(GeneratedArgs, Not(Contains(HasSubstr("-fmodule-map-file=";
+}
+
+TEST_F(CommandLineTest, StringVectorSingle) {
+  const char *Args[] = {"-fmodule-map-file=a"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getFrontendOpts().ModuleMapFiles,
+std::vector({"a"}));
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+  ASSERT_EQ(count(GeneratedArgs, StringRef("-fmodule-map-file=a")), 1);
+}
+
+TEST_F(CommandLineTest, StringVectorMultiple) {
+  const char *Args[] = {"-fmodule-map-file=a", "-fmodule-map-file=b"};
+
+  CompilerInvocation::CreateFromArgs(I

[PATCH] D93631: [clang][cli] Implement `getAllArgValues` marshalling

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG63a24816f561: [clang][cli] Implement `getAllArgValues` 
marshalling (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D93631?vs=313090&id=313306#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93631

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Frontend/CompilerInvocationTest.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -167,6 +167,12 @@
   code Denormalizer = "denormalizeString";
 }
 
+class MarshallingInfoStringVector
+  : MarshallingInfo({})"> {
+  code Normalizer = "normalizeStringVector";
+  code Denormalizer = "denormalizeStringVector";
+}
+
 class MarshallingInfoFlag
   : MarshallingInfo {
   code Normalizer = "normalizeSimpleFlag";
Index: clang/unittests/Frontend/CompilerInvocationTest.cpp
===
--- clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -18,6 +18,7 @@
 using namespace clang;
 
 using ::testing::Contains;
+using ::testing::HasSubstr;
 using ::testing::StrEq;
 
 namespace {
@@ -408,6 +409,45 @@
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("legacy";
 }
 
+TEST_F(CommandLineTest, StringVectorEmpty) {
+  const char *Args[] = {""};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getFrontendOpts().ModuleMapFiles.empty());
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+  ASSERT_THAT(GeneratedArgs, Not(Contains(HasSubstr("-fmodule-map-file=";
+}
+
+TEST_F(CommandLineTest, StringVectorSingle) {
+  const char *Args[] = {"-fmodule-map-file=a"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getFrontendOpts().ModuleMapFiles,
+std::vector({"a"}));
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+  ASSERT_EQ(count(GeneratedArgs, StringRef("-fmodule-map-file=a")), 1);
+}
+
+TEST_F(CommandLineTest, StringVectorMultiple) {
+  const char *Args[] = {"-fmodule-map-file=a", "-fmodule-map-file=b"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getFrontendOpts().ModuleMapFiles ==
+  std::vector({"a", "b"}));
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+  ASSERT_EQ(count(GeneratedArgs, StringRef("-fmodule-map-file=a")), 1);
+  ASSERT_EQ(count(GeneratedArgs, StringRef("-fmodule-map-file=b")), 1);
+}
+
 // Tree of boolean options that can be (directly or transitively) implied by
 // their parent:
 //
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -323,6 +323,23 @@
   return Res;
 }
 
+static Optional>
+normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
+  DiagnosticsEngine &) {
+  return Args.getAllArgValues(Opt);
+}
+
+static void denormalizeStringVector(SmallVectorImpl &Args,
+const char *Spelling,
+CompilerInvocation::StringAllocator SA,
+Option::OptionClass OptClass,
+unsigned TableIndex,
+const std::vector &Values) {
+  for (const std::string &Value : Values) {
+denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
+  }
+}
+
 static Optional normalizeTriple(OptSpecifier Opt, int TableIndex,
  const ArgList &Args,
  DiagnosticsEngine &Diags) {
@@ -1715,7 +1732,6 @@
   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
-  Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
   // Only the -fmodule-file= form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
 StringRef Val = A->getValue();
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1915,7 +1915,8 @@
   MarshallingInfoFlag<"FrontendOpts.IsSystemModule">;
 def fmodule_map_file

[PATCH] D91054: [Clang][OpenMP] Frontend work for sections - D89671

2020-12-22 Thread Chirag Khandelwal via Phabricator via cfe-commits
AMDChirag updated this revision to Diff 313307.
AMDChirag added a comment.

Updated `BGenCallbackTy` to `StorableBodyGenCallbackTy`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91054

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -3546,6 +3546,72 @@
 }
 
 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
+  if (CGM.getLangOpts().OpenMPIRBuilder) {
+llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
+using FinalizationCallbackTy = llvm::OpenMPIRBuilder::FinalizeCallbackTy;
+
+auto FiniCB = [this](InsertPointTy IP) {
+  OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
+};
+// For now, it is the same as FiniCB, but is called for each of the 
sections
+// Will be updated in the future as required
+auto SectionFiniCB = [this](InsertPointTy IP) {
+  OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP);
+};
+
+const CapturedStmt *ICS = S.getInnermostCapturedStmt();
+const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt();
+const auto *CS = dyn_cast(CapturedStmt);
+llvm::SmallVector SectionCBVector;
+llvm::SmallVector SectionFiniCBVector;
+if (CS) {
+  for (const Stmt *SubStmt : CS->children()) {
+auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP,
+ InsertPointTy CodeGenIP,
+ llvm::BasicBlock &FiniBB) {
+  OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
+ FiniBB);
+  OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP,
+ FiniBB);
+};
+SectionCBVector.push_back(SectionCB);
+SectionFiniCBVector.push_back(SectionFiniCB);
+  }
+} else {
+  auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP,
+InsertPointTy CodeGenIP,
+llvm::BasicBlock &FiniBB) {
+OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, 
FiniBB);
+OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP,
+   FiniBB);
+  };
+  SectionCBVector.push_back(SectionCB);
+}
+
+// Privatization callback that performs appropriate action for
+// shared/private/firstprivate/lastprivate/copyin/... variables.
+//
+// TODO: This defaults to shared right now.
+auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
+ llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) {
+  // The next line is appropriate only for variables (Val) with the
+  // data-sharing attribute "shared".
+  ReplVal = &Val;
+
+  return CodeGenIP;
+};
+
+CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP);
+CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI);
+llvm::OpenMPIRBuilder::InsertPointTy AllocaIP(
+AllocaInsertPt->getParent(), AllocaInsertPt->getIterator());
+Builder.restoreIP(OMPBuilder.createSections(
+Builder, AllocaIP, SectionCBVector, SectionFiniCBVector, PrivCB, 
FiniCB,
+S.hasCancel(), S.getSingleClause()));
+return;
+  }
   {
 auto LPCRegion =
 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S);
@@ -5970,7 +6036,9 @@
 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
 // TODO: This check is necessary as we only generate `omp parallel` through
 // the OpenMPIRBuilder for now.
-if (S.getCancelRegion() == OMPD_parallel) {
+if (S.getCancelRegion() == OMPD_parallel ||
+S.getCancelRegion() == OMPD_sections ||
+S.getCancelRegion() == OMPD_section) {
   llvm::Value *IfCondition = nullptr;
   if (IfCond)
 IfCondition = EmitScalarExpr(IfCond,


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -3546,6 +3546,72 @@
 }
 
 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) {
+  if (CGM.getLangOpts().OpenMPIRBuilder) {
+llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
+using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
+using FinalizationCallbackTy = llvm::OpenMPIRBuilder::Fi

[PATCH] D93628: [clang] NFC: Refactor custom class into a lambda in CompilerInvocation

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 313309.
jansvoboda11 added a comment.

Extract SFINAE check into function again


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93628

Files:
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -157,33 +157,26 @@
   Args.push_back(Spelling);
 }
 
-namespace {
-template  struct FlagToValueNormalizer {
-  T Value;
+template  static constexpr bool is_uint64_t_convertible() {
+  return !std::is_same::value &&
+ llvm::is_integral_or_enum::value;
+}
 
-  Optional operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &) {
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
+ DiagnosticsEngine &) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
-  }
-};
-} // namespace
-
-template  static constexpr bool is_int_convertible() {
-  return sizeof(T) <= sizeof(uint64_t) &&
- std::is_trivially_constructible::value &&
- std::is_trivially_constructible::value;
-}
-
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{Value};
+  };
 }
 
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{std::move(Value)};
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }
 
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -157,33 +157,26 @@
   Args.push_back(Spelling);
 }
 
-namespace {
-template  struct FlagToValueNormalizer {
-  T Value;
+template  static constexpr bool is_uint64_t_convertible() {
+  return !std::is_same::value &&
+ llvm::is_integral_or_enum::value;
+}
 
-  Optional operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &) {
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
+ DiagnosticsEngine &) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
-  }
-};
-} // namespace
-
-template  static constexpr bool is_int_convertible() {
-  return sizeof(T) <= sizeof(uint64_t) &&
- std::is_trivially_constructible::value &&
- std::is_trivially_constructible::value;
-}
-
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{Value};
+  };
 }
 
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{std::move(Value)};
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }
 
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93628: [clang] NFC: Refactor custom class into a lambda in CompilerInvocation

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/lib/Frontend/CompilerInvocation.cpp:176
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }

dexonsmith wrote:
> (not a behaviour change but) I wonder if this correct for signed types, where 
> the conversion back to `T` could change sign if it's a negative value. Should 
> there be an assertion that the value is `>= 0`? (Probably to do separately / 
> outside this patch)
It might be good to be defensive here. I'll put that into a follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93628

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


[clang] bef9eb8 - [clang] NFC: Refactor custom class into a lambda in CompilerInvocation

2020-12-22 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-22T14:45:29+01:00
New Revision: bef9eb84b2fb17b22ca771c8c5c34a85f141168d

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

LOG: [clang] NFC: Refactor custom class into a lambda in CompilerInvocation

Change `makeFlagToValueNormalizer` so that one specialization converts all 
integral/enum arguments into `uint64_t` and forwards them to the more generic 
version.

This makes it easy to replace the custom `FlagToValueNormalizer` struct with a 
lambda, which is the common approach in other (de)normalizers.

Finally, drop custom `is_int_convertbile` in favor of 
`llvm::is_integral_or_enum`.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index d7c1a6ffd600..44453ad462c4 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -157,33 +157,26 @@ static void denormalizeSimpleFlag(SmallVectorImpl &Args,
   Args.push_back(Spelling);
 }
 
-namespace {
-template  struct FlagToValueNormalizer {
-  T Value;
+template  static constexpr bool is_uint64_t_convertible() {
+  return !std::is_same::value &&
+ llvm::is_integral_or_enum::value;
+}
 
-  Optional operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &) {
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
+ DiagnosticsEngine &) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
-  }
-};
-} // namespace
-
-template  static constexpr bool is_int_convertible() {
-  return sizeof(T) <= sizeof(uint64_t) &&
- std::is_trivially_constructible::value &&
- std::is_trivially_constructible::value;
-}
-
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{Value};
+  };
 }
 
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{std::move(Value)};
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }
 
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,



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


[PATCH] D93628: [clang] NFC: Refactor custom class into a lambda in CompilerInvocation

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbef9eb84b2fb: [clang] NFC: Refactor custom class into a 
lambda in CompilerInvocation (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93628

Files:
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -157,33 +157,26 @@
   Args.push_back(Spelling);
 }
 
-namespace {
-template  struct FlagToValueNormalizer {
-  T Value;
+template  static constexpr bool is_uint64_t_convertible() {
+  return !std::is_same::value &&
+ llvm::is_integral_or_enum::value;
+}
 
-  Optional operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &) {
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
+ DiagnosticsEngine &) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
-  }
-};
-} // namespace
-
-template  static constexpr bool is_int_convertible() {
-  return sizeof(T) <= sizeof(uint64_t) &&
- std::is_trivially_constructible::value &&
- std::is_trivially_constructible::value;
-}
-
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{Value};
+  };
 }
 
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{std::move(Value)};
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }
 
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -157,33 +157,26 @@
   Args.push_back(Spelling);
 }
 
-namespace {
-template  struct FlagToValueNormalizer {
-  T Value;
+template  static constexpr bool is_uint64_t_convertible() {
+  return !std::is_same::value &&
+ llvm::is_integral_or_enum::value;
+}
 
-  Optional operator()(OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &) {
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
+ DiagnosticsEngine &) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
-  }
-};
-} // namespace
-
-template  static constexpr bool is_int_convertible() {
-  return sizeof(T) <= sizeof(uint64_t) &&
- std::is_trivially_constructible::value &&
- std::is_trivially_constructible::value;
-}
-
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{Value};
+  };
 }
 
-template (), bool> = false>
-static FlagToValueNormalizer makeFlagToValueNormalizer(T Value) {
-  return FlagToValueNormalizer{std::move(Value)};
+template (), bool> = false>
+static auto makeFlagToValueNormalizer(T Value) {
+  return makeFlagToValueNormalizer(uint64_t(Value));
 }
 
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93586: [InstCombine] use poison as placeholder for undemanded elems

2020-12-22 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

I'm sorry I've only just started looking at this - are you saying that you want 
to handle all "insertelement undef" cases in one go and not just a series of 
patcches after this one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93586

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


[PATCH] D91927: [X86] Add x86_amx type for intel AMX.

2020-12-22 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke updated this revision to Diff 313315.
LuoYuanke added a comment.

Address Pengfei's comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91927

Files:
  clang/test/CodeGen/X86/amx_api.c
  llvm/include/llvm-c/Core.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/CodeGen/ValueTypes.td
  llvm/include/llvm/IR/DataLayout.h
  llvm/include/llvm/IR/Intrinsics.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/IR/IntrinsicsX86.td
  llvm/include/llvm/IR/Type.h
  llvm/include/llvm/Support/MachineValueType.h
  llvm/lib/Analysis/ConstantFolding.cpp
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/CodeGen/ValueTypes.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/ConstantFold.cpp
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/LLVMContextImpl.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/IR/Type.cpp
  llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86LowerAMXType.cpp
  llvm/lib/Target/X86/X86RegisterInfo.td
  llvm/test/CodeGen/X86/AMX/amx-across-func.ll
  llvm/test/CodeGen/X86/AMX/amx-config.ll
  llvm/test/CodeGen/X86/AMX/amx-spill.ll
  llvm/test/CodeGen/X86/AMX/amx-type.ll
  llvm/utils/TableGen/CodeGenTarget.cpp
  llvm/utils/TableGen/IntrinsicEmitter.cpp

Index: llvm/utils/TableGen/IntrinsicEmitter.cpp
===
--- llvm/utils/TableGen/IntrinsicEmitter.cpp
+++ llvm/utils/TableGen/IntrinsicEmitter.cpp
@@ -248,7 +248,8 @@
   IIT_V128 = 47,
   IIT_BF16 = 48,
   IIT_STRUCT9 = 49,
-  IIT_V256 = 50
+  IIT_V256 = 50,
+  IIT_AMX  = 51
 };
 
 static void EncodeFixedValueType(MVT::SimpleValueType VT,
@@ -276,6 +277,7 @@
   case MVT::token: return Sig.push_back(IIT_TOKEN);
   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
+  case MVT::x86amx: return Sig.push_back(IIT_AMX);
   // MVT::OtherVT is used to mean the empty struct type here.
   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
   // MVT::isVoid is used to represent varargs here.
Index: llvm/utils/TableGen/CodeGenTarget.cpp
===
--- llvm/utils/TableGen/CodeGenTarget.cpp
+++ llvm/utils/TableGen/CodeGenTarget.cpp
@@ -76,6 +76,7 @@
   case MVT::f128: return "MVT::f128";
   case MVT::ppcf128:  return "MVT::ppcf128";
   case MVT::x86mmx:   return "MVT::x86mmx";
+  case MVT::x86amx:   return "MVT::x86amx";
   case MVT::Glue: return "MVT::Glue";
   case MVT::isVoid:   return "MVT::isVoid";
   case MVT::v1i1: return "MVT::v1i1";
Index: llvm/test/CodeGen/X86/AMX/amx-type.ll
===
--- llvm/test/CodeGen/X86/AMX/amx-type.ll
+++ llvm/test/CodeGen/X86/AMX/amx-type.ll
@@ -8,18 +8,146 @@
 @buf = dso_local global [1024 x i8] zeroinitializer, align 16
 @buf2 = dso_local global [1024 x i8] zeroinitializer, align 16
 
+define dso_local <256 x i32> @test_amx_bitcast(<256 x i32> %in) #2 {
+; CHECK-LABEL: @test_amx_bitcast(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:ret <256 x i32> [[IN:%.*]]
+;
+entry:
+  %amx = bitcast <256 x i32> %in to x86_amx
+  %vec = bitcast x86_amx %amx to <256 x i32>
+  ret <256 x i32> %vec
+}
+
+define dso_local void @test_amx_store(<256 x i32>* %in, i16 %m, i16 %n, i8 *%buf, i64 %s) #2 {
+; CHECK-LABEL: @test_amx_store(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[T0:%.*]] = call x86_amx @llvm.x86.tileloadd64.internal(i16 [[M:%.*]], i16 [[N:%.*]], i8* [[BUF:%.*]], i64 [[S:%.*]]) [[ATTR3:#.*]]
+; CHECK-NEXT:[[ADDR:%.*]] = bitcast <256 x i32>* [[IN:%.*]] to x86_amx*
+; CHECK-NEXT:[[TMP0:%.*]] = bitcast x86_amx* [[ADDR]] to i8*
+; CHECK-NEXT:call void @llvm.x86.tilestored64.internal(i16 [[M]], i16 [[N]], i8* [[TMP0]], i64 64, x86_amx [[T0]])
+; CHECK-NEXT:ret void
+;
+entry:
+  %t0 = call x86_amx @llvm.x86.tileloadd64.internal(i16 %m, i16 %n, i8* %buf, i64 %s) #3
+  %addr = bitcast <256 x i32>* %in to x86_amx*
+  store x86_amx %t0, x86_amx* %addr, align 64
+  ret void
+}
+
+define dso_local void @test_amx_load(<256 x i32>* %in, i16 %m, i16 %n, i8 *%buf, i64 %s) #2 {
+; CHECK-LABEL: @test_amx_load(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[T0:%.*]] = bitcast <256 x i32>* [[IN:%.*]] to x86_amx*
+; CHECK-NEXT:[[TMP0:%.*]] = bitcast x86_amx* [[T0]] to i8*
+; CHECK-NEXT:[[TMP1:%.*]] = call x86_amx @llvm.x86.tileloadd64.internal(i16 [[M:%.*]], i16 [[N:%.*]], i8* [[TMP0]], i64 64)
+; CHECK-NEXT:call void @llvm.x86.tilestored64.internal(i16 [[M]], i16 [[N]], i8* [[BUF:%.*]], i64 [[S:%.*]], x86_amx [[TMP1]]) [[ATTR3]]
+; CHECK-NEXT:ret void
+;
+entry:
+  %t0 = bitcast <256 x i32>* %in to x86_amx*
+  %t1 = load x86_amx, x86_amx* %t0, align 64
+  call void @llvm.x86.tilestored64.internal(i16 

[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:26-28
+  // The first argument of an overloaded member operator is the implicit object
+  // argument of the method which should not be matched against a parameter, so
+  // we skip over it here.

Isn't this true for any non-static member function? e.g., should the matcher be 
looking at `cxxOperatorCallExpr()` at all?



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:61
+  anyOf(
+  hasParent(explicitCastExpr(hasDestinationType(booleanType(,
+  hasParent(ifStmt(hasCondition(expr(equalsBoundNode(exprName),

I take it we can't do `hasParent(anyOf(...))` instead?



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:67
+  
hasParent(forStmt(hasCondition(expr(equalsBoundNode(exprName),
+  hasParent(varDecl(hasType(booleanType(,
+  hasParent(

If this matters for var decls, what about field decls in a structure?



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:69
+  hasParent(
+  parenListExpr(hasParent(varDecl(hasType(booleanType()),
+  hasParent(parenExpr(hasParent(

Same question here.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp:493
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be 
used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}

The quoting here is unfortunate. It's not part of your patch, but it could be 
solved by calling `Container->getName()` and manually quoting the note text if 
you wanted to hit it in a follow-up (I'd consider that an NFC change, no need 
to review). You could also address it as part of this patch if you felt like it.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp:631
+};
+
+void instantiator() {

Some other test cases that may be of interest:
```
class C {
  bool B;
public:
  C(const std::vector &C) : B(C.size()) {}
};

struct S {
  std::vector C;
  bool B = C.size();
};

int func(const std::vector &C) {
  return C.size() ? 0 : 1;
}

struct Lazy {
  constexpr unsigned size() const { return 0; }
  constexpr bool empty() const { return true; }
};

constexpr Lazy L;
static_assert(!L.size(), ""); // This one should get converted

struct S {
  void func() noexcept(L.size()); // This one should not
};
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

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


[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 313316.
vsavchenko added a comment.
Herald added a subscriber: arphaman.

Fix block.c test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

Files:
  clang/lib/Parse/ParseStmt.cpp
  clang/test/Index/blocks.c
  clang/test/Parser/stmt-attributes.c
  clang/test/Sema/address_spaces.c
  clang/test/Sema/block-literal.c
  clang/test/SemaTemplate/address_space-dependent.cpp

Index: clang/test/SemaTemplate/address_space-dependent.cpp
===
--- clang/test/SemaTemplate/address_space-dependent.cpp
+++ clang/test/SemaTemplate/address_space-dependent.cpp
@@ -9,7 +9,8 @@
   __attribute__((address_space(J))) int array[5]; // expected-error {{automatic variable qualified with an address space}}
   __attribute__((address_space(I))) int arrarr[5][5]; // expected-error {{automatic variable qualified with an address space}}
 
-  __attribute__((address_space(J))) * x; // expected-error {{C++ requires a type specifier for all declarations}}
+  __attribute__((address_space(J))) * x; // expected-error {{use of undeclared identifier 'x'}}
+  // expected-error@-1 {{'address_space' attribute cannot be applied to a statement}}
 
   __attribute__((address_space(I))) float *B;
 
Index: clang/test/Sema/block-literal.c
===
--- clang/test/Sema/block-literal.c
+++ clang/test/Sema/block-literal.c
@@ -41,8 +41,11 @@
 
   foo:
   takeblock(^{ x = 4; });  // expected-error {{variable is not assignable (missing __block type specifier)}}
-  __block y = 7;// expected-warning {{type specifier missing, defaults to 'int'}}
-  takeblock(^{ y = 8; });
+  __block y = 7;   // expected-error {{use of undeclared identifier 'y'}}
+  __block int z = 7;
+  takeblock(^{
+z = 8;
+  });
 }
 
 
Index: clang/test/Sema/address_spaces.c
===
--- clang/test/Sema/address_spaces.c
+++ clang/test/Sema/address_spaces.c
@@ -9,7 +9,8 @@
 void foo(_AS3 float *a,
  _AS1 float b) // expected-error {{parameter may not be qualified with an address space}}
 {
-  _AS2 *x;// expected-warning {{type specifier missing, defaults to 'int'}}
+  _AS2 *x; // expected-error {{'address_space' attribute cannot be applied to a statement}}
+  // expected-error@-1 {{use of undeclared identifier 'x'}}
   _AS1 float * _AS2 *B;
 
   int _AS1 _AS2 *Y;   // expected-error {{multiple address spaces specified for type}}
Index: clang/test/Parser/stmt-attributes.c
===
--- /dev/null
+++ clang/test/Parser/stmt-attributes.c
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void foo(int i) {
+
+  __attribute__((unknown_attribute));// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) {}  // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) if (0) {}   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) for (;;);   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) do {// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) continue; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  }
+  while (0)
+;
+  __attribute__((unknown_attribute)) while (0); // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((unknown_attribute)) switch (i) {  // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) case 0 :// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) default :   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+ __attribute__((unknown_attribute)) break; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  }
+
+  __attribute__((unknown_attribute)) goto here; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) here : // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+__attribute__((unknown_attribute)) return; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((noreturn)) {}   

[PATCH] D93695: [clang-tidy] Update uses of deprecated Transformer APIs in StringFindStrContainsCheck.

2020-12-22 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: tdl-g.
Herald added a subscriber: xazax.hun.
ymandel requested review of this revision.
Herald added a project: clang.

Migrates `change` to `changeTo`; changes to new constructor API (2-arg construct
+ `setRule`); refactors use of `addInclude` to newer version.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93695

Files:
  clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp


Index: clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
===
--- clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
+++ clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp
@@ -24,9 +24,10 @@
 namespace tidy {
 namespace abseil {
 
+using ::clang::transformer::addInclude;
 using ::clang::transformer::applyFirst;
 using ::clang::transformer::cat;
-using ::clang::transformer::change;
+using ::clang::transformer::changeTo;
 using ::clang::transformer::makeRule;
 using ::clang::transformer::node;
 using ::clang::transformer::RewriteRule;
@@ -38,22 +39,9 @@
"::absl::string_view";
 static const char DefaultAbseilStringsMatchHeader[] = "absl/strings/match.h";
 
-static llvm::Optional
-MakeRule(const LangOptions &LangOpts,
- const ClangTidyCheck::OptionsView &Options) {
-  // Parse options.
-  //
-  // FIXME(tdl-g): These options are being parsed redundantly with the
-  // constructor because TransformerClangTidyCheck forces us to provide 
MakeRule
-  // before "this" is fully constructed, but StoreOptions requires us to store
-  // the parsed options in "this".  We need to fix TransformerClangTidyCheck 
and
-  // then we can clean this up.
-  const std::vector StringLikeClassNames =
-  utils::options::parseStringList(
-  Options.get("StringLikeClasses", DefaultStringLikeClasses));
-  const std::string AbseilStringsMatchHeader =
-  Options.get("AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader);
-
+static transformer::RewriteRule
+makeRewriteRule(const std::vector &StringLikeClassNames,
+StringRef AbseilStringsMatchHeader) {
   auto StringLikeClass = cxxRecordDecl(hasAnyName(SmallVector(
   StringLikeClassNames.begin(), StringLikeClassNames.end(;
   auto StringType =
@@ -75,29 +63,36 @@
   onImplicitObjectArgument(expr().bind("string_being_searched")));
 
   RewriteRule rule = applyFirst(
-  {makeRule(binaryOperator(hasOperatorName("=="),
-   hasOperands(ignoringParenImpCasts(StringNpos),
-   ignoringParenImpCasts(StringFind))),
-change(cat("!absl::StrContains(", 
node("string_being_searched"),
-   ", ", node("parameter_to_find"), ")")),
-cat("use !absl::StrContains instead of find() == npos")),
-   makeRule(binaryOperator(hasOperatorName("!="),
-   hasOperands(ignoringParenImpCasts(StringNpos),
-   ignoringParenImpCasts(StringFind))),
-change(cat("absl::StrContains(", node("string_being_searched"),
-   ", ", node("parameter_to_find"), ")")),
-cat("use absl::StrContains instead of find() != npos"))});
-  addInclude(rule, AbseilStringsMatchHeader);
+  {makeRule(
+   binaryOperator(hasOperatorName("=="),
+  hasOperands(ignoringParenImpCasts(StringNpos),
+  ignoringParenImpCasts(StringFind))),
+   {changeTo(cat("!absl::StrContains(", node("string_being_searched"),
+ ", ", node("parameter_to_find"), ")")),
+addInclude(AbseilStringsMatchHeader)},
+   cat("use !absl::StrContains instead of find() == npos")),
+   makeRule(
+   binaryOperator(hasOperatorName("!="),
+  hasOperands(ignoringParenImpCasts(StringNpos),
+  ignoringParenImpCasts(StringFind))),
+   {changeTo(cat("absl::StrContains(", node("string_being_searched"),
+ ", ", node("parameter_to_find"), ")")),
+addInclude(AbseilStringsMatchHeader)},
+   cat("use absl::StrContains instead "
+   "of find() != npos"))});
   return rule;
 }
 
 StringFindStrContainsCheck::StringFindStrContainsCheck(
 StringRef Name, ClangTidyContext *Context)
-: TransformerClangTidyCheck(&MakeRule, Name, Context),
+: TransformerClangTidyCheck(Name, Context),
   StringLikeClassesOption(utils::options::parseStringList(
   Options.get("StringLikeClasses", DefaultStringLikeClasses))),
   AbseilStringsMatchHeaderOption(Options.get(
-  "AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader)) {}
+  "AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader)) {
+ 

[PATCH] D93377: [Clang] Add __ibm128 type to represent ppc_fp128

2020-12-22 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:6230
 /// LHS < RHS, return -1.
 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
   FloatingRank LHSR = getFloatingRank(LHS);

nemanjai wrote:
> hubert.reinterpretcast wrote:
> > I think this function should vocally fail when presented with "unordered" 
> > cases.
> But is it possible to emit errors here or should there be code explicitly 
> added to Sema to disallow conversions between `__ibm128` and `__float128` 
> (and `long double` to/from either of those to which it is not equivalent)?
I did not mean a user-facing error message. I meant that there should be some 
form of assertion or internal diagnostic here. I believe `assert` is 
appropriate.

I will note that this is a public member function of ASTContext. Regardless of 
explicit code in Sema that does what you describe, I think this function should 
not present an interface where it does not report "unordered" cases as 
unordered.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93377

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


[PATCH] D93453: [flang][driver] Add support for `-I`

2020-12-22 Thread Faris via Phabricator via cfe-commits
FarisRehman updated this revision to Diff 313319.
FarisRehman added a comment.

Address review comments

Summary of changes:

- Add a regression test for -I
- Move claiming of -I option to the dedicated parsing preprocessing options 
method
- Rename SearchDirectoriesFromI to SearchDirectoriesFromDashI
- Undo unrelated changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93453

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/PreprocessorOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/test/Flang-Driver/Inputs/included.h
  flang/test/Flang-Driver/driver-help-hidden.f90
  flang/test/Flang-Driver/driver-help.f90
  flang/test/Flang-Driver/include_header.f90

Index: flang/test/Flang-Driver/include_header.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/include_header.f90
@@ -0,0 +1,41 @@
+! Ensure argument -I works as expected.
+
+! REQUIRES: new-flang-driver
+
+!--
+! FLANG DRIVER (flang-new)
+!--
+! RUN: %flang-new -E %s  2>&1 | FileCheck %s --check-prefix=UNINCLUDED
+! RUN: %flang-new -E -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: %flang-new -E -I %S/InvalidFolder %s  2>&1 | FileCheck %s --check-prefix=UNINCLUDED
+
+!-
+! FRONTEND FLANG DRIVER (flang-new -fc1)
+!-
+! RUN: %flang-new -fc1 -E %s  2>&1 | FileCheck %s --check-prefix=UNINCLUDED
+! RUN: %flang-new -fc1 -E -I %S/Inputs %s  2>&1 | FileCheck %s --check-prefix=INCLUDED
+! RUN: %flang-new -fc1 -E -I %S/InvalidFolder %s  2>&1 | FileCheck %s --check-prefix=UNINCLUDED
+
+
+!
+! EXPECTED OUTPUT FOR MISSING INCLUDE
+!
+! UNINCLUDED:program b
+! UNINCLUDED-NOT:program a
+! UNINCLUDED-NEXT:end
+
+!
+! EXPECTED OUTPUT FOR INCLUDE
+!
+! INCLUDED:program a
+! INCLUDED-NOT:program b
+! INCLUDED-NEXT:end
+
+! Include.F:
+#include 
+#ifdef X
+program A
+#else
+program B
+#endif
+end
\ No newline at end of file
Index: flang/test/Flang-Driver/driver-help.f90
===
--- flang/test/Flang-Driver/driver-help.f90
+++ flang/test/Flang-Driver/driver-help.f90
@@ -24,6 +24,7 @@
 ! HELP-NEXT: -fcolor-diagnosticsEnable colors in diagnostics
 ! HELP-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! HELP-NEXT: -help  Display available options
+! HELP-NEXT: -IAdd directory to include search path. If there are multiple -I options, these directories are searched in the order they are given before the standard system directories are searched. If the same directory is in the SYSTEM include search paths, for example if also specified with -isystem, the -I option will be ignored
 ! HELP-NEXT: -o   Write output to 
 ! HELP-NEXT: -U  Undefine macro 
 ! HELP-NEXT: --version  Print version information
@@ -37,6 +38,7 @@
 ! HELP-FC1-NEXT: -D = Define  to  (or 1 if  omitted)
 ! HELP-FC1-NEXT: -E Only run the preprocessor
 ! HELP-FC1-NEXT: -help  Display available options
+! HELP-FC1-NEXT: -IAdd directory to include search path. If there are multiple -I options, these directories are searched in the order they are given before the standard system directories are searched. If the same directory is in the SYSTEM include search paths, for example if also specified with -isystem, the -I option will be ignored
 ! HELP-FC1-NEXT: -o   Write output to 
 ! HELP-FC1-NEXT: -U  Undefine macro 
 ! HELP-FC1-NEXT: --version  Print version information
Index: flang/test/Flang-Driver/driver-help-hidden.f90
===
--- flang/test/Flang-Driver/driver-help-hidden.f90
+++ flang/test/Flang-Driver/driver-help-hidden.f90
@@ -24,6 +24,7 @@
 ! CHECK-NEXT: -fcolor-diagnosticsEnable colors in diagnostics
 ! CHECK-NEXT: -fno-color-diagnostics Disable colors in diagnostics
 ! CHECK-NEXT: -help Display available options
+! CHECK-NEXT: -IAdd directory to include search path. If there are multiple -I options, these directories are searched in the order they are given before the standard system directories are searched. If the same directory is in the SYSTEM include search paths, for example if also specified with -isystem, the -I option will be ignored
 ! CHECK-NEXT: -o  Write output to 
 ! CHECK-NEXT: -test-io  Run the InputOuputTest action. Use for development and testing only.
 ! CHECK-NEXT: -U  Undefine macro 
Index: flang/test/Flang-Driver/Inp

[PATCH] D91303: Simplify implementation of container-size-empty

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:56
-   hasEitherOperand(ignoringImpCasts(
-   anyOf(integerLiteral(equals(1)),
- integerLiteral(equals(0))

It looks like the changes drop the requirement that either operand is 0 or 1 -- 
is that an oversight or can you explain why that's correct?



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:101
-  ignoringImpCasts(stringLiteral(hasSize(0))),
-  ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
-  ignoringImplicit(DefaultConstructor),

We seem to lose this case entirely?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91303

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


[PATCH] D93401: [flang][driver] Add support for `-D`, `-U`

2020-12-22 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

@FarisRehman , thank you for updating this! I have two high-level comments:

1. In your summary:

> Change the way the driver handles end-of-line characters in macro definitions.

That's a a bit misleading - which driver do you mean? You're not changing the 
behavior of the current driver, `flang`. Also, this functionality doesn't yet 
exist in the new driver, `flang-new`, so you're not changing it there either. 
You can probably remove this sentence and just make it clear that you meant the 
new driver.

2. Could you doxygen style comments for input and output parameters in the new 
methods that you introduce? Ta! 
https://www.doxygen.nl/manual/commands.html#cmdparam

More comments inline.




Comment at: clang/lib/Driver/ToolChains/Flang.cpp:36
 
+  const InputInfo &Input = Inputs[0];
+

This is not used until line 73. Perhaps better to define it near to where it's 
used?

https://isocpp.org/wiki/faq/coding-standards#declare-near-first-use



Comment at: clang/lib/Driver/ToolChains/Flang.h:27-31
+  /// Add the specified preprocessing options from Args to CmdArgs,
+  /// claiming the arguments used.
+  ///
+  /// \param Args The list of input arguments
+  /// \param CmdArgs The list of output arguments

1. Could you clarify the difference between `Args` and `CmdArgs`?
2. Could you use doxygen's syntax to specify the parameter _direction_? E.g.:
```
  /// \param [in] Args The list of input arguments
  /// \param [out] CmdArgs The list of output arguments
```
See https://www.doxygen.nl/manual/commands.html#cmdparam.



Comment at: flang/include/flang/Frontend/PreprocessorOptions.h:26
+public:
+  std::vector> Macros;
+

`Macros` --> `macros_` :)



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:213-214
+///
+/// \param ppOpts The preprocessor options (input)
+/// \param opts The fortran options (output)
+static void collectMacroDefinitions(

[nit] Ideally this would use doxygen style: 
https://www.doxygen.nl/manual/commands.html#cmdparam. For example:
```
/// \param [in] ppOpts The preprocessor options
/// \param [out] opts The fortran options
```
Apologies for not making it clearer earlier.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:234
+if (macroName.size() == macro.size())
+  macroBody = "1";
+else {

I think that it would make sense to add a note in the commit message that 
`-Dname` predefines `name` as a macro with  definition 1. Basically, a note 
that all macros default to 1.



Comment at: flang/test/Flang-Driver/macro_def_undef.f90:19
+
+
+!

[nit] Empty line not needed



Comment at: flang/test/Flang-Driver/macro_def_undef.f90:37
+
+! Macro.F:
+#ifdef X

[nit] Doesn't agree with the name of file. Also, I would just skip it.



Comment at: flang/test/Flang-Driver/macro_multiline.f90:15
+
+
+!---

[nit] Empty line not needed



Comment at: flang/test/Flang-Driver/macro_multiline.f90:19
+!---
+! printf -- "-DX=A\nTHIS_SHOULD_NOT_EXIST_IN_THE_OUTPUT\n" | xargs 
flang-new -E %s
+! CHECK:program a

[nit] Repetition of the `RUN` line



Comment at: flang/test/Flang-Driver/macro_multiline.f90:24
+
+! Macro.F:
+program X

[nit] Doesn't agree with the name of file. Also, I would just skip it.



Comment at: flang/test/Flang-Driver/macro_multiline.f90:25-26
+! Macro.F:
+program X
+end

I think that it would be useful to make this a bit stronger:

```
! CHECK: {{^start a end$}}
! CHECK-NOT: THIS_SHOULD_NOT_EXIST_IN_THE_OUTPUT
! CHECK-NOT: this_should_not_exist_in_the_output
START X END
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93401

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


[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-22 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes added a comment.

This patch regressed the following test of Transforms/InstCombine/abs-1.ll:
(need to drop NSW in this case).

  define i8 @nabs_canonical_3(i8 %x) {
  %0:
%cmp = icmp slt i8 %x, 0
%neg = sub nsw i8 0, %x
%abs = select i1 %cmp, i8 %x, i8 %neg
ret i8 %abs
  }
  =>
  define i8 @nabs_canonical_3(i8 %x) {
  %0:
%1 = abs i8 %x, 1
%abs = sub nsw i8 0, %1
ret i8 %abs
  }
  Transformation doesn't verify!
  ERROR: Target is more poisonous than source
  
  Example:
  i8 %x = #x80 (128, -128)
  
  Source:
  i1 %cmp = #x1 (1)
  i8 %neg = poison
  i8 %abs = #x80 (128, -128)
  
  Target:
  i8 %1 = poison
  i8 %abs = poison
  Source value: #x80 (128, -128)
  Target value: poison

(same bug occurs with @nabs_nabs_x01 in Transforms/InstCombine/abs_abs.ll)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D80623: WIP: Add an API to simplify setting TraversalKind in clang-tidy matchers

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchFinder.h:118
+/// behavior of clang-tidy.
+virtual llvm::Optional
+getCheckTraversalKind() const;

steveire wrote:
> sammccall wrote:
> > I don't really get why this would be optional.
> > A check's implementation isn't really going to be robust to "whatever the 
> > default is", it's going to be tested against one or the other.
> > So None isn't really a sensible return value - can't the base class simply 
> > return the actual default?
> ASTMatchFinder doesn't know the ASTContext, so it can't access the default. 
> That's why I made it an optional.
The fact that it's optional is a bit weird. Given that this is a temporary API, 
I see two approaches: hold our nose because the ugliness shouldn't be 
long-lived, or have the default be specified in two places with comments saying 
"don't forget to update over here if you change this value" so we can get rid 
of the `Optional<>` here. WDYT?



Comment at: clang/lib/ASTMatchers/ASTMatchFinder.cpp:1205
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind()) {
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);

Elide the braces.



Comment at: clang/lib/ASTMatchers/ASTMatchFinder.cpp:1221
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind()) {
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);

Elide the braces.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80623

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


[PATCH] D93683: [clangd] Do not take stale definition from the static index.

2020-12-22 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 313320.
ArcsinX added a comment.

- Simplify test.
- Revert PreambleSymbols.update() first argument change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93683

Files:
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -290,6 +290,38 @@
   EXPECT_THAT(lookup(M, {}), UnorderedElementsAre());
 }
 
+TEST(MergeIndexTest, LookupRemovedDefinition) {
+  FileIndex DynamicIndex, StaticIndex;
+  MergedIndex Merge(&DynamicIndex, &StaticIndex);
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo definition
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo {};";
+  Test.Filename = "test.cc";
+  auto AST = Test.build();
+  StaticIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Remove Foo definition from test.cc, i.e. build dynamic index for test.cc
+  // without Foo definition.
+  Test.Code = "class Foo;";
+  AST = Test.build();
+  DynamicIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Merged index should not return the symbol definition if this definition
+  // location is inside a file from the dynamic index.
+  LookupRequest LookupReq;
+  LookupReq.IDs = {Foo.ID};
+  std::vector Symbols;
+  Merge.lookup(LookupReq, [&](const Symbol &Sym) { Symbols.push_back(Sym); });
+  ASSERT_EQ(Symbols.size(), 1u);
+  EXPECT_FALSE(Symbols.front().Definition);
+}
+
 TEST(MergeIndexTest, FuzzyFind) {
   auto I = MemIndex::build(generateSymbols({"ns::A", "ns::B"}), RefSlab(),
RelationSlab()),
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -76,7 +76,11 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
+  auto DynamicContainsFile = Dynamic->indexedFiles();
   Static->lookup(Req, [&](const Symbol &S) {
+if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+ : S.CanonicalDeclaration.FileURI))
+  return;
 const Symbol *Sym = B.find(S.ID);
 RemainingIDs.erase(S.ID);
 if (!Sym)


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -290,6 +290,38 @@
   EXPECT_THAT(lookup(M, {}), UnorderedElementsAre());
 }
 
+TEST(MergeIndexTest, LookupRemovedDefinition) {
+  FileIndex DynamicIndex, StaticIndex;
+  MergedIndex Merge(&DynamicIndex, &StaticIndex);
+
+  const char *HeaderCode = "class Foo;";
+  auto HeaderSymbols = TestTU::withHeaderCode(HeaderCode).headerSymbols();
+  auto Foo = findSymbol(HeaderSymbols, "Foo");
+
+  // Build static index for test.cc with Foo definition
+  TestTU Test;
+  Test.HeaderCode = HeaderCode;
+  Test.Code = "class Foo {};";
+  Test.Filename = "test.cc";
+  auto AST = Test.build();
+  StaticIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Remove Foo definition from test.cc, i.e. build dynamic index for test.cc
+  // without Foo definition.
+  Test.Code = "class Foo;";
+  AST = Test.build();
+  DynamicIndex.updateMain(testPath(Test.Filename), AST);
+
+  // Merged index should not return the symbol definition if this definition
+  // location is inside a file from the dynamic index.
+  LookupRequest LookupReq;
+  LookupReq.IDs = {Foo.ID};
+  std::vector Symbols;
+  Merge.lookup(LookupReq, [&](const Symbol &Sym) { Symbols.push_back(Sym); });
+  ASSERT_EQ(Symbols.size(), 1u);
+  EXPECT_FALSE(Symbols.front().Definition);
+}
+
 TEST(MergeIndexTest, FuzzyFind) {
   auto I = MemIndex::build(generateSymbols({"ns::A", "ns::B"}), RefSlab(),
RelationSlab()),
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -76,7 +76,11 @@
   Dynamic->lookup(Req, [&](const Symbol &S) { B.insert(S); });
 
   auto RemainingIDs = Req.IDs;
+  auto DynamicContainsFile = Dynamic->indexedFiles();
   Static->lookup(Req, [&](const Symbol &S) {
+if (DynamicContainsFile(S.Definition ? S.Definition.FileURI
+ : S.CanonicalDeclaration.FileURI))
+  return;
 const Symbol *Sym = B.find(S.ID);
 RemainingIDs.erase(S.ID);
 if (!Sym)
_

[PATCH] D93626: [clang-format] PR48535 clang-format Incorrectly Removes Space After C Style Cast When Type Is Not a Pointer

2020-12-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D93626#2467745 , @curdeius wrote:

> LGTM now. I tried to find other cases where this change may change the 
> behaviour but couldn't. Have you tried applying to some bigger repo and see 
> what you get? The best would be a repo with SpaceAfterCStyleCast=true.

Only my own internally, which I preconverted to using this style using an older 
clang-format then ran with this version. This seems to be fixing more cases 
than creating false positives:

Here are just 2 additional cases I found

  int a = (int16)(a + (b << 2) + (c << 4));
  if ((size_t)(a - b) <= c)

which become

  int a = (int16) (a + (b << 2) + (c << 4));
  if ((size_t) (a - b) <= c) {




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

https://reviews.llvm.org/D93626

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


[PATCH] D93633: [format] Add overload to parseConfiguration that accept llvm::MemoryBufferRef

2020-12-22 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay 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/D93633/new/

https://reviews.llvm.org/D93633

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


[PATCH] D93698: [clang][cli] Port a CommaJoined option to the marshalling infrastructure

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93698

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Frontend/CompilerInvocationTest.cpp

Index: clang/unittests/Frontend/CompilerInvocationTest.cpp
===
--- clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -508,6 +508,53 @@
   ASSERT_THAT(GeneratedArgs, ContainsN(HasSubstr("-fmodule-map-file"), 2));
 }
 
+// CommaJoined option with MarshallingInfoStringVector.
+
+TEST_F(CommandLineTest, StringVectorCommaJoinedNone) {
+  const char *Args[] = {""};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getLangOpts()->CommentOpts.BlockCommandNames.empty());
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs,
+  Not(Contains(HasSubstr("-fcomment-block-commands";
+}
+
+TEST_F(CommandLineTest, StringVectorCommaJoinedSingle) {
+  const char *Args[] = {"-fcomment-block-commands=x,y"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getLangOpts()->CommentOpts.BlockCommandNames,
+std::vector({"x", "y"}));
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs,
+  ContainsN(StrEq("-fcomment-block-commands=x,y"), 1));
+}
+
+TEST_F(CommandLineTest, StringVectorCommaJoinedMultiple) {
+  const char *Args[] = {"-fcomment-block-commands=x,y",
+"-fcomment-block-commands=a,b"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getLangOpts()->CommentOpts.BlockCommandNames,
+std::vector({"x", "y", "a", "b"}));
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs,
+  ContainsN(StrEq("-fcomment-block-commands=x,y,a,b"), 1));
+}
+
 // Tree of boolean options that can be (directly or transitively) implied by
 // their parent:
 //
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -328,8 +328,18 @@
 Option::OptionClass OptClass,
 unsigned TableIndex,
 const std::vector &Values) {
-  for (const std::string &Value : Values) {
-denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
+  if (OptClass == Option::OptionClass::CommaJoinedClass) {
+std::string CommaJoinedValue;
+for (const std::string &Value : Values) {
+  if (&Value != &Values.front())
+CommaJoinedValue.append(",");
+  CommaJoinedValue.append(Value);
+}
+denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
+  TableIndex, CommaJoinedValue);
+  } else if (OptClass == Option::OptionClass::JoinedClass) {
+for (const std::string &Value : Values)
+  denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
   }
 }
 
@@ -785,7 +795,6 @@
 }
 
 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
-  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
   Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
 }
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1201,7 +1201,7 @@
   MarshallingInfoFlag<"DiagnosticOpts->UseANSIEscapeCodes">;
 def fcomment_block_commands : CommaJoined<["-"], "fcomment-block-commands=">, Group, Flags<[CC1Option]>,
   HelpText<"Treat each comma separated argument in  as a documentation comment block command">,
-  MetaVarName<"">;
+  MetaVarName<"">, MarshallingInfoStringVector<"LangOpts->CommentOpts.BlockCommandNames">;
 def fparse_all_comments : Flag<["-"], "fparse-all-comments">, Group, Flags<[CC1Option]>,
   MarshallingInfoFlag<"LangOpts->CommentOpts.ParseAllComments">;
 def frecord_command_line : Flag<["-"], "frecord-command-line">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D93699: [clang][cli] Port getAllArgumentValues to the marshalling infrastructure

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
Herald added a subscriber: dang.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93699

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -328,7 +328,8 @@
 Option::OptionClass OptClass,
 unsigned TableIndex,
 const std::vector &Values) {
-  if (OptClass == Option::OptionClass::CommaJoinedClass) {
+  switch (OptClass) {
+  case Option::CommaJoinedClass: {
 std::string CommaJoinedValue;
 for (const std::string &Value : Values) {
   if (&Value != &Values.front())
@@ -337,9 +338,17 @@
 }
 denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
   TableIndex, CommaJoinedValue);
-  } else if (OptClass == Option::OptionClass::JoinedClass) {
+break;
+  }
+  case Option::JoinedClass:
+  case Option::SeparateClass:
+  case Option::JoinedOrSeparateClass:
 for (const std::string &Value : Values)
   denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
+break;
+  default:
+llvm_unreachable("Cannot denormalize an option with option class "
+ "incompatible with string vector denormalization.");
   }
 }
 
@@ -994,8 +1003,6 @@
 }
   }
 
-  Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ);
-
   // Basic Block Sections implies Function Sections.
   Opts.FunctionSections =
   Args.hasArg(OPT_ffunction_sections) ||
@@ -1125,10 +1132,6 @@
 }
 Opts.LinkBitcodeFiles.push_back(F);
   }
-  Opts.SanitizeCoverageAllowlistFiles =
-  Args.getAllArgValues(OPT_fsanitize_coverage_allowlist);
-  Opts.SanitizeCoverageBlocklistFiles =
-  Args.getAllArgValues(OPT_fsanitize_coverage_blocklist);
   Opts.SSPBufferSize =
   getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
 
@@ -1210,8 +1213,6 @@
 }
   }
 
-  Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
-  Opts.LinkerOptions = Args.getAllArgValues(OPT_linker_option);
   bool NeedLocTracking = false;
 
   if (!Opts.OptRecordFile.empty())
@@ -1285,8 +1286,6 @@
   if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
 Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
 
-  Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file);
-
   // Parse -fsanitize-recover= arguments.
   // FIXME: Report unrecoverable sanitizers incorrectly specified here.
   parseSanitizerKinds("-fsanitize-recover=",
@@ -1298,16 +1297,11 @@
 
   Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
 
-  Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
-
-  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
-
   return Success;
 }
 
 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
   ArgList &Args) {
-  Opts.Targets = Args.getAllArgValues(OPT_MT);
   if (Args.hasArg(OPT_show_includes)) {
 // Writing both /showIncludes and preprocessor output to stdout
 // would produce interleaved output, so use stderr for /showIncludes.
@@ -1485,7 +1479,6 @@
   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
-  Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
   if (Args.hasArg(OPT_verify))
 Opts.VerifyPrefixes.push_back("expected");
   // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
@@ -1532,8 +1525,6 @@
   Opts.MessageLength =
   getLastArgIntValue(Args, OPT_fmessage_length_EQ, 0, Diags);
 
-  Opts.UndefPrefixes = Args.getAllArgValues(OPT_Wundef_prefix_EQ);
-
   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
 
@@ -1730,8 +1721,6 @@
   }
 
   Opts.Plugins = Args.getAllArgValues(OPT_load);
-  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
-  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
   // Only the -fmodule-file= form.
@@ -1740,7 +1729,6 @@
 if (Val.find('=') == StringRef::npos)
   Opts.ModuleFiles.push_back(std::string(Val));
   }
-  Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ);
   Opts.AllowPCMWithCompil

[PATCH] D91927: [X86] Add x86_amx type for intel AMX.

2020-12-22 Thread LuoYuanke via Phabricator via cfe-commits
LuoYuanke updated this revision to Diff 313326.
LuoYuanke added a comment.

Rebase and fix lit test case failure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91927

Files:
  clang/test/CodeGen/X86/amx_api.c
  llvm/include/llvm-c/Core.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/CodeGen/ValueTypes.td
  llvm/include/llvm/IR/DataLayout.h
  llvm/include/llvm/IR/Intrinsics.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/IR/IntrinsicsX86.td
  llvm/include/llvm/IR/Type.h
  llvm/include/llvm/Support/MachineValueType.h
  llvm/lib/Analysis/ConstantFolding.cpp
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/CodeGen/ValueTypes.cpp
  llvm/lib/IR/AsmWriter.cpp
  llvm/lib/IR/ConstantFold.cpp
  llvm/lib/IR/Core.cpp
  llvm/lib/IR/DataLayout.cpp
  llvm/lib/IR/Function.cpp
  llvm/lib/IR/LLVMContextImpl.cpp
  llvm/lib/IR/LLVMContextImpl.h
  llvm/lib/IR/Type.cpp
  llvm/lib/Target/X86/X86ISelDAGToDAG.cpp
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86LowerAMXType.cpp
  llvm/lib/Target/X86/X86RegisterInfo.td
  llvm/test/CodeGen/X86/AMX/amx-across-func.ll
  llvm/test/CodeGen/X86/AMX/amx-config.ll
  llvm/test/CodeGen/X86/AMX/amx-intrinsic-chain.ll
  llvm/test/CodeGen/X86/AMX/amx-spill.ll
  llvm/test/CodeGen/X86/AMX/amx-type.ll
  llvm/utils/TableGen/CodeGenTarget.cpp
  llvm/utils/TableGen/IntrinsicEmitter.cpp

Index: llvm/utils/TableGen/IntrinsicEmitter.cpp
===
--- llvm/utils/TableGen/IntrinsicEmitter.cpp
+++ llvm/utils/TableGen/IntrinsicEmitter.cpp
@@ -248,7 +248,8 @@
   IIT_V128 = 47,
   IIT_BF16 = 48,
   IIT_STRUCT9 = 49,
-  IIT_V256 = 50
+  IIT_V256 = 50,
+  IIT_AMX  = 51
 };
 
 static void EncodeFixedValueType(MVT::SimpleValueType VT,
@@ -276,6 +277,7 @@
   case MVT::token: return Sig.push_back(IIT_TOKEN);
   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
+  case MVT::x86amx: return Sig.push_back(IIT_AMX);
   // MVT::OtherVT is used to mean the empty struct type here.
   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
   // MVT::isVoid is used to represent varargs here.
Index: llvm/utils/TableGen/CodeGenTarget.cpp
===
--- llvm/utils/TableGen/CodeGenTarget.cpp
+++ llvm/utils/TableGen/CodeGenTarget.cpp
@@ -76,6 +76,7 @@
   case MVT::f128: return "MVT::f128";
   case MVT::ppcf128:  return "MVT::ppcf128";
   case MVT::x86mmx:   return "MVT::x86mmx";
+  case MVT::x86amx:   return "MVT::x86amx";
   case MVT::Glue: return "MVT::Glue";
   case MVT::isVoid:   return "MVT::isVoid";
   case MVT::v1i1: return "MVT::v1i1";
Index: llvm/test/CodeGen/X86/AMX/amx-type.ll
===
--- llvm/test/CodeGen/X86/AMX/amx-type.ll
+++ llvm/test/CodeGen/X86/AMX/amx-type.ll
@@ -8,18 +8,146 @@
 @buf = dso_local global [1024 x i8] zeroinitializer, align 16
 @buf2 = dso_local global [1024 x i8] zeroinitializer, align 16
 
+define dso_local <256 x i32> @test_amx_bitcast(<256 x i32> %in) #2 {
+; CHECK-LABEL: @test_amx_bitcast(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:ret <256 x i32> [[IN:%.*]]
+;
+entry:
+  %amx = bitcast <256 x i32> %in to x86_amx
+  %vec = bitcast x86_amx %amx to <256 x i32>
+  ret <256 x i32> %vec
+}
+
+define dso_local void @test_amx_store(<256 x i32>* %in, i16 %m, i16 %n, i8 *%buf, i64 %s) #2 {
+; CHECK-LABEL: @test_amx_store(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[T0:%.*]] = call x86_amx @llvm.x86.tileloadd64.internal(i16 [[M:%.*]], i16 [[N:%.*]], i8* [[BUF:%.*]], i64 [[S:%.*]]) [[ATTR3:#.*]]
+; CHECK-NEXT:[[ADDR:%.*]] = bitcast <256 x i32>* [[IN:%.*]] to x86_amx*
+; CHECK-NEXT:[[TMP0:%.*]] = bitcast x86_amx* [[ADDR]] to i8*
+; CHECK-NEXT:call void @llvm.x86.tilestored64.internal(i16 [[M]], i16 [[N]], i8* [[TMP0]], i64 64, x86_amx [[T0]])
+; CHECK-NEXT:ret void
+;
+entry:
+  %t0 = call x86_amx @llvm.x86.tileloadd64.internal(i16 %m, i16 %n, i8* %buf, i64 %s) #3
+  %addr = bitcast <256 x i32>* %in to x86_amx*
+  store x86_amx %t0, x86_amx* %addr, align 64
+  ret void
+}
+
+define dso_local void @test_amx_load(<256 x i32>* %in, i16 %m, i16 %n, i8 *%buf, i64 %s) #2 {
+; CHECK-LABEL: @test_amx_load(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[T0:%.*]] = bitcast <256 x i32>* [[IN:%.*]] to x86_amx*
+; CHECK-NEXT:[[TMP0:%.*]] = bitcast x86_amx* [[T0]] to i8*
+; CHECK-NEXT:[[TMP1:%.*]] = call x86_amx @llvm.x86.tileloadd64.internal(i16 [[M:%.*]], i16 [[N:%.*]], i8* [[TMP0]], i64 64)
+; CHECK-NEXT:call void @llvm.x86.tilestored64.internal(i16 [[M]], i16 [[N]], i8* [[BUF:%.*]], i64 [[S:%.*]], x86_amx [[TMP1]]) [[ATTR3]]
+; CHECK-NEXT:ret void
+;
+entry:
+  %t0 = bitcast <256 x i32>* %in to x86_amx*
+  %t1 = load x86_amx, x86_amx* %t

[PATCH] D93700: [clang][cli] Report the actual argument parsing result

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93700

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Frontend/CompilerInvocationTest.cpp

Index: clang/unittests/Frontend/CompilerInvocationTest.cpp
===
--- clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -100,9 +100,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTrueSingleFlagNotPresent) {
   const char *Args[] = {""};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_TRUE(Invocation.getFrontendOpts().UseTemporary);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -113,9 +111,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTrueSingleFlagPresent) {
   const char *Args[] = {"-fno-temp-file"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_FALSE(Invocation.getFrontendOpts().UseTemporary);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -126,10 +122,8 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTrueSingleFlagUnknownPresent) {
   const char *Args[] = {"-ftemp-file"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-
   // Driver-only flag.
-  ASSERT_TRUE(Diags->hasErrorOccurred());
+  ASSERT_FALSE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_TRUE(Invocation.getFrontendOpts().UseTemporary);
 }
 
@@ -140,8 +134,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTruePresentNone) {
   const char *Args[] = {""};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_TRUE(Invocation.getCodeGenOpts().Autolink);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -152,8 +145,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTruePresentNegChange) {
   const char *Args[] = {"-fno-autolink"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_FALSE(Invocation.getCodeGenOpts().Autolink);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -164,8 +156,8 @@
 TEST_F(CommandLineTest, BoolOptionDefaultTruePresentPosReset) {
   const char *Args[] = {"-fautolink"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_TRUE(Diags->hasErrorOccurred()); // Driver-only flag.
+  // Driver-only flag.
+  ASSERT_FALSE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_TRUE(Invocation.getCodeGenOpts().Autolink);
 }
 
@@ -176,8 +168,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNone) {
   const char *Args[] = {""};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_FALSE(Invocation.getCodeGenOpts().NoInlineLineTables);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -188,8 +179,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNegChange) {
   const char *Args[] = {"-gno-inline-line-tables"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_TRUE(Invocation.getCodeGenOpts().NoInlineLineTables);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -200,8 +190,8 @@
 TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentPosReset) {
   const char *Args[] = {"-ginline-line-tables"};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_TRUE(Diags->hasErrorOccurred()); // Driver-only flag.
+  // Driver-only flag.
+  ASSERT_FALSE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_FALSE(Invocation.getCodeGenOpts().NoInlineLineTables);
 }
 
@@ -212,8 +202,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultFalsePresentNoneX) {
   const char *Args[] = {""};
 
-  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
-  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags));
   ASSERT_FALSE(Invocation.getCodeGenOpts().CodeViewGHash);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
@@ -224,8 +213,7 @@
 TEST_F(CommandLineTest, BoolOptionDefaultFals

[PATCH] D93701: [clang][cli] NFC: Make Diags optional in normalizer

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is needed for a future patch, where we start using normalizers in contexts 
where no Diags are available.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93701

Files:
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -131,7 +131,7 @@
 
 static llvm::Optional
 normalizeSimpleFlag(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
-DiagnosticsEngine &Diags, bool &Success) {
+DiagnosticsEngine *Diags, bool &Success) {
   if (Args.hasArg(Opt))
 return true;
   return None;
@@ -139,7 +139,7 @@
 
 static Optional normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
   const ArgList &Args,
-  DiagnosticsEngine &,
+  DiagnosticsEngine *,
   bool &Success) {
   if (Args.hasArg(Opt))
 return false;
@@ -166,7 +166,7 @@
   std::enable_if_t(), bool> = false>
 static auto makeFlagToValueNormalizer(T Value) {
   return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
- DiagnosticsEngine &, bool &Success) -> Optional {
+ DiagnosticsEngine *, bool &Success) -> Optional {
 if (Args.hasArg(Opt))
   return Value;
 return None;
@@ -182,7 +182,7 @@
 static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
 OptSpecifier OtherOpt) {
   return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
-   const ArgList &Args, DiagnosticsEngine &,
+   const ArgList &Args, DiagnosticsEngine *,
bool &Success) -> Optional {
 if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
   return A->getOption().matches(Opt) ? Value : OtherValue;
@@ -248,7 +248,7 @@
 
 static llvm::Optional
 normalizeSimpleEnum(OptSpecifier Opt, unsigned TableIndex, const ArgList &Args,
-DiagnosticsEngine &Diags, bool &Success) {
+DiagnosticsEngine *Diags, bool &Success) {
   assert(TableIndex < SimpleEnumValueTablesSize);
   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
 
@@ -261,8 +261,9 @@
 return MaybeEnumVal->Value;
 
   Success = false;
-  Diags.Report(diag::err_drv_invalid_value)
-  << Arg->getAsString(Args) << ArgValue;
+  if (Diags)
+Diags->Report(diag::err_drv_invalid_value)
+<< Arg->getAsString(Args) << ArgValue;
   return None;
 }
 
@@ -294,7 +295,7 @@
 
 static Optional normalizeString(OptSpecifier Opt, int TableIndex,
  const ArgList &Args,
- DiagnosticsEngine &Diags,
+ DiagnosticsEngine *Diags,
  bool &Success) {
   auto *Arg = Args.getLastArg(Opt);
   if (!Arg)
@@ -305,22 +306,23 @@
 template 
 static Optional
 normalizeStringIntegral(OptSpecifier Opt, int, const ArgList &Args,
-DiagnosticsEngine &Diags, bool &Success) {
+DiagnosticsEngine *Diags, bool &Success) {
   auto *Arg = Args.getLastArg(Opt);
   if (!Arg)
 return None;
   IntTy Res;
   if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
 Success = false;
-Diags.Report(diag::err_drv_invalid_int_value)
-<< Arg->getAsString(Args) << Arg->getValue();
+if (Diags)
+  Diags->Report(diag::err_drv_invalid_int_value)
+  << Arg->getAsString(Args) << Arg->getValue();
   }
   return Res;
 }
 
 static Optional>
 normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
-  DiagnosticsEngine &, bool &Success) {
+  DiagnosticsEngine *, bool &Success) {
   return Args.getAllArgValues(Opt);
 }
 
@@ -356,7 +358,7 @@
 
 static Optional normalizeTriple(OptSpecifier Opt, int TableIndex,
  const ArgList &Args,
- DiagnosticsEngine &Diags,
+ DiagnosticsEngine *Diags,
  bool &Success) {
   auto *Arg = Args.getLastArg(Opt);
   if (!Arg)
@@ -2990,7 +2992,9 @@
 }
 
 bool CompilerInvocation::parseSimpleArgs(const ArgList &Args,
- DiagnosticsEngine &Diags) {
+   

[PATCH] D93702: [clang][cli] NFC: Make marshalling macros reusable

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is necessary for a future patch, where we start using these macros in 
multiple places.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93702

Files:
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -384,6 +384,46 @@
   return KeyPath & Value;
 }
 
+/// Expects the following variables to be visible:
+///   * const ArgList &Args
+///   * DiagnosticsEngine *Diags
+///   * bool &Success
+#define PARSE_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
+TABLE_INDEX)   \
+  if ((FLAGS)&options::CC1Option) {\
+this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
+if (IMPLIED_CHECK) \
+  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
+if (auto MaybeValue =  \
+NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
+  this->KEYPATH = MERGER(  \
+  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
+  }
+
+/// Expects the following variables to be visible:
+///   * SmallVectorImpl &Args
+///   * CompilerInvocation::StringAllocator SA
+// Capture the extracted value as a lambda argument to avoid potential issues
+// with lifetime extension of the reference.
+#define GENERATE_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
+TABLE_INDEX)   \
+  if ((FLAGS)&options::CC1Option) {\
+[&](const auto &Extracted) {   \
+  if (ALWAYS_EMIT ||   \
+  (Extracted !=\
+   static_castKEYPATH)>(   \
+   (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE  \
+DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \
+ Extracted);   \
+}(EXTRACTOR(this->KEYPATH));   \
+  }
+
 static void FixupInvocation(CompilerInvocation &Invocation,
 DiagnosticsEngine &Diags,
 const InputArgList &Args) {
@@ -3002,15 +3042,11 @@
 HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
 TABLE_INDEX)   \
-  if ((FLAGS)&options::CC1Option) {\
-this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
-if (IMPLIED_CHECK) \
-  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
-if (auto MaybeValue =  \
-NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
-  this->KEYPATH = MERGER(  \
-  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
-  }
+  PARSE_OPTION_WITH_MARSHALLING(   \
+  PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
+  HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH,   \
+  DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,   \
+  MERGER, EXTRACTOR, TABLE_INDEX)
 
 #include "clang/Driver/Options.inc"
 #undef OPTION_WITH_MARSHALLING
@@ -3259,23 +3295,17 @@
 
 void CompilerInvocation::generateCC1CommandLine(
 SmallVectorImpl &Args, StringAllocator SA) const {
-  // Capture the extracted value as a lambda argument to avo

[PATCH] D93626: [clang-format] PR48535 clang-format Incorrectly Removes Space After C Style Cast When Type Is Not a Pointer

2020-12-22 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

In D93626#2467927 , @MyDeveloperDay 
wrote:

> In D93626#2467745 , @curdeius wrote:
>
>> LGTM now. I tried to find other cases where this change may change the 
>> behaviour but couldn't. Have you tried applying to some bigger repo and see 
>> what you get? The best would be a repo with SpaceAfterCStyleCast=true.
>
> Only my own internally, which I preconverted to using this style using an 
> older clang-format then ran with this version. This seems to be fixing more 
> cases than creating false positives:
>
> Here are just 2 additional cases I found
>
>   int a = (int16)(a + (b << 2) + (c << 4));
>   if ((size_t)(a - b) <= c)
>
> which become
>
>   int a = (int16) (a + (b << 2) + (c << 4));
>   if ((size_t) (a - b) <= c) {

Great!


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

https://reviews.llvm.org/D93626

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


[PATCH] D93699: [clang][cli] Port getAllArgumentValues to the marshalling infrastructure

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 abandoned this revision.
jansvoboda11 added a comment.

Duplicate of D93679 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93699

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


[PATCH] D93110: [analyzer] Implement a first version of suppressions via attributes

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D93110#2460375 , @vsavchenko wrote:

> In D93110#2458613 , @aaron.ballman 
> wrote:
>
>> Have you explored how this attribute will work with clang frontend 
>> diagnostics or clang-tidy diagnostics?
>
> Actually, this attribute is not used anywhere in the codebase (even in 
> `clang-tidy`!).  I think that it can be used for warning suppressions as 
> well, it is more comfortable than pragmas IMO.  However, I think that the 
> problem of false positive or, for that matter, suppressions is much more 
> visible with static analysis tools.

Agreed that an attribute will feel like a more natural way to suppress 
diagnostics than using a pragma. However, use of the pragma in the wild 
suggests people are just as interested in suppressing frontend diagnostics as 
they are any other kind. I'd like to make sure that whatever we design can be 
used for all of these purposes. What I want to avoid is having a static 
analyzer-specific suppression attribute, and a different one for clang-tidy, 
and a third one for the frontend. I also want to avoid confusing behavior. 
That's why I was wondering if you were considering the wider scope as part of 
this design.

For instance, given code like:

  signed i = ...;
  unsigned u = ...;
  int *ptr = ...;
  int what = ...;
  
  int val = i < u ? *ptr : *ptr / what;

This code would have at least three different diagnostics -- a signed/unsigned 
comparison, a possible null dereference of ptr (twice), and a possible divide 
by zero. If the user tries to add `[[clang::suppress]]` to that statement, it 
won't suppress all of the diagnostics. Also, depending on how the suppression 
works, it may also be even more unintuitive because clang-tidy runs the clang 
static analyzer and the clang frontend, so the user may be able to suppress 
some warnings that look like they come from clang-tidy and not others. I think 
that's going to be confusing behavior for users and we don't want to live in 
that state for very long and we should be considering the bigger design of the 
feature (which may require an RFC given how many components are involved).

I'm not suggesting we have to roll out complete support for everything with the 
initial patch. I'm fine if the initial support only suppresses static analyzer 
warnings so long as there's a clear path forward for the other components and 
(hopefully) some promise of extending support to those within the next release 
or two. I don't want a repeat of what happened with `[[gsl::suppress]]` (where 
we added the attribute to Clang, didn't utilize it in tree, the C++ Core 
Guideline then changed the syntax for the attribute to be incompatible with 
what we provided, and we're left with something that's not particularly useful 
for anyone).

>> One usability concern I have with adding [[clang::suppress]] is that users 
>> are going to want to use it to suppress all the various kinds of diagnostics 
>> and not just clang static analyzer warnings.
>
> Documentation will explicitly state that this mechanism is for the clang 
> static analyzer and if users would like to use it for others things as well, 
> that would prove that it is a good approach and can be fully supported in 
> other parts of Clang.

I don't think documentation will be sufficient long-term. The attribute name is 
basically self-documenting in terms of what the user will expect it to do and 
it won't behave in the obvious way.

> Additionally, I was thinking about third parties developing their own static 
> analysis tools using Clang as a parser for C/C++/Obj-C.  They would probably 
> also like to use this attribute.  This is one reason why we probably 
> shouldn't complain about unknown identifiers used with this attribute.

That's a great point and is definitely something that should be considered as 
part of the wider concern.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93110

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


[PATCH] D91927: [X86] Add x86_amx type for intel AMX.

2020-12-22 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: llvm/lib/Target/X86/X86LowerAMXType.cpp:264
+  SmallVector DeadInsts;
+  SmallVector DeadBitcasts;
+

Maybe better to use BitCastInst?



Comment at: llvm/lib/Target/X86/X86LowerAMXType.cpp:274
+  if (Bitcast->user_empty()) {
+DeadInsts.push_back(Bitcast);
 continue;

Why don't put it in DeadBitcasts?



Comment at: llvm/lib/Target/X86/X86LowerAMXType.cpp:280
+  Type *Ty = Bitcast->getType();
+  auto CanonicalizeBitcast = [&]() {
+bool Change = false;

Can we leave the canonicalize bitcast cases a single patch. It's a bit complex 
here and I don't think it's a common case.



Comment at: llvm/lib/Target/X86/X86LowerAMXType.cpp:420
   }
+  // Delete user first.
+  for (auto *Inst : DeadBitcasts)

This comment is for above code? Better move it up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91927

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


[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

Thank you for working on this, it's a problem that's annoyed me for a while but 
I've never found a satisfactory solution to. Unfortunately, it causes us to 
reject valid code (which is the same problem I kept running up against when I 
last tried).




Comment at: clang/test/Index/blocks.c:8
   static struct foo _foo;
-  __block i = 0;
+  __block int i = 0;
   ^ int_t(struct foo *foo) { return (int_t) foo->x + i; }(&_foo);

This change should not be necessary as the original code was valid (and I think 
was testing that validity, but could probably use a comment to make that 
explicit).



Comment at: clang/test/Sema/address_spaces.c:12
 {
-  _AS2 *x;// expected-warning {{type specifier missing, defaults to 'int'}}
+  _AS2 *x; // expected-error {{'address_space' attribute cannot be applied to 
a statement}}
+  // expected-error@-1 {{use of undeclared identifier 'x'}}

This breaks valid C89 code that uses implicit int (it is also a less helpful 
diagnostic, but that's secondary to the rejects valid bug).



Comment at: clang/test/Sema/block-literal.c:44
   takeblock(^{ x = 4; });  // expected-error {{variable is not assignable 
(missing __block type specifier)}}
-  __block y = 7;// expected-warning {{type specifier missing, defaults to 
'int'}}
-  takeblock(^{ y = 8; });
+  __block y = 7;   // expected-error {{use of undeclared identifier 
'y'}}
+  __block int z = 7;

This is also valid C89 that should not be rejected.



Comment at: clang/test/SemaTemplate/address_space-dependent.cpp:12-13
 
-  __attribute__((address_space(J))) * x; // expected-error {{C++ requires a 
type specifier for all declarations}}
+  __attribute__((address_space(J))) * x; // expected-error {{use of undeclared 
identifier 'x'}}
+  // expected-error@-1 {{'address_space' attribute cannot be applied to a 
statement}}
 

I think this is a pretty unfortunate degradation of diagnostic wording. The 
code looks like a somewhat validish declaration, so the diagnostic about a 
missing type specifier is more helpful than a use of an undeclared identifier 
that the user is likely trying to declare.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

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


[PATCH] D93703: [libTooling] Change `addInclude` to use expansion locs.

2020-12-22 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: tdl-g.
ymandel requested review of this revision.
Herald added a project: clang.

This patch changes the default range used to anchor the include insertion to use
an expansion loc.  This ensures that the location is valid, when the user relies
on the default range.

Driveby: extend a FIXME for a problem that was emphasized by this change; fix 
some spellings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93703

Files:
  clang/include/clang/Tooling/Transformer/RewriteRule.h
  clang/lib/Tooling/Transformer/RewriteRule.cpp


Index: clang/lib/Tooling/Transformer/RewriteRule.cpp
===
--- clang/lib/Tooling/Transformer/RewriteRule.cpp
+++ clang/lib/Tooling/Transformer/RewriteRule.cpp
@@ -42,7 +42,12 @@
 llvm::Optional EditRange =
 tooling::getRangeForEdit(*Range, *Result.Context);
 // FIXME: let user specify whether to treat this case as an error or ignore
-// it as is currently done.
+// it as is currently done. This behavior is problematic in that it hides
+// failures from bad ranges. Also, the behavior here differs from
+// `flatten`. Here, we abort (without error), whereas flatten, if it hits 
an
+// empty list, does not abort. As a result, `editList({A,B})` is not
+// equivalent to `flatten(edit(A), edit(B))`. The former will abort if `A`
+// produces a bad range, whereas the latter will simply ignore A.
 if (!EditRange)
   return SmallVector();
 auto Replacement = E.Replacement->eval(Result);
Index: clang/include/clang/Tooling/Transformer/RewriteRule.h
===
--- clang/include/clang/Tooling/Transformer/RewriteRule.h
+++ clang/include/clang/Tooling/Transformer/RewriteRule.h
@@ -213,10 +213,12 @@
IncludeFormat Format = IncludeFormat::Quoted);
 
 /// Adds an include directive for the given header to the file associated with
-/// `RootID`.
+/// `RootID`. If `RootID` matches inside a macro expansion, will add the
+/// directive to the file in which the macro was expanded (as opposed to the
+/// file in which the macro is defined).
 inline ASTEdit addInclude(StringRef Header,
   IncludeFormat Format = IncludeFormat::Quoted) {
-  return addInclude(node(RootID), Header, Format);
+  return addInclude(expansion(node(RootID)), Header, Format);
 }
 
 // FIXME: If `Metadata` returns an `llvm::Expected` the `AnyGenerator` will
@@ -312,8 +314,8 @@
 /// \code
 ///   auto R = makeRule(callExpr(callee(functionDecl(hasName("foo",
 ///changeTo(cat("bar()")));
-///   AddInclude(R, "path/to/bar_header.h");
-///   AddInclude(R, "vector", IncludeFormat::Angled);
+///   addInclude(R, "path/to/bar_header.h");
+///   addInclude(R, "vector", IncludeFormat::Angled);
 /// \endcode
 void addInclude(RewriteRule &Rule, llvm::StringRef Header,
 IncludeFormat Format = IncludeFormat::Quoted);


Index: clang/lib/Tooling/Transformer/RewriteRule.cpp
===
--- clang/lib/Tooling/Transformer/RewriteRule.cpp
+++ clang/lib/Tooling/Transformer/RewriteRule.cpp
@@ -42,7 +42,12 @@
 llvm::Optional EditRange =
 tooling::getRangeForEdit(*Range, *Result.Context);
 // FIXME: let user specify whether to treat this case as an error or ignore
-// it as is currently done.
+// it as is currently done. This behavior is problematic in that it hides
+// failures from bad ranges. Also, the behavior here differs from
+// `flatten`. Here, we abort (without error), whereas flatten, if it hits an
+// empty list, does not abort. As a result, `editList({A,B})` is not
+// equivalent to `flatten(edit(A), edit(B))`. The former will abort if `A`
+// produces a bad range, whereas the latter will simply ignore A.
 if (!EditRange)
   return SmallVector();
 auto Replacement = E.Replacement->eval(Result);
Index: clang/include/clang/Tooling/Transformer/RewriteRule.h
===
--- clang/include/clang/Tooling/Transformer/RewriteRule.h
+++ clang/include/clang/Tooling/Transformer/RewriteRule.h
@@ -213,10 +213,12 @@
IncludeFormat Format = IncludeFormat::Quoted);
 
 /// Adds an include directive for the given header to the file associated with
-/// `RootID`.
+/// `RootID`. If `RootID` matches inside a macro expansion, will add the
+/// directive to the file in which the macro was expanded (as opposed to the
+/// file in which the macro is defined).
 inline ASTEdit addInclude(StringRef Header,
   IncludeFormat Format = IncludeFormat::Quoted) {
-  return addInclude(node(RootID), Header, Format);
+  return addInclude(expansion(node(RootID)), Header, Format);
 }
 
 // FIXME: If `Metadata` returns an `llvm::Expected` the `AnyGenerator` will
@@ -312,8

[PATCH] D93702: [clang][cli] NFC: Make marshalling macros reusable

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 313335.
jansvoboda11 added a comment.

Add newline at the end of file, simplify macro forwarding


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93702

Files:
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -384,6 +384,46 @@
   return KeyPath & Value;
 }
 
+/// Expects the following variables to be visible:
+///   * const ArgList &Args
+///   * DiagnosticsEngine *Diags
+///   * bool &Success
+#define PARSE_OPTION_WITH_MARSHALLING( \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
+TABLE_INDEX)   \
+  if ((FLAGS)&options::CC1Option) {\
+this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
+if (IMPLIED_CHECK) \
+  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
+if (auto MaybeValue =  \
+NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
+  this->KEYPATH = MERGER(  \
+  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
+  }
+
+/// Expects the following variables to be visible:
+///   * SmallVectorImpl &Args
+///   * CompilerInvocation::StringAllocator SA
+// Capture the extracted value as a lambda argument to avoid potential issues
+// with lifetime extension of the reference.
+#define GENERATE_OPTION_WITH_MARSHALLING(  \
+PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
+HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
+IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
+TABLE_INDEX)   \
+  if ((FLAGS)&options::CC1Option) {\
+[&](const auto &Extracted) {   \
+  if (ALWAYS_EMIT ||   \
+  (Extracted !=\
+   static_castKEYPATH)>(   \
+   (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE  \
+DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \
+ Extracted);   \
+}(EXTRACTOR(this->KEYPATH));   \
+  }
+
 static void FixupInvocation(CompilerInvocation &Invocation,
 DiagnosticsEngine &Diags,
 const InputArgList &Args) {
@@ -2997,21 +3037,7 @@
 
   bool Success = true;
 
-#define OPTION_WITH_MARSHALLING(   \
-PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,\
-HELPTEXT, METAVAR, VALUES, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,  \
-IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
-TABLE_INDEX)   \
-  if ((FLAGS)&options::CC1Option) {\
-this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
-if (IMPLIED_CHECK) \
-  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
-if (auto MaybeValue =  \
-NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
-  this->KEYPATH = MERGER(  \
-  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
-  }
-
+#define OPTION_WITH_MARSHALLING PARSE_OPTION_WITH_MARSHALLING
 #include "clang/Driver/Options.inc"
 #undef OPTION_WITH_MARSHALLING
 
@@ -3259,24 +3285,8 @@
 
 void CompilerInvocation::generateCC1CommandLine(
 SmallVectorImpl &Args, StringAllocator SA) const {
-  // Capture the extracted value as a lambda argument to avoid potential issues
-  // with lifetime extension of the reference.
-#define OPTION_WITH_MARSHALLING(   \
-PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS,

[PATCH] D84673: [clang][cli] Port DiagnosticOpts to new option parsing system

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 313337.
jansvoboda11 added a comment.

Rebase, undo NFC changes. Replace the previous diagnostic option tagging system 
implemented in TableGen with less intrusive backend check. Extract prep patches.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84673

Files:
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -99,6 +99,14 @@
 
   MarshallingInfo(const Record &R) : R(R) {}
 
+  std::string getMacroName() const {
+if (KeyPath.startswith("DiagnosticOpts.")) {
+  return (Twine("DIAG_") + MarshallingInfo::MacroName).str();
+}
+
+return MarshallingInfo::MacroName;
+  }
+
   void emit(raw_ostream &OS) const {
 write_cstring(OS, StringRef(getOptionSpelling(R)));
 OS << ", ";
@@ -420,13 +428,13 @@
 MarshallingInfos.push_back(createMarshallingInfo(*R));
 
   for (const auto &MI : MarshallingInfos) {
-OS << "#ifdef " << MarshallingInfo::MacroName << "\n";
-OS << MarshallingInfo::MacroName << "(";
+OS << "#ifdef " << MI.getMacroName() << "\n";
+OS << MI.getMacroName() << "(";
 WriteOptRecordFields(OS, MI.R);
 OS << ", ";
 MI.emit(OS);
 OS << ")\n";
-OS << "#endif // " << MarshallingInfo::MacroName << "\n";
+OS << "#endif // " << MI.getMacroName() << "\n";
   }
 
   OS << "\n";
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -394,13 +394,12 @@
 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
 TABLE_INDEX)   \
   if ((FLAGS)&options::CC1Option) {\
-this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
+KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);  \
 if (IMPLIED_CHECK) \
-  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
+  KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);\
 if (auto MaybeValue =  \
 NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
-  this->KEYPATH = MERGER(  \
-  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
+  KEYPATH = MERGER(KEYPATH, static_cast(*MaybeValue));  \
   }
 
 /// Expects the following variables to be visible:
@@ -417,18 +416,17 @@
 [&](const auto &Extracted) {   \
   if (ALWAYS_EMIT ||   \
   (Extracted !=\
-   static_castKEYPATH)>(   \
-   (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE  \
+   static_cast((IMPLIED_CHECK) ? (IMPLIED_VALUE)\
+  : (DEFAULT_VALUE \
 DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \
  Extracted);   \
-}(EXTRACTOR(this->KEYPATH));   \
+}(EXTRACTOR(KEYPATH)); \
   }
 
 static void FixupInvocation(CompilerInvocation &Invocation,
 DiagnosticsEngine &Diags,
 const InputArgList &Args) {
   LangOptions &LangOpts = *Invocation.getLangOpts();
-  DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
   TargetOptions &TargetOpts = Invocation.getTargetOpts();
   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
@@ -442,8 +440,6 @@
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
 
-  llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
-
   llvm::Triple T(TargetOpts.Triple);
   llvm::Triple::ArchType Arch = T.getArch();
 
@@ -1447,82 +1443,22 @@
 bool DefaultDiagColor) {
   bool Success = true;
 
-  Opts.DiagnosticLogFile =
-  std::string(Args.getLastArgValue(OPT_diagnostic_log_file));
+  DiagnosticOptions &DiagnosticOpts = Opts;
+
+#define DIAG_OPTION_WITH_MAR

[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313346.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -483,3 +483,192 @@
   f();
   f();
 }
+
+template 
+bool neverInstantiatedTemplate() {
+  std::vector v;
+  if (v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+
+  if (v == std::vector())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of comparing to an empty object [readability-container-size-empty]
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  if (v.size() == 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (static_cast(v.size()))
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:25: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (static_cast(!v.empty())){{$}}
+  if (v.size() && false)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty() && false){{$}}
+  if (!v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+
+  TemplatedContainer templated_container;
+  if (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  if (templated_container != TemplatedContainer())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  while (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty()){{$}}
+
+  do {
+  }
+  while (templated_container.size());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty());
+
+  for (; templated_container.size();)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}for (; !templated_container.empty();){{$}}
+
+  if (true && templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:15: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (true && !templated_container.empty()){{$}}
+
+  if (true || templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:15: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (true || !templated_container.empty()){{$}}
+
+  if (!templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (templated_container.empty()){{$}}
+
+  bo

[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire marked 2 inline comments as done.
steveire added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:26-28
+  // The first argument of an overloaded member operator is the implicit object
+  // argument of the method which should not be matched against a parameter, so
+  // we skip over it here.

aaron.ballman wrote:
> Isn't this true for any non-static member function? e.g., should the matcher 
> be looking at `cxxOperatorCallExpr()` at all?
 I think it's deliberate - https://godbolt.org/z/EYYndv  - it's just that we 
don't consider the `aa` an argument because the op is a member func.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:67
+  
hasParent(forStmt(hasCondition(expr(equalsBoundNode(exprName),
+  hasParent(varDecl(hasType(booleanType(,
+  hasParent(

aaron.ballman wrote:
> If this matters for var decls, what about field decls in a structure?
Not sure. What would this look like in a test?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp:493
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be 
used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}

aaron.ballman wrote:
> The quoting here is unfortunate. It's not part of your patch, but it could be 
> solved by calling `Container->getName()` and manually quoting the note text 
> if you wanted to hit it in a follow-up (I'd consider that an NFC change, no 
> need to review). You could also address it as part of this patch if you felt 
> like it.
That will be a follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

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


[PATCH] D84673: [clang][cli] Port DiagnosticOpts to new option parsing system

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

I still need to figure out why Clang built in release mode replaces spaces in 
an error message by newlines and indents:

  $ ./build.noindex/debug/bin/clang -c clang/test/Driver/fmessage-length.c 
-fmessage-length=nan 
  clang-12: error: 
invalid
argument
'nan'
to
-fmessage-length=

Where the debug built Clang behaves as expected:

  $ ./build.noindex/debug/bin/clang -c clang/test/Driver/fmessage-length.c 
-fmessage-length=nan
  clang-12: error: invalid argument 'nan' to -fmessage-length=


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84673

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


[PATCH] D84673: [clang][cli] Port DiagnosticOpts to new option parsing system

2020-12-22 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 313347.
jansvoboda11 added a comment.

Remove unnecessary if braces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84673

Files:
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -99,6 +99,13 @@
 
   MarshallingInfo(const Record &R) : R(R) {}
 
+  std::string getMacroName() const {
+if (KeyPath.startswith("DiagnosticOpts."))
+  return (Twine("DIAG_") + MarshallingInfo::MacroName).str();
+
+return MarshallingInfo::MacroName;
+  }
+
   void emit(raw_ostream &OS) const {
 write_cstring(OS, StringRef(getOptionSpelling(R)));
 OS << ", ";
@@ -420,13 +427,13 @@
 MarshallingInfos.push_back(createMarshallingInfo(*R));
 
   for (const auto &MI : MarshallingInfos) {
-OS << "#ifdef " << MarshallingInfo::MacroName << "\n";
-OS << MarshallingInfo::MacroName << "(";
+OS << "#ifdef " << MI.getMacroName() << "\n";
+OS << MI.getMacroName() << "(";
 WriteOptRecordFields(OS, MI.R);
 OS << ", ";
 MI.emit(OS);
 OS << ")\n";
-OS << "#endif // " << MarshallingInfo::MacroName << "\n";
+OS << "#endif // " << MI.getMacroName() << "\n";
   }
 
   OS << "\n";
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -394,13 +394,12 @@
 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, MERGER, EXTRACTOR, \
 TABLE_INDEX)   \
   if ((FLAGS)&options::CC1Option) {\
-this->KEYPATH = MERGER(this->KEYPATH, DEFAULT_VALUE);  \
+KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE);  \
 if (IMPLIED_CHECK) \
-  this->KEYPATH = MERGER(this->KEYPATH, IMPLIED_VALUE);\
+  KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE);\
 if (auto MaybeValue =  \
 NORMALIZER(OPT_##ID, TABLE_INDEX, Args, Diags, Success))   \
-  this->KEYPATH = MERGER(  \
-  this->KEYPATH, static_castKEYPATH)>(*MaybeValue));   \
+  KEYPATH = MERGER(KEYPATH, static_cast(*MaybeValue));  \
   }
 
 /// Expects the following variables to be visible:
@@ -417,18 +416,17 @@
 [&](const auto &Extracted) {   \
   if (ALWAYS_EMIT ||   \
   (Extracted !=\
-   static_castKEYPATH)>(   \
-   (IMPLIED_CHECK) ? (IMPLIED_VALUE) : (DEFAULT_VALUE  \
+   static_cast((IMPLIED_CHECK) ? (IMPLIED_VALUE)\
+  : (DEFAULT_VALUE \
 DENORMALIZER(Args, SPELLING, SA, Option::KIND##Class, TABLE_INDEX, \
  Extracted);   \
-}(EXTRACTOR(this->KEYPATH));   \
+}(EXTRACTOR(KEYPATH)); \
   }
 
 static void FixupInvocation(CompilerInvocation &Invocation,
 DiagnosticsEngine &Diags,
 const InputArgList &Args) {
   LangOptions &LangOpts = *Invocation.getLangOpts();
-  DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
   TargetOptions &TargetOpts = Invocation.getTargetOpts();
   FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
@@ -442,8 +440,6 @@
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
 
-  llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
-
   llvm::Triple T(TargetOpts.Triple);
   llvm::Triple::ArchType Arch = T.getArch();
 
@@ -1447,82 +1443,22 @@
 bool DefaultDiagColor) {
   bool Success = true;
 
-  Opts.DiagnosticLogFile =
-  std::string(Args.getLastArgValue(OPT_diagnostic_log_file));
+  DiagnosticOptions &DiagnosticOpts = Opts;
+
+#define DIAG_OPTION_WITH_MARSHALLING PARSE_OPTION_WITH_MARSHALLING
+#include "clang/Driver/Options.inc"
+#undef DIAG_OPTION_WITH_MARSHALLING
+
+  llvm::sys::Process::UseA

[PATCH] D93586: [InstCombine] use poison as placeholder for undemanded elems

2020-12-22 Thread Juneyoung Lee via Phabricator via cfe-commits
aqjune added a comment.

In D93586#2467844 , @RKSimon wrote:

> I'm sorry I've only just started looking at this - are you saying that you 
> want to handle all "insertelement undef" cases in one go and not just a 
> series of patcches after this one?

It will be treated in a series of patches. There are places other than 
SimplifyDemandedVectorElts that create `insertelement undef`. I'll create these 
and link them as children.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93586

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


[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

@aaron.ballman I totally agree, but I also would like to understand. 
`__attribute__` is a GNU extension, right?  Then why does it affect the grammar 
of C?  I always thought that attributes should be somewhat transparent for 
parsers, but it looks like in this situation all compilers automatically assume 
that `__attribute__` begins a declaration.
It is unclear to me why `*x;`, `[[unknown]] *x;` (dereference of x) and 
`__attribute__((unknown)) *x;` (declaration of `int *`) have different meanings.

Does it essentially mean that there is no way to implement statement attributes 
in C/Obj-C?
Because even if we introduce some heuristics for understanding that what we 
parsed is a declaration attribute -> what follows must be a declaration, 
attributes that can be applied to both declaration and statements will cause 
confusion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

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


[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:56
+AST_MATCHER(Expr, usedInBooleanContext) {
+  std::string exprName = "__booleanContextExpr";
+  auto result =





Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:57
+  std::string exprName = "__booleanContextExpr";
+  auto result =
+  expr(expr().bind(exprName),





Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:84
+  .matches(Node, Finder, Builder);
+  Builder->removeBindings([this, exprName](const BoundNodesMap &Nodes) {
+return Nodes.getNode(exprName).getNodeKind().isNone();

Might as well drop the `this` from here.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:67
+  
hasParent(forStmt(hasCondition(expr(equalsBoundNode(exprName),
+  hasParent(varDecl(hasType(booleanType(,
+  hasParent(

steveire wrote:
> aaron.ballman wrote:
> > If this matters for var decls, what about field decls in a structure?
> Not sure. What would this look like in a test?
I was thinking this one:
```
struct S {
  std::vector C;
  bool B = C.size();
};
```
but that seems to be handled properly already.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp:493
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be 
used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}

steveire wrote:
> aaron.ballman wrote:
> > The quoting here is unfortunate. It's not part of your patch, but it could 
> > be solved by calling `Container->getName()` and manually quoting the note 
> > text if you wanted to hit it in a follow-up (I'd consider that an NFC 
> > change, no need to review). You could also address it as part of this patch 
> > if you felt like it.
> That will be a follow-up.
SGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

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


[PATCH] D90670: Simplifying memory globalization from the front end to move optimizations to the middle end.

2020-12-22 Thread Jose Manuel Monsalve Diaz via Phabricator via cfe-commits
josemonsalve2 updated this revision to Diff 313352.
josemonsalve2 added a comment.

Modifying 3 more tests to reflect changes in this patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90670

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.h
  clang/test/OpenMP/declare_target_codegen_globalization.cpp
  clang/test/OpenMP/nvptx_data_sharing.cpp
  clang/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_codegen.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
  openmp/libomptarget/deviceRTLs/common/src/data_sharing.cu
  openmp/libomptarget/deviceRTLs/interface.h

Index: openmp/libomptarget/deviceRTLs/interface.h
===
--- openmp/libomptarget/deviceRTLs/interface.h
+++ openmp/libomptarget/deviceRTLs/interface.h
@@ -432,7 +432,7 @@
 EXTERN void __kmpc_data_sharing_init_stack_spmd();
 EXTERN void *__kmpc_data_sharing_coalesced_push_stack(size_t size,
 int16_t UseSharedMemory);
-EXTERN void *__kmpc_data_sharing_push_stack(size_t size, int16_t UseSharedMemory);
+EXTERN void *__kmpc_data_sharing_push_stack(size_t size);
 EXTERN void __kmpc_data_sharing_pop_stack(void *a);
 EXTERN void __kmpc_begin_sharing_variables(void ***GlobalArgs, size_t nArgs);
 EXTERN void __kmpc_end_sharing_variables();
Index: openmp/libomptarget/deviceRTLs/common/src/data_sharing.cu
===
--- openmp/libomptarget/deviceRTLs/common/src/data_sharing.cu
+++ openmp/libomptarget/deviceRTLs/common/src/data_sharing.cu
@@ -144,11 +144,7 @@
 // the list of references to shared variables and to pre-allocate global storage
 // for holding the globalized variables.
 //
-// By default the globalized variables are stored in global memory. If the
-// UseSharedMemory is set to true, the runtime will attempt to use shared memory
-// as long as the size requested fits the pre-allocated size.
-EXTERN void *__kmpc_data_sharing_push_stack(size_t DataSize,
-int16_t UseSharedMemory) {
+EXTERN void *__kmpc_data_sharing_push_stack(size_t DataSize) {
   // Compute the total memory footprint of the requested data.
   // The master thread requires a stack only for itself. A worker
   // thread (which at this point is a warp master) will require
Index: llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
===
--- llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
+++ llvm/include/llvm/Frontend/OpenMP/OMPKinds.def
@@ -543,7 +543,7 @@
 __OMP_RTL(__kmpc_data_sharing_init_stack_spmd, false, Void, )
 
 __OMP_RTL(__kmpc_data_sharing_coalesced_push_stack, false, VoidPtr, SizeTy, Int16)
-__OMP_RTL(__kmpc_data_sharing_push_stack, false, VoidPtr, SizeTy, Int16)
+__OMP_RTL(__kmpc_data_sharing_push_stack, false, VoidPtr, SizeTy)
 __OMP_RTL(__kmpc_data_sharing_pop_stack, false, Void, VoidPtr)
 __OMP_RTL(__kmpc_begin_sharing_variables, false, Void, VoidPtrPtrPtr, SizeTy)
 __OMP_RTL(__kmpc_end_sharing_variables, false, Void, )
Index: clang/test/OpenMP/nvptx_parallel_codegen.cpp
===
--- clang/test/OpenMP/nvptx_parallel_codegen.cpp
+++ clang/test/OpenMP/nvptx_parallel_codegen.cpp
@@ -1,16 +1,16 @@
 // Test target codegen - host bc file has to be created first.
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc
-// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -disable-llvm-optzns | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 --check-prefix SEQ
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -disable-llvm-optzns -fopenmp-cuda-parallel-target-regions | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 --check-prefix PAR
 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc
-// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - -disable-llvm-optzns | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 --check-prefix SEQ
-// RUN: %clang_cc1 -verify -fopenmp -fexceptions -fcxx-exceptions -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - -disable-llvm-optzns | FileCheck %s --check-prefix CHECK --check-pr

[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D93630#2468168 , @vsavchenko wrote:

> @aaron.ballman I totally agree, but I also would like to understand. 
> `__attribute__` is a GNU extension, right?

Correct.

> Then why does it affect the grammar of C?  I always thought that attributes 
> should be somewhat transparent for parsers, but it looks like in this 
> situation all compilers automatically assume that `__attribute__` begins a 
> declaration.

GNU attributes are kind of awful in that they "slide" around to whatever 
construct seems to make the most sense based on the given attribute. My guess 
is that this assumption is baked into compilers because otherwise there would 
be parsing ambiguities. e.g., `__attribute__((attr)) int x = ..., y, z;` could 
either be a declaration attribute that applies to `x`, `y`, and `z` or maybe 
it's a statement attribute that's meant to suppress a diagnostic on the 
initialization of x (that sort of thing), and it would take too much lookahead 
to make a determination based on the attribute name.

> It is unclear to me why `*x;`, `[[unknown]] *x;` (dereference of x) and 
> `__attribute__((unknown)) *x;` (declaration of `int *`) have different 
> meanings.

C and C++ style attributes have a very well-defined meaning in terms of what 
they appertain to based on the syntactic location of the attribute rather than 
based on the name of the attribute. That's why `[[attr]] *x;` and 
`__attribute__((attr))) *x` behave differently.

> Does it essentially mean that there is no way to implement statement 
> attributes in C/Obj-C?
> Because even if we introduce some heuristics for understanding that what we 
> parsed is a declaration attribute -> what follows must be a declaration, 
> attributes that can be applied to both declaration and statements will cause 
> confusion.

That was really the crux of the problem I kept running into as well. I wouldn't 
say there's "no way" to do it, but it's not as trivial as it feels like it 
should be.

If we could tell that the attribute is a decl or stmt attribute, we could throw 
our hands up in that specific circumstance and say "this code is ambiguous", 
but then we're extending the syntactic locations of where GNU attributes can be 
written and what they mean (so we'd diverge from GCC). But then again, we've 
done that before (such as with allowing you to write a GNU-style attribute on a 
function definition, as in: https://godbolt.org/z/PGrfP3 (but this has caused 
users some pain, from what I understand).

Perhaps coordinating with the GCC folks on this may not be a bad idea. However, 
taking a step back -- what attributes would need this functionality (and 
couldn't be written on something within the expression statement)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

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


[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313354.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -483,3 +483,192 @@
   f();
   f();
 }
+
+template 
+bool neverInstantiatedTemplate() {
+  std::vector v;
+  if (v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+
+  if (v == std::vector())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of comparing to an empty object [readability-container-size-empty]
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  if (v.size() == 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (static_cast(v.size()))
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:25: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (static_cast(!v.empty())){{$}}
+  if (v.size() && false)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty() && false){{$}}
+  if (!v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+
+  TemplatedContainer templated_container;
+  if (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  if (templated_container != TemplatedContainer())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  while (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty()){{$}}
+
+  do {
+  }
+  while (templated_container.size());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty());
+
+  for (; templated_container.size();)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}for (; !templated_container.empty();){{$}}
+
+  if (true && templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:15: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (true && !templated_container.empty()){{$}}
+
+  if (true || templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:15: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (true || !templated_container.empty()){{$}}
+
+  if (!templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (templated_container.empty()){{$}}
+
+  bo

[PATCH] D80623: WIP: Add an API to simplify setting TraversalKind in clang-tidy matchers

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchFinder.h:118
+/// behavior of clang-tidy.
+virtual llvm::Optional
+getCheckTraversalKind() const;

aaron.ballman wrote:
> steveire wrote:
> > sammccall wrote:
> > > I don't really get why this would be optional.
> > > A check's implementation isn't really going to be robust to "whatever the 
> > > default is", it's going to be tested against one or the other.
> > > So None isn't really a sensible return value - can't the base class 
> > > simply return the actual default?
> > ASTMatchFinder doesn't know the ASTContext, so it can't access the default. 
> > That's why I made it an optional.
> The fact that it's optional is a bit weird. Given that this is a temporary 
> API, I see two approaches: hold our nose because the ugliness shouldn't be 
> long-lived, or have the default be specified in two places with comments 
> saying "don't forget to update over here if you change this value" so we can 
> get rid of the `Optional<>` here. WDYT?
My preference is to keep the optional. Having multiple places to update makes 
it likely they'll get out of sync.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80623

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


[PATCH] D87702: [Frontend] Add pragma align natural and sort out pragma pack stack effect

2020-12-22 Thread Jason Liu via Phabricator via cfe-commits
jasonliu added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:505
+// AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
+uint32_t getRawEncoding(const AlignPackInfo &Info) const {
+  std::uint32_t Encoding{};

this getter do not need to take any parameters. You could just use `*this`.
Or, to make it consistent with the getFromRawEncoding, we could make this a 
static function as well and keep the parameter.



Comment at: clang/include/clang/Sema/Sema.h:506
+uint32_t getRawEncoding(const AlignPackInfo &Info) const {
+  std::uint32_t Encoding{};
+  if (Info.IsAIXStack())

Since this new structure have the same size as the uint32_t, have you consider 
using memcpy to burn the data directly into the uint32_t, and vice versa?



Comment at: clang/include/clang/Sema/Sema.h:570
+/// \brief True if it is a AIX #pragma align/pack stack.
+bool AIXStack;
+

It might be better to rename it XLStack, as this is the XL compiler behavior on 
AIX. Other compilers on AIX, like gcc, could have different behavior.



Comment at: clang/include/clang/Sema/Sema.h:637
   PragmaStack VtorDispStack;
-  // #pragma pack.
-  // Sentinel to represent when the stack is set to mac68k alignment.
-  static const unsigned kMac68kAlignmentSentinel = ~0U;
-  PragmaStack PackStack;
+  PragmaStack PackStack;
   // The current #pragma pack values and locations at each #include.

Xiangling_L wrote:
> jasonliu wrote:
> > We should consider renaming PackStack to AlignPackStack across Clang. Maybe 
> > even as a NFC first. As it is right now, clang already uses one stack to 
> > record those two informations from `Pragma align` and `Pragma pack`. Leave 
> > it as PackStack is too confusing, and people could actually ignore the 
> > pragma Align when developing with PackStack. 
> That's a good point. I will create a NFC accordingly.
Please post this NFC when you have time.



Comment at: clang/lib/AST/RecordLayoutBuilder.cpp:699-700
+IsMac68kAlign(false),
+IsNaturalAlign(!Context.getTargetInfo().getTriple().isOSAIX() ? true
+  : false),
+IsMsStruct(false), UnfilledBitsInLastUnit(0),





Comment at: clang/lib/AST/RecordLayoutBuilder.cpp:1322
   HandledFirstNonOverlappingEmptyField =
-  !Context.getTargetInfo().defaultsToAIXPowerAlignment();
+  !Context.getTargetInfo().defaultsToAIXPowerAlignment() || IsNaturalAlign;
 

Not sure if this would have a real effect, but reading this code concerns me a 
little bit:
We would set `HandledFirstNonOverlappingEmptyField` based on `IsNaturalAlign`, 
but for AIX, that bit might only get set at line 1343.
It would look like we have a read before write to the variable here. 



Comment at: clang/lib/Sema/SemaAttr.cpp:232
 Action = Sema::PSK_Push_Set;
-Alignment = 0;
+if (IsAIX)
+  ModeVal = AlignPackInfo::Natural;

XLPragmaPack is used to control pack and align stack semantic behavior.
Someone on AIX might want to turn off this compatible pack and align with XL 
behavior (to get the compatible behavior with clang on other platform for 
easier porting purpose), but they would still prefer to have the natural 
alignment to work correctly.
So it might not be desirable to query this option for this natural alignment 
behavior.



Comment at: clang/lib/Sema/SemaAttr.cpp:413
+  // FIXME: PackStack may contain both #pragma align and #pragma pack
+  // information, we should warn about both modified align mode and alignment.
   if (PrevPackState.CurrentValue != PackStack.CurrentValue) {

I don't think there is a preferable solution yet. Pointing out what could go 
wrong is good enough here.
Same for the FIXME below.


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

https://reviews.llvm.org/D87702

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


[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D93630#2468197 , @aaron.ballman 
wrote:

> However, taking a step back -- what attributes would need this functionality 
> (and couldn't be written on something within the expression statement)?

It is still good old `suppress`, it is very counter-intuitive when you put 
`suppress` and it causes some weird parse errors: https://godbolt.org/z/zzY64q


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

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


[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313360.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -483,3 +483,216 @@
   f();
   f();
 }
+
+template 
+bool neverInstantiatedTemplate() {
+  std::vector v;
+  if (v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+
+  if (v == std::vector())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of comparing to an empty object [readability-container-size-empty]
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  if (v.size() == 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() != 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() < 1)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() > 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() == 1)
+;
+  if (v.size() != 1)
+;
+  if (v.size() == 2)
+;
+  if (v.size() != 2)
+;
+
+  if (static_cast(v.size()))
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:25: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (static_cast(!v.empty())){{$}}
+  if (v.size() && false)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty() && false){{$}}
+  if (!v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+
+  TemplatedContainer templated_container;
+  if (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  if (templated_container != TemplatedContainer())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  while (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty()){{$}}
+
+  do {
+  }
+  while (templated_container.size());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty());
+
+  for (; templated_container.size();)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method shoul

[PATCH] D52050: [Driver] Fix architecture triplets and search paths for Linux x32

2020-12-22 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added a comment.

In D52050#2466874 , @glaubitz wrote:

> However, that's not the same as whether we're on an x86_64 system or on an 
> x32 system determines which GNU triplet to use and which include and library 
> search paths are our primary ones.

I don't see why it should?
When you target i386-linux-gnu, you can use objects from 
/usr/lib/gcc/i386-linux-gnu/*, /usr/lib/gcc/x86_64-linux-gnu/*/32, and 
/usr/lib/gcc/x86_64-linux-gnux32/*/32.
When you target x86_64-linux-gnu, you can use objects from 
/usr/lib/gcc/x86_64-linux-gnu/*, /usr/lib/gcc/x86_64-linux-gnux32/*/64, and 
/usr/lib/gcc/i386-linux-gnu/*/64.
When you target x86_64-linux-gnux32, you can use objects from 
/usr/lib/gcc/x86_64-linux-gnux32/*, /usr/lib/gcc/x86_64-linux-gnu/*/x32, and 
/usr/lib/gcc/i386-linux-gnu/*/x32.
All cases should be read to include all variants of the triples as well. None 
of that depends on the LLVM host architecture, does it? The LLVM host 
architecture makes it more or less likely that a GCC installation will be found 
in any of the listed directories, but not how it should be handled if found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D52050

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


[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313361.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -483,3 +483,219 @@
   f();
   f();
 }
+
+template 
+bool neverInstantiatedTemplate() {
+  std::vector v;
+  if (v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+
+  if (v == std::vector())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of comparing to an empty object [readability-container-size-empty]
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  if (v.size() == 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() != 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() < 1)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() > 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() == 1)
+;
+  if (v.size() != 1)
+;
+  if (v.size() == 2)
+;
+  if (v.size() != 2)
+;
+
+  if (static_cast(v.size()))
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:25: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (static_cast(!v.empty())){{$}}
+  if (v.size() && false)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty() && false){{$}}
+  if (!v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:8: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+
+  TemplatedContainer templated_container;
+  if (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  if (templated_container != TemplatedContainer())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!templated_container.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  while (templated_container.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty()){{$}}
+
+  do {
+  }
+  while (templated_container.size());
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used
+  // CHECK-MESSAGES: :44:8: note: method 'TemplatedContainer'::empty() defined here
+  // CHECK-FIXES: {{^  }}while (!templated_container.empty());
+
+  for (; templated_container.size();)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:10: warning: the 'empty' method shoul

[PATCH] D93630: [Attr] Apply GNU-style attributes to expression statements

2020-12-22 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 313362.
vsavchenko added a comment.

Maintain previous behavior unless preceeded by a statement attribute


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93630

Files:
  clang/lib/Parse/ParseStmt.cpp
  clang/test/Parser/stmt-attributes.c

Index: clang/test/Parser/stmt-attributes.c
===
--- /dev/null
+++ clang/test/Parser/stmt-attributes.c
@@ -0,0 +1,86 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void foo(int i) {
+
+  __attribute__((unknown_attribute));// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) {}  // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) if (0) {}   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) for (;;);   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) do {// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) continue; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  }
+  while (0)
+;
+  __attribute__((unknown_attribute)) while (0); // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((unknown_attribute)) switch (i) {  // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) case 0 :// expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+__attribute__((unknown_attribute)) default :   // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+ __attribute__((unknown_attribute)) break; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  }
+
+  __attribute__((unknown_attribute)) goto here; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+  __attribute__((unknown_attribute)) here : // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+__attribute__((unknown_attribute)) return; // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((noreturn)) {} // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) if (0) {}  // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) for (;;);  // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+  __attribute__((noreturn)) do {   // expected-error {{'noreturn' attribute cannot be applied to a statement}}
+__attribute__((unavailable)) continue; // expected-error {{'unavailable' attribute cannot be applied to a statement}}
+  }
+  while (0)
+;
+  __attribute__((unknown_attributqqq)) while (0); // expected-warning {{unknown attribute 'unknown_attributqqq' ignored}}
+  // TODO: remove 'qqq' part and enjoy 'empty loop body' warning here (DiagnoseEmptyLoopBody)
+
+  __attribute__((unknown_attribute)) while (0); // expected-warning {{unknown attribute 'unknown_attribute' ignored}}
+
+  __attribute__((unused)) switch (i) { // expected-error {{'unused' attribute cannot be applied to a statement}}
+  __attribute__((uuid)) case 0:// expected-warning {{unknown attribute 'uuid' ignored}}
+  __attribute__((visibility)) default: // expected-error {{'visibility' attribute cannot be applied to a statement}}
+__attribute__((carries_dependency)) break; // expected-error {{'carries_dependency' attribute cannot be applied to a statement}}
+  }
+
+  __attribute__((fastcall)) goto there; // expected-error {{'fastcall' attribute cannot be applied to a statement}}
+  __attribute__((noinline)) there : // expected-warning {{'noinline' attribute only applies to functions}}
+
+__attribute__((weakref)) return; // expected-error {{'weakref' attribute only applies to variables and functions}}
+
+  __attribute__((carries_dependency));// expected-error {{'carries_dependency' attribute cannot be applied to a statement}}
+  __attribute__((carries_dependency)) {}  // expected-error {{'carries_dependency' attribute cannot be applied to a statement}}
+  __attribute__((carries_dependency)) if (0) {}   // expected-error {{'carries_dependency' attribute cannot be appli

[PATCH] D91303: Simplify implementation of container-size-empty

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:56
-   hasEitherOperand(ignoringImpCasts(
-   anyOf(integerLiteral(equals(1)),
- integerLiteral(equals(0))

aaron.ballman wrote:
> It looks like the changes drop the requirement that either operand is 0 or 1 
> -- is that an oversight or can you explain why that's correct?
Sorry, that was an old/intermediate version of the patch.



Comment at: 
clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp:101
-  ignoringImpCasts(stringLiteral(hasSize(0))),
-  ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
-  ignoringImplicit(DefaultConstructor),

aaron.ballman wrote:
> We seem to lose this case entirely?
In `IgnoreUnlessSpelledInSource` mode, 
`ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor)))` simplifies to 
`cxxConstructExpr(isDefaultConstruction())`, which is there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91303

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


[PATCH] D91303: Simplify implementation of container-size-empty

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313370.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91303

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -695,7 +695,4 @@
 
 struct StructWithLazyNoexcept {
   void func() noexcept(L.size());
-// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: the 'empty' method should be used
-// CHECK-MESSAGES: :687:18: note: method 'Lazy'::empty() defined here
-// CHECK-FIXES: {{^  }}void func() noexcept(!L.empty());
 };
Index: clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
===
--- clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
+++ clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
@@ -33,6 +33,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace readability
Index: clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
@@ -86,6 +86,9 @@
   });
   return Result;
 }
+AST_MATCHER(CXXConstructExpr, isDefaultConstruction) {
+  return Node.getConstructor()->isDefaultConstructor();
+}
 } // namespace ast_matchers
 namespace tidy {
 namespace readability {
@@ -119,24 +122,16 @@
   const auto ValidContainer = qualType(
   anyOf(ValidContainerNonTemplateType, ValidContainerTemplateType));
 
-  const auto WrongUse = traverse(
-  TK_AsIs,
-  anyOf(
-  hasParent(binaryOperator(isComparisonOperator(),
-   hasEitherOperand(ignoringImpCasts(
-   anyOf(integerLiteral(equals(1)),
- integerLiteral(equals(0))
-.bind("SizeBinaryOp")),
-  hasParent(implicitCastExpr(
-  hasImplicitDestinationType(booleanType()),
-  anyOf(hasParent(
-unaryOperator(hasOperatorName("!")).bind("NegOnSize")),
-anything(,
-  usedInBooleanContext()));
+  const auto WrongUse =
+  anyOf(hasParent(binaryOperator(
+  isComparisonOperator(),
+  hasEitherOperand(anyOf(integerLiteral(equals(1)),
+ integerLiteral(equals(0)
+  .bind("SizeBinaryOp")),
+usedInBooleanContext());
 
   Finder->addMatcher(
-  cxxMemberCallExpr(unless(isInTemplateInstantiation()),
-on(expr(anyOf(hasType(ValidContainer),
+  cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
   hasType(pointsTo(ValidContainer)),
   hasType(references(ValidContainer
.bind("MemberCallObject")),
@@ -160,18 +155,9 @@
   .bind("SizeCallExpr"),
   this);
 
-  // Empty constructor matcher.
-  const auto DefaultConstructor = cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(isDefaultConstructor(;
   // Comparison to empty string or empty constructor.
   const auto WrongComparend = anyOf(
-  ignoringImpCasts(stringLiteral(hasSize(0))),
-  ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
-  ignoringImplicit(DefaultConstructor),
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isCopyConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isMoveConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
+  stringLiteral(hasSize(0)), cxxConstructExpr(isDefaultConstruction()),
   cxxUnresolvedConstructExpr(argumentCountIs(0)));
   // Match the object being compared.
   const auto STLArg =
@@ -182,7 +168,6 @@
 expr(hasType(ValidContainer)).bind("STLObject"));
   Finder->addMatcher(
   cxxOperatorCallExpr(
-  unless(isInTemplateInstantiation()),
   hasAnyOve

[PATCH] D93586: [InstCombine] use poison as placeholder for undemanded elems

2020-12-22 Thread Sanjay Patel via Phabricator via cfe-commits
spatel added a comment.

In D93586#2467248 , @aqjune wrote:

>> There are 792 files in llvm/test, most of which are in test/Transform (119) 
>> and test/CodeGen(655).
>> The transition will be swiftly done (if there's no other issue hopefully) by 
>> the next weekend.
>
> Thinking about these again, do we need to make a poison copy for 
> test/CodeGen? I don't think so, since the backend won't be changed anyway.

It would be good to update those for consistency; the codegen tests are 
supposed to be representative of what comes out of the IR optimizer. IIUC, we 
could do the substitution on those files already, and it would not change 
anything. But let's sort out the IR changes first?

In D93586#2466284 , @aqjune wrote:

> My concern is that some tests aren't using `utils/update_test_checks.py`, and 
> this makes things complicated. :(
> Simply replacing `insertelement undef` at `CHECK:` isn't enough (ex: 
> Transforms/SLPVectorizer/X86/alternate-cast.ll).

Yes, tests that don't have scripted CHECK lines require more work to 
understand. That SLP test file is scripted though. Is there another problem 
with that one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93586

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


[PATCH] D93490: [clang-format] PR48539 ReflowComments breaks Qt translation comments

2020-12-22 Thread JVApen via Phabricator via cfe-commits
JVApen added a comment.

In D93490#2467733 , @MyDeveloperDay 
wrote:

> remove // = and // ~ cases

Wouldn't it make sense to explicitly document that `//=` and `//~` are not put 
in here as reflowing them results in wrong results?


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

https://reviews.llvm.org/D93490

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


[PATCH] D91944: OpenMP 5.0 metadirective

2020-12-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

As discussed in the OpenMP in LLVM call on December 9th, we should go ahead 
with this patch and add support for the missing features, e.g., dependent 
selectors, afterwards. LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91944

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


[PATCH] D91944: OpenMP 5.0 metadirective

2020-12-22 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

(Please make sure all clang and clang-tidy tests pass properly so we can merge 
the patch)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91944

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


[PATCH] D91944: OpenMP 5.0 metadirective

2020-12-22 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Sema/TreeTransform.h:8383-8388
+  DeclarationNameInfo DirName;
+  getDerived().getSema().StartOpenMPDSABlock(OMPD_metadirective, DirName,
+ nullptr, D->getBeginLoc());
+  StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
+  getDerived().getSema().EndOpenMPDSABlock(Res.get());
+  return Res;

It would not work correctly, I would replace it with just error emission that 
instantiation is not supported yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91944

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


[PATCH] D52050: [Driver] Fix architecture triplets and search paths for Linux x32

2020-12-22 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

In D52050#2466874 , @glaubitz wrote:

> In D52050#2441164 , @glaubitz wrote:
>
>> In D52050#2441141 , @jrtc27 wrote:
>>
>>> What gets done currently for i386? That suffers potentially the same 
>>> problem given both /usr/lib/gcc/x86_64-linux-gnu/$V/32 and 
>>> /usr/lib/gcc/i386-linux-gnu/$V are possible locations for an i386 GCC 
>>> toolchain.
>>
>> Very good suggestion. I will look into that tomorrow. Thanks for the pointer!
>
> I have been wrapping my head around this for some time and I have run into 
> one problem trying to apply the suggested approach.
>
> The problem is that I don't know how to tell whether I'm on an x86_64 system 
> or an x32 system there is no ```case llvm::Triple::x32:``` which would be 
> needed here (we have it for x86).
>
> x32 takes the switch case for x86_64, so x32 and x86_64 targeting x32 are 
> identical.
>
> However, that's not the same as whether we're on an x86_64 system or on an 
> x32 system determines which GNU triplet to use and which include and library 
> search paths are our primary ones.

But `Triple.getEnvironment()` will give you `llvm::Triple::GNUX32` that you can 
check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D52050

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


[PATCH] D92024: [clang] Implement P0692R1 from C++20 (access checking on specializations and instantiations)

2020-12-22 Thread Alex Orlov via Phabricator via cfe-commits
aorlov added a comment.

One more ping!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92024

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


[PATCH] D91303: [clang-tidy] readability-container-size-empty: simplify implementation

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313381.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91303

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -477,9 +477,6 @@
 
 struct StructWithLazyNoexcept {
   void func() noexcept(L.size());
-// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: the 'empty' method should be used
-// CHECK-MESSAGES: :101:18: note: method 'Lazy'::empty() defined here
-// CHECK-FIXES: {{^  }}void func() noexcept(!L.empty());
 };
 
 #define CHECKSIZE(x) if (x.size()) {}
Index: clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
===
--- clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
+++ clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.h
@@ -33,6 +33,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 };
 
 } // namespace readability
Index: clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
@@ -86,6 +86,9 @@
   });
   return Result;
 }
+AST_MATCHER(CXXConstructExpr, isDefaultConstruction) {
+  return Node.getConstructor()->isDefaultConstructor();
+}
 } // namespace ast_matchers
 namespace tidy {
 namespace readability {
@@ -119,24 +122,16 @@
   const auto ValidContainer = qualType(
   anyOf(ValidContainerNonTemplateType, ValidContainerTemplateType));
 
-  const auto WrongUse = traverse(
-  TK_AsIs,
-  anyOf(
-  hasParent(binaryOperator(isComparisonOperator(),
-   hasEitherOperand(ignoringImpCasts(
-   anyOf(integerLiteral(equals(1)),
- integerLiteral(equals(0))
-.bind("SizeBinaryOp")),
-  hasParent(implicitCastExpr(
-  hasImplicitDestinationType(booleanType()),
-  anyOf(hasParent(
-unaryOperator(hasOperatorName("!")).bind("NegOnSize")),
-anything(,
-  usedInBooleanContext()));
+  const auto WrongUse =
+  anyOf(hasParent(binaryOperator(
+  isComparisonOperator(),
+  hasEitherOperand(anyOf(integerLiteral(equals(1)),
+ integerLiteral(equals(0)
+  .bind("SizeBinaryOp")),
+usedInBooleanContext());
 
   Finder->addMatcher(
-  cxxMemberCallExpr(unless(isInTemplateInstantiation()),
-on(expr(anyOf(hasType(ValidContainer),
+  cxxMemberCallExpr(on(expr(anyOf(hasType(ValidContainer),
   hasType(pointsTo(ValidContainer)),
   hasType(references(ValidContainer
.bind("MemberCallObject")),
@@ -160,18 +155,9 @@
   .bind("SizeCallExpr"),
   this);
 
-  // Empty constructor matcher.
-  const auto DefaultConstructor = cxxConstructExpr(
-  hasDeclaration(cxxConstructorDecl(isDefaultConstructor(;
   // Comparison to empty string or empty constructor.
   const auto WrongComparend = anyOf(
-  ignoringImpCasts(stringLiteral(hasSize(0))),
-  ignoringImpCasts(cxxBindTemporaryExpr(has(DefaultConstructor))),
-  ignoringImplicit(DefaultConstructor),
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isCopyConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
-  cxxConstructExpr(hasDeclaration(cxxConstructorDecl(isMoveConstructor())),
-   has(expr(ignoringImpCasts(DefaultConstructor,
+  stringLiteral(hasSize(0)), cxxConstructExpr(isDefaultConstruction()),
   cxxUnresolvedConstructExpr(argumentCountIs(0)));
   // Match the object being compared.
   const auto STLArg =
@@ -182,7 +168,6 @@
 expr(hasType(ValidContainer)).bind("STLObject"));
   Finder->addMatcher(
   cxxOperatorCallExpr(
-  unless(isInTempl

[PATCH] D80623: WIP: Add an API to simplify setting TraversalKind in clang-tidy matchers

2020-12-22 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchFinder.h:118
+/// behavior of clang-tidy.
+virtual llvm::Optional
+getCheckTraversalKind() const;

steveire wrote:
> aaron.ballman wrote:
> > steveire wrote:
> > > sammccall wrote:
> > > > I don't really get why this would be optional.
> > > > A check's implementation isn't really going to be robust to "whatever 
> > > > the default is", it's going to be tested against one or the other.
> > > > So None isn't really a sensible return value - can't the base class 
> > > > simply return the actual default?
> > > ASTMatchFinder doesn't know the ASTContext, so it can't access the 
> > > default. That's why I made it an optional.
> > The fact that it's optional is a bit weird. Given that this is a temporary 
> > API, I see two approaches: hold our nose because the ugliness shouldn't be 
> > long-lived, or have the default be specified in two places with comments 
> > saying "don't forget to update over here if you change this value" so we 
> > can get rid of the `Optional<>` here. WDYT?
> My preference is to keep the optional. Having multiple places to update makes 
> it likely they'll get out of sync.
Then I think it's fine to leave it as `Optional<>` given that it's a temporary 
API for easing the transition. @sammccall, are you okay with that?

In terms of eventually removing this API, what's your plan? I noticed we can't 
do something nice like slapping a `[[deprecated]]` attribute on the declaration 
and have overriders get a notification that the method they're overriding is 
deprecated. Will we just pull the API entirely and force users to react to the 
code breakage?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80623

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


[PATCH] D91302: Handle template instantiations better in clang-tidy check

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313385.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91302

Files:
  clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-container-size-empty.cpp
@@ -96,6 +96,11 @@
   bool empty() const { return *this == Container4(); }
 };
 
+struct Lazy {
+  constexpr unsigned size() const { return 0; }
+  constexpr bool empty() const { return true; }
+};
+
 std::string s_func() {
   return std::string();
 }
@@ -440,6 +445,43 @@
   // CHECK-FIXES: {{^  }}return !derived.empty();
 }
 
+class ConstructWithBoolField {
+  bool B;
+public:
+  ConstructWithBoolField(const std::vector &C) : B(C.size()) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:57: warning: the 'empty' method should be used
+// CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+// CHECK-FIXES: {{^  }}ConstructWithBoolField(const std::vector &C) : B(!C.empty()) {}
+};
+
+struct StructWithNSDMI {
+  std::vector C;
+  bool B = C.size();
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: the 'empty' method should be used
+// CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+// CHECK-FIXES: {{^  }}bool B = !C.empty();
+};
+
+int func(const std::vector &C) {
+  return C.size() ? 0 : 1;
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: the 'empty' method should be used
+// CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+// CHECK-FIXES: {{^  }}return !C.empty() ? 0 : 1;
+}
+
+constexpr Lazy L;
+static_assert(!L.size(), "");
+// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: the 'empty' method should be used
+// CHECK-MESSAGES: :101:18: note: method 'Lazy'::empty() defined here
+// CHECK-FIXES: {{^}}static_assert(L.empty(), "");
+
+struct StructWithLazyNoexcept {
+  void func() noexcept(L.size());
+// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: the 'empty' method should be used
+// CHECK-MESSAGES: :101:18: note: method 'Lazy'::empty() defined here
+// CHECK-FIXES: {{^  }}void func() noexcept(!L.empty());
+};
+
 #define CHECKSIZE(x) if (x.size()) {}
 // CHECK-FIXES: #define CHECKSIZE(x) if (x.size()) {}
 
@@ -483,3 +525,177 @@
   f();
   f();
 }
+
+template 
+bool neverInstantiatedTemplate() {
+  std::vector v;
+  if (v.size())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+
+  if (v == std::vector())
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of comparing to an empty object [readability-container-size-empty]
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  // CHECK-FIXES-NEXT: ;
+  if (v.size() == 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() != 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() < 1)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (v.empty()){{$}}
+  if (v.size() > 0)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (!v.empty()){{$}}
+  if (v.size() == 1)
+;
+  if (v.size() != 1)
+;
+  if (v.size() == 2)
+;
+  if (v.size() != 2)
+;
+
+  if (static_cast(v.size()))
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:25: warning: the 'empty' method should be used to check for emptiness instead of 'size' [readability-container-size-empty]
+  // CHECK-MESSAGES: :9:8: note: method 'vector'::empty() defined here
+  // CHECK-FIXES: {{^  }}if (static_cast(!v.empty())){{$}}
+  if (v.size() && false)
+;
+  // CHECK-MESSAGES: :[[@LINE-2]]:7: warning

[PATCH] D80623: WIP: Add an API to simplify setting TraversalKind in clang-tidy matchers

2020-12-22 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 313386.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80623

Files:
  clang/include/clang/ASTMatchers/ASTMatchFinder.h
  clang/lib/ASTMatchers/ASTMatchFinder.cpp


Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -990,6 +990,7 @@
 Callback(Callback) {}
 
 void visitMatch(const BoundNodes& BoundNodesView) override {
+  TraversalKindScope RAII(*Context, Callback->getCheckTraversalKind());
   Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
 }
 
@@ -1285,7 +1286,10 @@
 
 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1297,7 +1301,10 @@
 
 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1386,5 +1393,10 @@
 
 StringRef MatchFinder::MatchCallback::getID() const { return ""; }
 
+llvm::Optional
+MatchFinder::MatchCallback::getCheckTraversalKind() const {
+  return llvm::None;
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/ASTMatchers/ASTMatchFinder.h
===
--- clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -110,6 +110,12 @@
 /// This id is used, for example, for the profiling output.
 /// It defaults to "".
 virtual StringRef getID() const;
+
+/// TraversalKind to use while matching and processing
+/// the result nodes. This API is temporary to facilitate
+/// third parties porting existing code to the default
+/// behavior of clang-tidy.
+virtual llvm::Optional getCheckTraversalKind() const;
   };
 
   /// Called when parsing is finished. Intended for testing only.


Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -990,6 +990,7 @@
 Callback(Callback) {}
 
 void visitMatch(const BoundNodes& BoundNodesView) override {
+  TraversalKindScope RAII(*Context, Callback->getCheckTraversalKind());
   Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
 }
 
@@ -1285,7 +1286,10 @@
 
 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1297,7 +1301,10 @@
 
 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
  MatchCallback *Action) {
-  Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
+  if (auto TK = Action->getCheckTraversalKind())
+Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
+  else
+Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
   Matchers.AllCallbacks.insert(Action);
 }
 
@@ -1386,5 +1393,10 @@
 
 StringRef MatchFinder::MatchCallback::getID() const { return ""; }
 
+llvm::Optional
+MatchFinder::MatchCallback::getCheckTraversalKind() const {
+  return llvm::None;
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: clang/include/clang/ASTMatchers/ASTMatchFinder.h
===
--- clang/include/clang/ASTMatchers/ASTMatchFinder.h
+++ clang/include/clang/ASTMatchers/ASTMatchFinder.h
@@ -110,6 +110,12 @@
 /// This id is used, for example, for the profiling output.
 /// It defaults to "".
 virtual StringRef getID() const;
+
+/// TraversalKind to use while matching and processing
+/// the result nodes. This API is temporary to facilitate
+/// third parties porting existing code to the default
+/// behavior of clang-tidy.
+virtual llvm::Optional getCheckTraversalKind() const;
   };
 
   /// Called when parsing is finished. 

[clang] 85d4a4b - Revert "Fix memory leak complicated non-type template arguments."

2020-12-22 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2020-12-22T10:18:07-08:00
New Revision: 85d4a4bcc717a31ff40c4bd979dd6d78beb84b43

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

LOG: Revert "Fix memory leak complicated non-type template arguments."

This reverts commit ed13d8c66781b50ff007cb089c5905f9bb9e8af2.

This is part of 5 commits being reverted due to https://crbug.com/1161059. See 
bug for repro.

Added: 


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

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index a9bfdb4d5fa5..0c5d82b3e9aa 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2818,8 +2818,8 @@ class ASTContext : public RefCountedBase {
   /// for destruction.
   template  void addDestruction(T *Ptr) const {
 if (!std::is_trivially_destructible::value) {
-  auto DestroyPtr = [](void *V) { ((T*)V)->~T(); };
-  AddDeallocation(DestroyPtr, (void*)Ptr);
+  auto DestroyPtr = [](void *V) { static_cast(V)->~T(); };
+  AddDeallocation(DestroyPtr, Ptr);
 }
   }
 

diff  --git a/clang/lib/AST/TemplateBase.cpp b/clang/lib/AST/TemplateBase.cpp
index a746db315d85..0029c90a0ab6 100644
--- a/clang/lib/AST/TemplateBase.cpp
+++ b/clang/lib/AST/TemplateBase.cpp
@@ -137,7 +137,6 @@ TemplateArgument::TemplateArgument(const ASTContext &Ctx, 
QualType Type,
   else {
 Value.Kind = UncommonValue;
 Value.Value = new (Ctx) APValue(V);
-Ctx.addDestruction(Value.Value);
 Value.Type = Type.getAsOpaquePtr();
   }
 }



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


[clang] ab7a60e - Revert "Fix MSVC "not all control paths return a value" warnings. NFCI."

2020-12-22 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2020-12-22T10:18:07-08:00
New Revision: ab7a60eb4100ab197665b86f682dad0e787a4fed

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

LOG: Revert "Fix MSVC "not all control paths return a value" warnings. NFCI."

This reverts commit 7e84aa1b81e72d44bcc58ffe1731bfc7abb73ce0.

This is part of 5 commits being reverted due to https://crbug.com/1161059. See 
bug for repro.

Added: 


Modified: 
clang/lib/Sema/SemaTemplate.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 9d31a8701241..74a31c0a1b65 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -7637,7 +7637,6 @@ static Expr 
*BuildExpressionFromNonTypeTemplateArgumentValue(
 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
 return ConstantExpr::Create(S.Context, OVE, Val);
   }
-  llvm_unreachable("Unhandled APValue::ValueKind enum");
 }
 
 ExprResult
@@ -7667,7 +7666,6 @@ Sema::BuildExpressionFromNonTypeTemplateArgument(const 
TemplateArgument &Arg,
 return BuildExpressionFromNonTypeTemplateArgumentValue(
 *this, Arg.getUncommonValueType(), Arg.getAsUncommonValue(), Loc);
   }
-  llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
 }
 
 /// Match two template parameters within template parameter lists.



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


  1   2   >