[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-21 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
Herald added a subscriber: cfe-commits.

This fixes formatting namespaces with preceding 'inline' and 'export' (Modules 
TS) specifiers.

This change fixes namespaces not being identified as such with preceding 
'inline' or 'export' specifiers.

Motivation: I was experimenting with the Modules TS (-fmodules-ts) and found it 
would be useful if clang-format would correctly format 'export namespace'. 
While making the changes, I noticed that similar issues still exist with 
'inline namespace', and addressed them as well.


Repository:
  rC Clang

https://reviews.llvm.org/D51036

Files:
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -200,6 +200,24 @@
"inti;\n"
"}",
getGoogleStyle()));
+  EXPECT_EQ("inline namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("inline namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("export namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("export namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
 "\n"
 "int i;\n"
@@ -1573,6 +1591,11 @@
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("export namespace X {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("using namespace some_namespace;\n"
"class A {};\n"
"void f() { f(); }",
@@ -7556,6 +7579,9 @@
   verifyFormat("inline namespace Foo\n"
"{};",
Style);
+  verifyFormat("export namespace Foo\n"
+   "{};",
+   Style);
   verifyFormat("namespace Foo\n"
"{\n"
"void Bar();\n"
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -1063,6 +1063,13 @@
   parseJavaScriptEs6ImportExport();
   return;
 }
+if (Style.isCpp()) {
+  nextToken();
+  if (FormatTok->Tok.is(tok::kw_namespace)) {
+parseNamespace();
+return;
+  }
+}
 break;
   case tok::identifier:
 if (FormatTok->is(TT_ForEachMacro)) {
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -529,7 +529,10 @@
 Tok->SpacesRequiredBefore = 0;
 Tok->CanBreakBefore = true;
 return 1;
-  } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
+  } else if (Limit != 0 &&
+ !(Line.startsWith(tok::kw_namespace) ||
+   Line.startsWith(tok::kw_inline, tok::kw_namespace) ||
+   Line.startsWith(tok::kw_export, tok::kw_namespace)) &&
  !startsExternCBlock(Line)) {
 // We don't merge short records.
 FormatToken *RecordTok = Line.First;
@@ -1154,7 +1157,9 @@
   // Remove empty lines after "{".
   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
   PreviousLine->Last->is(tok::l_brace) &&
-  PreviousLine->First->isNot(tok::kw_namespace) &&
+  !(PreviousLine->startsWith(tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_inline, tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_export, tok::kw_namespace)) &&
   !startsExternCBlock(*PreviousLine))
 Newlines = 1;
 
Index: lib/Format/NamespaceEndCommentsFixer.cpp
===
--- lib/Format/NamespaceEndCommentsFixer.cpp
+++ lib/Format/NamespaceEndCommentsFixer.cpp
@@ -125,8 +125,8 @@
 if (StartLineIndex > 0)
   NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
   }
-  // Detect "(inline)? namespace" in the beginning of a line.
-  if (NamespaceTok->is(tok::kw_inline))
+  // Detect "(inline|export)? namespace" in the beginning of a line.
+  if (NamespaceTok->is(tok::kw_inline) || NamespaceTok->is(tok::kw_export))
 NamespaceTok = NamespaceTok->getNextNonComment();
   if (!NamespaceTok || NamespaceTok->isNot(tok::kw_namespace))
 return nullptr;
Index: lib/Format/FormatToken.h
==

[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 161960.
melver marked 8 inline comments as done.
melver added a comment.

Many thanks for the suggestions!

PTAL.


Repository:
  rC Clang

https://reviews.llvm.org/D51036

Files:
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -200,6 +200,24 @@
"inti;\n"
"}",
getGoogleStyle()));
+  EXPECT_EQ("inline namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("inline namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("export namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("export namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
 "\n"
 "int i;\n"
@@ -1573,6 +1591,11 @@
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("export namespace X {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("using namespace some_namespace;\n"
"class A {};\n"
"void f() { f(); }",
@@ -7556,6 +7579,9 @@
   verifyFormat("inline namespace Foo\n"
"{};",
Style);
+  verifyFormat("export namespace Foo\n"
+   "{};",
+   Style);
   verifyFormat("namespace Foo\n"
"{\n"
"void Bar();\n"
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -989,13 +989,6 @@
   case tok::kw_namespace:
 parseNamespace();
 return;
-  case tok::kw_inline:
-nextToken();
-if (FormatTok->Tok.is(tok::kw_namespace)) {
-  parseNamespace();
-  return;
-}
-break;
   case tok::kw_public:
   case tok::kw_protected:
   case tok::kw_private:
@@ -1063,6 +1056,16 @@
   parseJavaScriptEs6ImportExport();
   return;
 }
+if (!Style.isCpp())
+  break;
+// Handle C++ "(inline|export) namespace".
+LLVM_FALLTHROUGH;
+  case tok::kw_inline:
+nextToken();
+if (FormatTok->Tok.is(tok::kw_namespace)) {
+  parseNamespace();
+  return;
+}
 break;
   case tok::identifier:
 if (FormatTok->is(TT_ForEachMacro)) {
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -529,7 +529,10 @@
 Tok->SpacesRequiredBefore = 0;
 Tok->CanBreakBefore = true;
 return 1;
-  } else if (Limit != 0 && !Line.startsWith(tok::kw_namespace) &&
+  } else if (Limit != 0 &&
+ !(Line.startsWith(tok::kw_namespace) ||
+   Line.startsWith(tok::kw_inline, tok::kw_namespace) ||
+   Line.startsWith(tok::kw_export, tok::kw_namespace)) &&
  !startsExternCBlock(Line)) {
 // We don't merge short records.
 FormatToken *RecordTok = Line.First;
@@ -1154,7 +1157,9 @@
   // Remove empty lines after "{".
   if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
   PreviousLine->Last->is(tok::l_brace) &&
-  PreviousLine->First->isNot(tok::kw_namespace) &&
+  !(PreviousLine->startsWith(tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_inline, tok::kw_namespace) ||
+PreviousLine->startsWith(tok::kw_export, tok::kw_namespace)) &&
   !startsExternCBlock(*PreviousLine))
 Newlines = 1;
 
Index: lib/Format/NamespaceEndCommentsFixer.cpp
===
--- lib/Format/NamespaceEndCommentsFixer.cpp
+++ lib/Format/NamespaceEndCommentsFixer.cpp
@@ -125,12 +125,7 @@
 if (StartLineIndex > 0)
   NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
   }
-  // Detect "(inline)? namespace" in the beginning of a line.
-  if (NamespaceTok->is(tok::kw_inline))
-NamespaceTok = NamespaceTok->getNextNonComment();
-  if (!NamespaceTok || NamespaceTok->isNot(tok::kw_namespace))
-return nullptr;
-  return NamespaceTok;
+  return NamespaceTok->getNamespaceToken();
 }
 
 NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(const Environment &Env,
Index: lib/Format/FormatToken.h
===

[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-27 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 162653.
melver marked 4 inline comments as done.
melver added a comment.

Many thanks! PTAL.


Repository:
  rC Clang

https://reviews.llvm.org/D51036

Files:
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/TokenAnnotator.h
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -200,6 +200,42 @@
"inti;\n"
"}",
getGoogleStyle()));
+  EXPECT_EQ("/* something */ namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("/* something */ namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("inline namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("inline namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("/* something */ inline namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("/* something */ inline namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
+  EXPECT_EQ("export namespace N {\n"
+"\n"
+"int i;\n"
+"}",
+format("export namespace N {\n"
+   "\n"
+   "inti;\n"
+   "}",
+   getGoogleStyle()));
   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
 "\n"
 "int i;\n"
@@ -1186,12 +1222,25 @@
"private:\n"
"  void f() {}\n"
"};");
+  verifyFormat("export class A {\n"
+   "public:\n"
+   "public: // comment\n"
+   "protected:\n"
+   "private:\n"
+   "  void f() {}\n"
+   "};");
   verifyGoogleFormat("class A {\n"
  " public:\n"
  " protected:\n"
  " private:\n"
  "  void f() {}\n"
  "};");
+  verifyGoogleFormat("export class A {\n"
+ " public:\n"
+ " protected:\n"
+ " private:\n"
+ "  void f() {}\n"
+ "};");
   verifyFormat("class A {\n"
"public slots:\n"
"  void f1() {}\n"
@@ -1563,16 +1612,36 @@
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("/* something */ namespace some_namespace {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("namespace {\n"
"class A {};\n"
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("/* something */ namespace {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("inline namespace X {\n"
"class A {};\n"
"void f() { f(); }\n"
"}",
LLVMWithNoNamespaceFix);
+  verifyFormat("/* something */ inline namespace X {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
+  verifyFormat("export namespace X {\n"
+   "class A {};\n"
+   "void f() { f(); }\n"
+   "}",
+   LLVMWithNoNamespaceFix);
   verifyFormat("using namespace some_namespace;\n"
"class A {};\n"
"void f() { f(); }",
@@ -7556,6 +7625,12 @@
   verifyFormat("inline namespace Foo\n"
"{};",
Style);
+  verifyFormat("/* something */ inline namespace Foo\n"
+   "{};",
+   Style);
+  verifyFormat("export namespace Foo\n"
+   "{};",
+   Style);
   verifyFormat("namespace Foo\n"
"{\n"
"void Bar();\n"
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -989,13 +989,6 @@
   case tok::kw_namespace:
 parseNamespace();
 return;
-  case tok::kw_inline:
-nextToken();
-if (FormatTok->Tok.is(tok::kw_namespace)) {
-  parseNamespace();
-  return;
-}
-break;
   case tok::kw_public:
   case tok::kw_protected:
   case tok::kw_pr

[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-08-27 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: lib/Format/Format.cpp:1312
   auto &Line = *AnnotatedLines[i];
   if (Line.startsWith(tok::kw_namespace) ||
+  Line.startsWith(tok::kw_inline, tok::kw_namespace) ||

owenpan wrote:
> sammccall wrote:
> > these 3 startswith checks appear 4 times now, you could pull out a helper 
> > function `startsWithNamespace` in FormatToken.h or something like that.
> > Up to you.
> I missed it. Good catch!
Added startsWithNamespace to TokenAnnotator.h.



Comment at: unittests/Format/FormatTest.cpp:7582
Style);
+  verifyFormat("export namespace Foo\n"
+   "{};",

sammccall wrote:
> you may want to add tests for other modules TS syntax (e.g. non-namespace 
> export decls).
> It seems this works well today, but without tests it could regress.
I've added a couple for 'export class' with access specifiers. Otherwise, any 
other additions should probably be in future non-namespace related patches.


Repository:
  rC Clang

https://reviews.llvm.org/D51036



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


[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-09-04 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Awaiting remaining reviewer acceptance.

FYI: I do not have commit commit access -- what is the procedure to commit once 
diff is accepted?

Many thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D51036



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


[PATCH] D51036: clang-format: Fix formatting C++ namespaces with preceding 'inline' or 'export' specifier

2018-09-05 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In https://reviews.llvm.org/D51036#1223254, @sammccall wrote:

> In https://reviews.llvm.org/D51036#1223230, @melver wrote:
>
> > Awaiting remaining reviewer acceptance.
> >
> > FYI: I do not have commit commit access -- what is the procedure to commit 
> > once diff is accepted?
> >
> > Many thanks!
>
>
> Anyone with commit access can land it for you - I'm happy to do this.
>  @owenpan any concerns?


Great, many thanks for committing.


Repository:
  rL LLVM

https://reviews.llvm.org/D51036



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 182974.
melver marked 2 inline comments as done.
melver added a comment.

- Use SmallVector in CodeGenOptions.h


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

https://reviews.llvm.org/D56935

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,9 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  for (auto &&V : Args.getAllArgValues(OPT_fpass_plugin_EQ))
+Opts.PassPlugins.push_back(std::move(V));
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+A->claim();
+  }
+
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
   if (!StatsFile.empty())
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -37,6 +37,7 @@
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
+#include "llvm/Passes/PassPlugin.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -962,6 +963,16 @@
 
   PassBuilder PB(TM.get(), PGOOpt);
 
+  // Attempt to load pass plugins and register their callbacks with PB.
+  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
+if (auto PassPlugin = PassPlugin::Load(PluginFN)) {
+  PassPlugin->registerPassBuilderCallbacks(PB);
+} else {
+  errs() << "Failed to load passes from '" << PluginFN
+ << "'. Request ignored.\n";
+}
+  }
+
   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1613,6 +1613,9 @@
 def fno_rwpi : Flag<["-"], "fno-rwpi">, Group;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group, 
Flags<[DriverOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
+def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
+  Group, Flags<[CC1Option]>, MetaVarName<"">,
+  HelpText<"Load pass plugin from a dynamic shared object file (only with new 
pass manager).">;
 def fpreserve_as_comments : Flag<["-"], "fpreserve-as-comments">, 
Group;
 def fno_preserve_as_comments : Flag<["-"], "fno-preserve-as-comments">, 
Group, Flags<[CC1Option]>,
   HelpText<"Do not preserve comments in inline assembly">;
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -17,6 +17,7 @@
 #include "clang/Basic/DebugInfoOptions.h"
 #include "clang/Basic/Sanitizers.h"
 #include "clang/Basic/XRayInstr.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Target/TargetOptions.h"
@@ -288,6 +289,9 @@
 
   std::vector DefaultFunctionAttrs;
 
+  /// List of dynamic shared object files to be loaded as pass plugins.
+  SmallVector PassPlugins;
+
 public:
   // Define accessors/mutators for code generation options of enumeration type.
 #define CODEGENOPT(Name, Bits, Default)


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,9 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  for (auto &&V : Args.getAllArgValues(OPT_fpass_plugin_EQ))
+Opts.PassPlugins.push_back(std::move(V));
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const

[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-22 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Thanks!

In D56935#1366756 , @philip.pfaffe 
wrote:

> This generally looks sane. What will happen on windows though? Will it 
> silently fail?


AFAIK PassPlugin::Load uses sys::DynamicLibrary::getPermanentLibrary, which 
uses DynamicLibrary::HandleSet::AddLibrary which works for Windows as well. 
(The story is similar to legacy -fplugin=).




Comment at: clang/include/clang/Basic/CodeGenOptions.h:292
+  /// List of dynamic shared object files to be loaded as pass plugins.
+  std::vector PassPlugins;
+

philip.pfaffe wrote:
> This  should be SmallVector.
Not sure if this is better. getAllArgValues returns a vector, which is 
why I think the above members are also vector. And std::vector cannot 
be assigned to SmallVector, which required an extra line in 
CompilerInvocation.cpp.

Let me know what you think.


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

https://reviews.llvm.org/D56935



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-22 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

>> This generally looks sane. What will happen on windows though? Will it 
>> silently fa
> 
> AFAIK PassPlugin::Load uses sys::DynamicLibrary::getPermanentLibrary, which 
> uses DynamicLibrary::HandleSet::AddLibrary which works for Windows as well. 
> (The story is similar to legacy -fplugin=).

s/AddLibrary/DLOpen/ -- DLOpen and others in DynamicLibrary:: are wrappers 
around platform-specific code. On Windows the implementation is in: 
llvm/lib/Support/Windows/DynamicLibrary.inc


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

https://reviews.llvm.org/D56935



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-23 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 183140.
melver added a comment.

- Revert use of SmallVector


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

https://reviews.llvm.org/D56935

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,8 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+A->claim();
+  }
+
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
   if (!StatsFile.empty())
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -37,6 +37,7 @@
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
+#include "llvm/Passes/PassPlugin.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -962,6 +963,16 @@
 
   PassBuilder PB(TM.get(), PGOOpt);
 
+  // Attempt to load pass plugins and register their callbacks with PB.
+  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
+if (auto PassPlugin = PassPlugin::Load(PluginFN)) {
+  PassPlugin->registerPassBuilderCallbacks(PB);
+} else {
+  errs() << "Failed to load passes from '" << PluginFN
+ << "'. Request ignored.\n";
+}
+  }
+
   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1613,6 +1613,9 @@
 def fno_rwpi : Flag<["-"], "fno-rwpi">, Group;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group, 
Flags<[DriverOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
+def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
+  Group, Flags<[CC1Option]>, MetaVarName<"">,
+  HelpText<"Load pass plugin from a dynamic shared object file (only with new 
pass manager).">;
 def fpreserve_as_comments : Flag<["-"], "fpreserve-as-comments">, 
Group;
 def fno_preserve_as_comments : Flag<["-"], "fno-preserve-as-comments">, 
Group, Flags<[CC1Option]>,
   HelpText<"Do not preserve comments in inline assembly">;
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -288,6 +288,9 @@
 
   std::vector DefaultFunctionAttrs;
 
+  /// List of dynamic shared object files to be loaded as pass plugins.
+  std::vector PassPlugins;
+
 public:
   // Define accessors/mutators for code generation options of enumeration type.
 #define CODEGENOPT(Name, Bits, Default)


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,8 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+A->claim();
+  }
+
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
   if (!StatsFile.empty())
Index: clang/lib/CodeGen/BackendUtil.cpp
==

[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-23 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Thanks!

In D56935#1367545 , @philip.pfaffe 
wrote:

> I'm not sure what the current state of plugins on windows is. They were 
> broken and disabled last time I worked on this, but that might've changed in 
> the meantime! Worth checking.


Right, though I feel this is related to DynamicLibrary, and orthogonal to this 
patch. I don't have access to a Windows machine right now, but I can try to 
check if you feel it's urgent to land this. What do you think?


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

https://reviews.llvm.org/D56935



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-26 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 183715.
melver added a comment.

- Improve error reporting. While testing on Windows, noticed that Clang wants 
the error to be checked otherwise crashed quite verbosely.


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

https://reviews.llvm.org/D56935

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,8 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+A->claim();
+  }
+
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
   if (!StatsFile.empty())
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -37,6 +37,7 @@
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
+#include "llvm/Passes/PassPlugin.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -962,6 +963,17 @@
 
   PassBuilder PB(TM.get(), PGOOpt);
 
+  // Attempt to load pass plugins and register their callbacks with PB.
+  for (auto &PluginFN : CodeGenOpts.PassPlugins) {
+auto PassPlugin = PassPlugin::Load(PluginFN);
+if (PassPlugin) {
+  PassPlugin->registerPassBuilderCallbacks(PB);
+} else {
+  Diags.Report(diag::err_fe_unable_to_load_plugin)
+  << PluginFN << toString(PassPlugin.takeError());
+}
+  }
+
   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1613,6 +1613,9 @@
 def fno_rwpi : Flag<["-"], "fno-rwpi">, Group;
 def fplugin_EQ : Joined<["-"], "fplugin=">, Group, 
Flags<[DriverOption]>, MetaVarName<"">,
   HelpText<"Load the named plugin (dynamic shared object)">;
+def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
+  Group, Flags<[CC1Option]>, MetaVarName<"">,
+  HelpText<"Load pass plugin from a dynamic shared object file (only with new 
pass manager).">;
 def fpreserve_as_comments : Flag<["-"], "fpreserve-as-comments">, 
Group;
 def fno_preserve_as_comments : Flag<["-"], "fno-preserve-as-comments">, 
Group, Flags<[CC1Option]>,
   HelpText<"Do not preserve comments in inline assembly">;
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -288,6 +288,9 @@
 
   std::vector DefaultFunctionAttrs;
 
+  /// List of dynamic shared object files to be loaded as pass plugins.
+  std::vector PassPlugins;
+
 public:
   // Define accessors/mutators for code generation options of enumeration type.
 #define CODEGENOPT(Name, Bits, Default)


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1322,6 +1322,8 @@
 
   Opts.DefaultFunctionAttrs = Args.getAllArgValues(OPT_default_function_attr);
 
+  Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
+
   return Success;
 }
 
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5066,6 +5066,13 @@
 A->claim();
   }
 
+  // Forward -fpass-plugin=name.so to -cc1.
+  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
+CmdArgs.push_back(
+Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+A->claim();
+  }
+
   // Setup statistics file output.
   SmallString<128> StatsFile = getStatsFileName(Args, Output, 

[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-26 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D56935#1370861 , @philip.pfaffe 
wrote:

> It would be good to check, since the bots won't! Otherwise this looks good.


Thanks!

I attempted to test on Windows, but noticed that for a shared library CMake 
already reports "Loadable modules not supported on this platform", and couldn't 
create a real plugin. In any case, I attempted to load an arbitrary DLL to see 
if errors are reported correctly and subsequently improved that. If a library 
can't be loaded, it will not fail silently now.

If you're happy with this version, I would need you to land this for me (I do 
not have commit access). Many thanks!


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

https://reviews.llvm.org/D56935



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-01-30 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Gentle ping. Need someone to land this on my behalf, as I do not have commit 
access. Many thanks!


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

https://reviews.llvm.org/D56935



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


[PATCH] D56935: [NewPM] Add support for new-PM plugins to clang

2019-02-04 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D56935#1382156 , @philip.pfaffe 
wrote:

> Landed it for you in r352972. Thanks!


Great, thanks!


Repository:
  rC Clang

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

https://reviews.llvm.org/D56935



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


[PATCH] D80428: [clang] Optimize getFileIDLocal

2020-05-22 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Avoid bit operations to compute Offset by removing bitfields. On 64-bit 
architectures, SLocEntry's size is unchanged.

- Provide branch-prediction hints to compiler to generate better code.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80428

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80428: [clang] Optimize getFileIDLocal

2020-05-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 265717.
melver added a comment.

Extra unlikely hint.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80428

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
@@ -900,7 +900,7 @@
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
+if (LLVM_UNLIKELY(isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset))) 
{
   FileID Res = FileID::get(MiddleIndex);
 
   // If this isn't a macro expansion, remember it.  We have good locality
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,14 +885,14 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
 
 // If the offset of the midpoint is too large, chop the high side of the
 // range to the midpoint.
-if (MidOffset > SLocOffset) {
+if (LLVM_LIKELY(MidOffset > SLocOffset)) {
   GreaterIndex = MiddleIndex;
   continue;
 }
@@ -900,7 +900,7 @@
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
+if (LLVM_UNLIKELY(isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset))) {
   FileID Res = FileID::get(MiddleIndex);
 
   // If this isn't a macro expansion, remember it.  We have good locality
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80428: [clang] Optimize SourceManager::getFileIDLocal [WIP]

2020-05-22 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 265780.
melver retitled this revision from "[clang] Optimize getFileIDLocal [WIP]" to 
"[clang] Optimize SourceManager::getFileIDLocal [WIP]".
melver edited the summary of this revision.
melver added a comment.

Improve code-gen further -- another ~5%.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80428

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,7 +885,7 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
@@ -896,13 +896,15 @@
   GreaterIndex = MiddleIndex;
   continue;
 }
+// Otherwise, move the low-side up to the middle index. Used in next
+// iteration if !isOffsetInFileID() below.
+LessIndex = MiddleIndex;
 
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
-  FileID Res = FileID::get(MiddleIndex);
-
+FileID Res = FileID::get(MiddleIndex);
+if (LLVM_UNLIKELY(isOffsetInFileID(Res, SLocOffset))) {
   // If this isn't a macro expansion, remember it.  We have good locality
   // across FileID lookups.
   if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
@@ -910,9 +912,6 @@
   NumBinaryProbes += NumProbes;
   return Res;
 }
-
-// Otherwise, move the low-side up to the middle index.
-LessIndex = MiddleIndex;
   }
 }
 
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   ExpansionInfo Expansion;
@@ -465,7 +465,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const FileInfo &FI) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = false;
@@ -474,7 +473,6 @@
 }
 
 static SLocEntry get(unsigned Offset, const ExpansionInfo &Expansion) {
-  assert(!(Offset & (1u << 31)) && "Offset is too large");
   SLocEntry E;
   E.Offset = Offset;
   E.IsExpansion = true;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -885,7 +885,7 @@
 bool Invalid = false;
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
 unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset();
-if (Invalid)
+if (LLVM_UNLIKELY(Invalid))
   return FileID::get(0);
 
 ++NumProbes;
@@ -896,13 +896,15 @@
   GreaterIndex = MiddleIndex;
   continue;
 }
+// Otherwise, move the low-side up to the middle index. Used in next
+// iteration if !isOffsetInFileID() below.
+LessIndex = MiddleIndex;
 
 // If the middle index contains the value, succeed and return.
 // FIXME: This could be made faster by using a function that's aware of
 // being in the local area.
-if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) {
-  FileID Res = FileID::get(MiddleIndex);
-
+FileID Res = FileID::get(MiddleIndex);
+if (LLVM_UNLIKELY(isOffsetInFileID(Res, SLocOffset))) {
   // If this isn't a macro expansion, remember it.  We have good locality
   // across FileID lookups.
   if (!LocalSLocEntryTable[MiddleIndex].isExpansion())
@@ -910,9 +912,6 @@
   NumBinaryProbes += NumProbes;
   return Res;
 }
-
-// Otherwise, move the low-side up to the middle index.
-LessIndex = MiddleIndex;
   }
 }
 
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -439,8 +439,8 @@
   /// SourceManager keeps an array of these objects, and they are uniquely
   /// identified by the FileID datatype.
   class SLocEntry {
-unsigned Offset : 31;
-unsigned IsExpansion : 1;
+unsigned Offset;
+bool IsExpansion;
 union {
   FileInfo File;
   Expansio

[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-25 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 266048.
melver added a comment.
Herald added a project: Sanitizers.
Herald added a subscriber: Sanitizers.

Address failing tests:

- Set -triple for test.
- Some existing tests now pass under TSAN, and can be enabled.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-coverage-bounds.c
  clang/test/CodeGen/sanitize-coverage-thread.c
  clang/test/Driver/fsanitize-coverage.c
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp

Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
@@ -1,7 +1,6 @@
 // Tests trace pc guard coverage collection.
 //
 // REQUIRES: has_sancovcc,stable-runtime,x86_64-linux
-// XFAIL: tsan
 //
 // RUN: DIR=%t_workdir
 // RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard"
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
@@ -1,7 +1,5 @@
 // Tests -fsanitize-coverage=stack-depth
 //
-// XFAIL: tsan
-//
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=stack-depth %s -o %t
 // RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not Assertion{{.*}}failed
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=trace-pc-guard,stack-depth \
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
@@ -2,7 +2,7 @@
 
 // REQUIRES: has_sancovcc,stable-runtime
 // UNSUPPORTED: i386-darwin
-// XFAIL: ubsan,tsan
+// XFAIL: ubsan
 // XFAIL: android && asan
 
 // RUN: %clangxx -O0 %s -S -o - -emit-llvm -fsanitize-coverage=trace-pc,bb,no-prune 2>&1 | grep "call void @__sanitizer_cov_trace_pc" | count 3
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-bool-flag,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow -fsanitize-coverage=func,trace-pc %s

[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-25 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 266054.
melver added a comment.

-triple -> -target


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-coverage-bounds.c
  clang/test/CodeGen/sanitize-coverage-thread.c
  clang/test/Driver/fsanitize-coverage.c
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp

Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
@@ -1,7 +1,6 @@
 // Tests trace pc guard coverage collection.
 //
 // REQUIRES: has_sancovcc,stable-runtime,x86_64-linux
-// XFAIL: tsan
 //
 // RUN: DIR=%t_workdir
 // RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard"
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
@@ -1,7 +1,5 @@
 // Tests -fsanitize-coverage=stack-depth
 //
-// XFAIL: tsan
-//
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=stack-depth %s -o %t
 // RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not Assertion{{.*}}failed
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=trace-pc-guard,stack-depth \
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
@@ -2,7 +2,7 @@
 
 // REQUIRES: has_sancovcc,stable-runtime
 // UNSUPPORTED: i386-darwin
-// XFAIL: ubsan,tsan
+// XFAIL: ubsan
 // XFAIL: android && asan
 
 // RUN: %clangxx -O0 %s -S -o - -emit-llvm -fsanitize-coverage=trace-pc,bb,no-prune 2>&1 | grep "call void @__sanitizer_cov_trace_pc" | count 3
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-bool-flag,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread -fsanitize-coverage=func,trace-pc %s -

[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-25 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 266057.
melver added a comment.

Add missing -target to sanitize-coverage-bounds test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-coverage-bounds.c
  clang/test/CodeGen/sanitize-coverage-thread.c
  clang/test/Driver/fsanitize-coverage.c
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
  compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
  
compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp

Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_trace_pc_guard-init.cpp
@@ -1,7 +1,6 @@
 // Tests trace pc guard coverage collection.
 //
 // REQUIRES: has_sancovcc,stable-runtime,x86_64-linux
-// XFAIL: tsan
 //
 // RUN: DIR=%t_workdir
 // RUN: CLANG_ARGS="-O0 -fsanitize-coverage=trace-pc-guard"
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_stack_depth.cpp
@@ -1,7 +1,5 @@
 // Tests -fsanitize-coverage=stack-depth
 //
-// XFAIL: tsan
-//
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=stack-depth %s -o %t
 // RUN: %run %t 2>&1 | FileCheck %s --implicit-check-not Assertion{{.*}}failed
 // RUN: %clangxx -O0 -std=c++11 -fsanitize-coverage=trace-pc-guard,stack-depth \
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_no_prune.cpp
@@ -2,7 +2,7 @@
 
 // REQUIRES: has_sancovcc,stable-runtime
 // UNSUPPORTED: i386-darwin
-// XFAIL: ubsan,tsan
+// XFAIL: ubsan
 // XFAIL: android && asan
 
 // RUN: %clangxx -O0 %s -S -o - -emit-llvm -fsanitize-coverage=trace-pc,bb,no-prune 2>&1 | grep "call void @__sanitizer_cov_trace_pc" | count 3
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline_bool_flag.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-bool-flag,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
===
--- compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
+++ compiler-rt/test/sanitizer_common/TestCases/sanitizer_coverage_inline8bit_counter.cpp
@@ -5,7 +5,6 @@
 //
 // RUN: %clangxx -O0 %s -fsanitize-coverage=inline-8bit-counters,pc-table -o %t
 // RUN: %run %t 2>&1 | FileCheck %s
-// XFAIL: tsan
 
 #include 
 #include 
Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread -fs

[PATCH] D80428: [clang] Optimize SourceManager::getFileIDLocal [WIP]

2020-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver abandoned this revision.
melver added a comment.

More background: https://github.com/ClangBuiltLinux/linux/issues/1032

This approach likely doesn't yield too much benefit. Too much variability is 
observed when compiling Clang with either Clang or GCC.

Since Nick has a better proposal at the above link, let's abandon this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80428



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


[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D79628#2058404 , @vvereschaka wrote:

> the Clang sanitize-coverage.c test gets crashed on Windows platform for armv7 
> target:
>
> - FAIL: Clang::sanitize-coverage.c
>
>   ```
> - command stderr: Pass 'Run-time bounds checking' is not initialized.
>
>   Verify if there is a pass dependency cycle.
>
>   Required Passes:
>
>   Target Library Information ... ``` see more details here: 
> http://lab.llvm.org:8011/builders/llvm-clang-win-x-armv7l/builds/7561/steps/test-check-clang/logs/FAIL%3A%20Clang%3A%3Asanitize-coverage.c
>
>   The first failed build: 
> http://lab.llvm.org:8011/builders/llvm-clang-win-x-armv7l/builds/7561
>
>   Would you take care of it?


Thanks, I've been trying to understand this (similar failures on other armv7 
instances). What's different with LLVM on armv7? Does it use a differently 
configured pass manager? Given this only fails on armv7, to me this highlights 
an issue with the architecture.

What I can do is blacklist the test for armv7 and thumbv7 until those 
architectures get fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628



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


[PATCH] D80668: [Clang][Sanitizers] Expect test failure on {arm,thumb}v7

2020-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: vitalybuka.
Herald added subscribers: cfe-commits, danielkiss, kristof.beyls.
Herald added a project: clang.
melver added a comment.

Example of failing test:
http://lab.llvm.org:8011/builders/clang-cmake-armv7-full/builds/10689

So this definitely can't be -target, because we set that. So it seems that some 
version of LLVM compiled for armv7 is somehow broken?

Vitaly, I wasn't able to test this since I don't have access to any such 
platform right now. If the "XFAIL" looks sane, and there isn't a better option, 
the build bots should eventually be able to tell us if this is reasonable.

Thanks!


Versions of LLVM built on {arm,thumb}v7 appear to have differently
configured pass managers, which causes restrictions on which sanitizers
we may use.

As such, expect failure of the recently added "sanitize-coverage.c" test
on these architectures until we can investigate armv7's restrictions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D80668

Files:
  clang/test/CodeGen/sanitize-coverage.c


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,8 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,UBSAN
+//
+// XFAIL: armv7, thumbv7
 
 int x[10];
 


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,8 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,UBSAN
+//
+// XFAIL: armv7, thumbv7
 
 int x[10];
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80668: [Clang][Sanitizers] Expect test failure on {arm,thumb}v7

2020-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Example of failing test:
http://lab.llvm.org:8011/builders/clang-cmake-armv7-full/builds/10689

So this definitely can't be -target, because we set that. So it seems that some 
version of LLVM compiled for armv7 is somehow broken?

Vitaly, I wasn't able to test this since I don't have access to any such 
platform right now. If the "XFAIL" looks sane, and there isn't a better option, 
the build bots should eventually be able to tell us if this is reasonable.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80668



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


[PATCH] D80668: [Clang][Sanitizers] Expect test failure on {arm,thumb}v7

2020-05-28 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 266773.
melver added a comment.

Add link to bug.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80668

Files:
  clang/test/CodeGen/sanitize-coverage.c


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,9 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,UBSAN
+//
+// Host armv7 is currently unsupported: 
https://bugs.llvm.org/show_bug.cgi?id=46117
+// XFAIL: armv7, thumbv7
 
 int x[10];
 


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,9 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,UBSAN
+//
+// Host armv7 is currently unsupported: https://bugs.llvm.org/show_bug.cgi?id=46117
+// XFAIL: armv7, thumbv7
 
 int x[10];
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80668: [Clang][Sanitizers] Expect test failure on {arm,thumb}v7

2020-05-28 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG69935d86aed1: [Clang][Sanitizers] Expect test failure on 
{arm,thumb}v7 (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80668

Files:
  clang/test/CodeGen/sanitize-coverage.c


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,9 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck 
%s --check-prefixes=CHECK,UBSAN
+//
+// Host armv7 is currently unsupported: 
https://bugs.llvm.org/show_bug.cgi?id=46117
+// XFAIL: armv7, thumbv7
 
 int x[10];
 


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -4,6 +4,9 @@
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=memory -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,MSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=thread -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,TSAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=undefined  -fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s --check-prefixes=CHECK,UBSAN
+//
+// Host armv7 is currently unsupported: https://bugs.llvm.org/show_bug.cgi?id=46117
+// XFAIL: armv7, thumbv7
 
 int x[10];
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80197: [DebugInfo] Upgrade DISubrange to support Fortran dynamic arrays

2020-05-28 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp:1522
 
 static uint64_t rotateSign(int64_t I) {
   uint64_t U = I;

rotateSign() is no longer used in this file. If there are no plans to use it 
again, please remove it.
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80197



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


[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-28 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D79628#2060254 , @alanphipps wrote:

> clang/test/CodeGen/sanitize-coverage.c is also failing our downstream 
> embedded ARMv7 validations.


https://reviews.llvm.org/D80668 has been submitted. It would be good if someone 
with access to armv7 machines could verify if that works for now, since I can't 
test it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628



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


[PATCH] D80805: [KernelAddressSanitizer] Make globals constructors compatible with kernel

2020-06-05 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 268796.
melver added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Update IR test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80805

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -1838,6 +1837,12 @@
   }
 
   if (G->hasSection()) {
+// The kernel uses explicit sections for mostly special global variables
+// that we should not instrument. E.g. the kernel may rely on their layout
+// without redzones, or remove them at link time

[PATCH] D80805: [KernelAddressSanitizer] Make globals constructors compatible with kernel

2020-06-05 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG866ee2353f7d: [KernelAddressSanitizer] Make globals 
constructors compatible with kernel (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80805

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -1838,6 +1837,12 @@
   }
 
   if (G->hasSection()) {
+// The kernel uses explicit sections for mostly special global variables
+// that we should not instrument. E.g. the kernel may rely on their layout
+//

[PATCH] D81306: [ASan][Test] Fix globals test for Mach-O

2020-06-05 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added reviewers: nickdesaulniers, thakis.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Use a portable section name, as for the test's purpose any name will do.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81306

Files:
  clang/test/CodeGen/asan-globals.cpp


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -11,7 +11,7 @@
 int dyn_init_global = global;
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
-int __attribute__((section(".foo.bar"))) sectioned_global;
+int __attribute__ ((section("__DATA, __common"))) sectioned_global;
 
 void func() {
   static int static_var = 0;
@@ -41,7 +41,7 @@
 // CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], 
!"sectioned_global", i1 false, i1 false}
-// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 
42}
+// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 
51}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 
false, i1 false}
 // CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -11,7 +11,7 @@
 int dyn_init_global = global;
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
-int __attribute__((section(".foo.bar"))) sectioned_global;
+int __attribute__ ((section("__DATA, __common"))) sectioned_global;
 
 void func() {
   static int static_var = 0;
@@ -41,7 +41,7 @@
 // CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], !"sectioned_global", i1 false, i1 false}
-// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 42}
+// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 51}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 false, i1 false}
 // CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D80805: [KernelAddressSanitizer] Make globals constructors compatible with kernel

2020-06-05 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D80805#2077396 , @thakis wrote:

> Hi, this broke check-clang on mac: http://45.33.8.238/mac/14998/step_7.txt
>
> Please take a look, and if it takes a while to fix please revert while you 
> investigate.


Sent https://reviews.llvm.org/D81306


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80805



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


[PATCH] D81306: [ASan][Test] Fix globals test for Mach-O

2020-06-05 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2dd83a923046: [ASan][Test] Fix globals test for Mach-O 
(authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81306

Files:
  clang/test/CodeGen/asan-globals.cpp


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -11,7 +11,7 @@
 int dyn_init_global = global;
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
-int __attribute__((section(".foo.bar"))) sectioned_global;
+int __attribute__ ((section("__DATA, __common"))) sectioned_global;
 
 void func() {
   static int static_var = 0;
@@ -41,7 +41,7 @@
 // CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], 
!"sectioned_global", i1 false, i1 false}
-// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 
42}
+// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 
51}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 
false, i1 false}
 // CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -11,7 +11,7 @@
 int dyn_init_global = global;
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
-int __attribute__((section(".foo.bar"))) sectioned_global;
+int __attribute__ ((section("__DATA, __common"))) sectioned_global;
 
 void func() {
   static int static_var = 0;
@@ -41,7 +41,7 @@
 // CHECK: ![[ATTR_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], !"sectioned_global", i1 false, i1 false}
-// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 42}
+// CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 14, i32 51}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 false, i1 false}
 // CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-06-07 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added reviewers: nathanchance, glider, andreyknvl.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya.
Herald added a reviewer: aaron.ballman.
Herald added projects: clang, LLVM.

The kernel expects certain global arrays' size to remain a multiple of
the array type. In particular, for kernel modules some arrays of structs
shared with userspace are sanity-checked by modpost to have a size that
is a multiple of that type:

https://elixir.bootlin.com/linux/latest/source/scripts/mod/file2alias.c#L132

Since the AddressSanitizer takes a global and replaces it with a new one
that has the redzone appended to it, any information about the global as
well as the section size is increased. Therefore, to ensure we retain
the array-size-property required for globals, calculate the redzone size
to be a multiple of the original global's size.

To improve readability, the existing redzone size calculation is
refactored into its own function; no other functional change intended.

Report: https://github.com/ClangBuiltLinux/linux/issues/1045


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81346

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -796,9 +796,10 @@
   StringRef getGlobalMetadataSection() const;
   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
-  size_t MinRedzoneSizeForGlobal() const {
+  uint64_t getMinRedzoneSizeForGlobal() const {
 return RedzoneSizeForScale(Mapping.Scale);
   }
+  uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
   int GetAsanVersion(const Module &M) const;
 
   const GlobalsMetadata &GlobalsMD;
@@ -1807,7 +1808,7 @@
   //   - Need to poison all copies, not just the main thread's one.
   if (G->isThreadLocal()) return false;
   // For now, just ignore this Global if the alignment is large.
-  if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
+  if (G->getAlignment() > getMinRedzoneSizeForGlobal()) return false;
 
   // For non-COFF targets, only instrument globals known to be defined by this
   // TU.
@@ -2276,7 +2277,6 @@
   M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
 
   for (size_t i = 0; i < n; i++) {
-static const uint64_t kMaxGlobalRedzone = 1 << 18;
 GlobalVariable *G = GlobalsToChange[i];
 
 // FIXME: Metadata should be attched directly to the global directly instead
@@ -2290,16 +2290,8 @@
 /*AllowMerging*/ true, kAsanGenPrefix);
 
 Type *Ty = G->getValueType();
-uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
-uint64_t MinRZ = MinRedzoneSizeForGlobal();
-// MinRZ <= RZ <= kMaxGlobalRedzone
-// and trying to make RZ to be ~ 1/4 of SizeInBytes.
-uint64_t RZ = std::max(
-MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
-uint64_t RightRedzoneSize = RZ;
-// Round up to MinRZ
-if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
-assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
+const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
+const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
 
 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
@@ -2315,7 +2307,7 @@
"", G, G->getThreadLocalMode());
 NewGlobal->copyAttributesFrom(G);
 NewGlobal->setComdat(G->getComdat());
-NewGlobal->setAlignment(MaybeAlign(MinRZ));
+NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
 // Don't fold globals with redzones. ODR violation detector and redzone
 // poisoning implicitly creates a dependence on the global's address, so it
 // is no longer valid for it to be marked unnamed_addr.
@@ -2437,6 +2429,39 @@
   return true;
 }
 
+uint64_t
+ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
+  const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
+  // Limit redzone size when compiling the kernel.
+  const uint64_t MaxRZ = CompileKernel ? MinRZ * 2 : 1 << 18;
+
+  // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
+  uint64_t RZ =
+  std::max(MinRZ, std::min(MaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
+
+  // Round up to multiple of MinRZ.
+  if (SizeInBytes % MinRZ)
+RZ += MinRZ - (SizeInBytes % MinRZ);
+  assert((RZ + SizeInBytes) % MinRZ == 0);
+
+  if (CompileKernel && SizeInBytes && RZ % SizeInBytes) {
+// When compiling the Linux kernel, ensure that the size of global+redzone
+// has the same divisors as b

[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-06-07 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269078.
melver added a comment.

Add 0-size array to test to check redzone calculation does not divide by 0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81346

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -796,9 +796,10 @@
   StringRef getGlobalMetadataSection() const;
   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
-  size_t MinRedzoneSizeForGlobal() const {
+  uint64_t getMinRedzoneSizeForGlobal() const {
 return RedzoneSizeForScale(Mapping.Scale);
   }
+  uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
   int GetAsanVersion(const Module &M) const;
 
   const GlobalsMetadata &GlobalsMD;
@@ -1807,7 +1808,7 @@
   //   - Need to poison all copies, not just the main thread's one.
   if (G->isThreadLocal()) return false;
   // For now, just ignore this Global if the alignment is large.
-  if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
+  if (G->getAlignment() > getMinRedzoneSizeForGlobal()) return false;
 
   // For non-COFF targets, only instrument globals known to be defined by this
   // TU.
@@ -2276,7 +2277,6 @@
   M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
 
   for (size_t i = 0; i < n; i++) {
-static const uint64_t kMaxGlobalRedzone = 1 << 18;
 GlobalVariable *G = GlobalsToChange[i];
 
 // FIXME: Metadata should be attched directly to the global directly instead
@@ -2290,16 +2290,8 @@
 /*AllowMerging*/ true, kAsanGenPrefix);
 
 Type *Ty = G->getValueType();
-uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
-uint64_t MinRZ = MinRedzoneSizeForGlobal();
-// MinRZ <= RZ <= kMaxGlobalRedzone
-// and trying to make RZ to be ~ 1/4 of SizeInBytes.
-uint64_t RZ = std::max(
-MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
-uint64_t RightRedzoneSize = RZ;
-// Round up to MinRZ
-if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
-assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
+const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
+const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
 
 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
@@ -2315,7 +2307,7 @@
"", G, G->getThreadLocalMode());
 NewGlobal->copyAttributesFrom(G);
 NewGlobal->setComdat(G->getComdat());
-NewGlobal->setAlignment(MaybeAlign(MinRZ));
+NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
 // Don't fold globals with redzones. ODR violation detector and redzone
 // poisoning implicitly creates a dependence on the global's address, so it
 // is no longer valid for it to be marked unnamed_addr.
@@ -2437,6 +2429,39 @@
   return true;
 }
 
+uint64_t
+ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
+  const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
+  // Limit redzone size when compiling the kernel.
+  const uint64_t MaxRZ = CompileKernel ? MinRZ * 2 : 1 << 18;
+
+  // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
+  uint64_t RZ =
+  std::max(MinRZ, std::min(MaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
+
+  // Round up to multiple of MinRZ.
+  if (SizeInBytes % MinRZ)
+RZ += MinRZ - (SizeInBytes % MinRZ);
+  assert((RZ + SizeInBytes) % MinRZ == 0);
+
+  if (CompileKernel && SizeInBytes && RZ % SizeInBytes) {
+// When compiling the Linux kernel, ensure that the size of global+redzone
+// has the same divisors as before. For certain arrays, the kernel expects
+// that the global's size remains a multiple of the type's size.
+//
+// For example, in kernel modules certain arrays of structs shared with
+// userspace are checked to be a multiple of sizeof(shared struct). These
+// checks happen on the final binary.
+//
+// We can ensure the checks do not fail by ensuring that the array's size
+// remains a multiple of the original size.
+RZ += SizeInBytes - (RZ % SizeInBytes);
+assert((RZ + SizeInBytes) % SizeInBytes == 0);
+  }
+
+  return RZ;
+}
+
 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
   int LongSize = M.getDataLayout().getPointerSizeInBits();
   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
Index: clang/test/CodeGen/asan-globals.cpp
=

[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-06-08 Thread Marco Elver via Phabricator via cfe-commits
melver abandoned this revision.
melver added a comment.

With an allmodconfig, mostpost still isn't happy because it expects the 
device_id info to be a certain size. Revert everything while we figure out how 
to make modpost happy.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81346



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


[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel

2020-06-08 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: glider.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya, aprantl.
Herald added a reviewer: aaron.ballman.
Herald added projects: clang, LLVM.

[ The first version of this feature was reverted due to modpost causing

  failures. This version fixes this. More info:
  https://github.com/ClangBuiltLinux/linux/issues/1045#issuecomment-640381783 ]

This makes -fsanitize=kernel-address emit the correct globals
constructors for the kernel. We had to do the following:

- Disable generation of constructors that rely on linker features such as 
dead-global elimination.

- Only instrument globals *not* in explicit sections. The kernel uses sections 
for special globals, which we should not touch.

- Do not instrument globals that are aliased by a symbol that is prefixed with 
"__". For example, modpost relies on specially named aliases to find globals 
and checks their contents. Unfortunately mod post relies on size stored as ELF 
debug info and any padding of globals currently causes the debug info to cause 
size reported to be *with* redzone which throws modpost off.

Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=203493

Tested:

1. With 'clang/test/CodeGen/asan-globals.cpp'.

2. With test_kasan.ko, we can see:

BUG: KASAN: global-out-of-bounds in kasan_global_oob+0xb3/0xba 
[test_kasan]

3. allyesconfig, allmodconfig


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobals

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel

2020-06-08 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269229.
melver added a comment.

Also ignore non-alias globals prefixed by __.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,8 +791,9 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
-  bool ShouldUseMachOGlobalsSection() const;
+  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  bool shoul

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D81390#2081067 , @nathanchance 
wrote:

> I do not know enough about KASAN enough to review this patch but I can say 
> that against mainline at 
> https://git.kernel.org/linus/af7b4801030c07637840191c69eb666917e4135d, there 
> appear to be no visible regressions with this version of the patch on top of 
> caa2fddce72f2e8ca3d6346cc2c8fe85252b91d8 
> .


Thank you for testing this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390



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


[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269578.
melver marked 6 inline comments as done.
melver added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,7 +791,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
+  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  bool shouldInstrumentGlobal(GlobalVariable 

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Thanks! PTAL.




Comment at: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp:759
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());

glider wrote:
> `UseGlobalsGC` assumes `!this->CompileKernel` already, doesn't it?
I experimented a bit and found that even if one of them is enabled things break 
(say if you remove UseGlobalsGC here). This is more explicit and less 
error-prone in case somebody removes UseGlobalsGC from UseCtorComdat. And there 
is no real penalty here for having it on both.



Comment at: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp:1796
+const GlobalAlias &GA) const {
+  if (CompileKernel) {
+// When compiling the kernel, globals that are aliased by symbols prefixed

glider wrote:
> Maybe it's better to call this function only if CompileKernel is true?
> I don't think we need it except for the kernel.
Done, though the previous version was cleaner. I guarded the call but now we 
need an assert and a comment to make sure the check is moved when people decide 
to use this for more than the kernel.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390



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


[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269582.
melver added a comment.

Fix test broken by linter.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,7 +791,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
+  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMach

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269751.
melver added a comment.

Fix typos.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,7 +791,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
+  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection(

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269780.
melver added a comment.

Fix test on windows.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,7 +791,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
+  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGloba

[PATCH] D81390: [KernelAddressSanitizer] Make globals constructors compatible with kernel [v2]

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd3f89314ff20: [KernelAddressSanitizer] Make globals 
constructors compatible with kernel [v2] (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81390

Files:
  clang/test/CodeGen/asan-globals.cpp
  llvm/include/llvm/Transforms/Utils/ModuleUtils.h
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
  llvm/lib/Transforms/Utils/ModuleUtils.cpp

Index: llvm/lib/Transforms/Utils/ModuleUtils.cpp
===
--- llvm/lib/Transforms/Utils/ModuleUtils.cpp
+++ llvm/lib/Transforms/Utils/ModuleUtils.cpp
@@ -119,6 +119,15 @@
   AttributeList());
 }
 
+Function *llvm::createSanitizerCtor(Module &M, StringRef CtorName) {
+  Function *Ctor = Function::Create(
+  FunctionType::get(Type::getVoidTy(M.getContext()), false),
+  GlobalValue::InternalLinkage, CtorName, &M);
+  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
+  ReturnInst::Create(M.getContext(), CtorBB);
+  return Ctor;
+}
+
 std::pair llvm::createSanitizerCtorAndInitFunctions(
 Module &M, StringRef CtorName, StringRef InitName,
 ArrayRef InitArgTypes, ArrayRef InitArgs,
@@ -128,11 +137,8 @@
  "Sanitizer's init function expects different number of arguments");
   FunctionCallee InitFunction =
   declareSanitizerInitFunction(M, InitName, InitArgTypes);
-  Function *Ctor = Function::Create(
-  FunctionType::get(Type::getVoidTy(M.getContext()), false),
-  GlobalValue::InternalLinkage, CtorName, &M);
-  BasicBlock *CtorBB = BasicBlock::Create(M.getContext(), "", Ctor);
-  IRBuilder<> IRB(ReturnInst::Create(M.getContext(), CtorBB));
+  Function *Ctor = createSanitizerCtor(M, CtorName);
+  IRBuilder<> IRB(Ctor->getEntryBlock().getTerminator());
   IRB.CreateCall(InitFunction, InitArgs);
   if (!VersionCheckName.empty()) {
 FunctionCallee VersionCheckFunction = M.getOrInsertFunction(
Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -589,11 +589,10 @@
   AddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
bool CompileKernel = false, bool Recover = false,
bool UseAfterScope = false)
-  : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+  : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(*GlobalsMD) {
 C = &(M.getContext());
 LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -742,7 +741,11 @@
   ModuleAddressSanitizer(Module &M, const GlobalsMetadata *GlobalsMD,
  bool CompileKernel = false, bool Recover = false,
  bool UseGlobalsGC = true, bool UseOdrIndicator = false)
-  : GlobalsMD(*GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
+  : GlobalsMD(*GlobalsMD),
+CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
+: CompileKernel),
+Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
+UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
 // Enable aliases as they should have no downside with ODR indicators.
 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
@@ -753,11 +756,7 @@
 // argument is designed as workaround. Therefore, disable both
 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
 // do globals-gc.
-UseCtorComdat(UseGlobalsGC && ClWithComdat) {
-this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
-this->CompileKernel =
-ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
-
+UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel) {
 C = &(M.getContext());
 int LongSize = M.getDataLayout().getPointerSizeInBits();
 IntptrTy = Type::getIntNTy(*C, LongSize);
@@ -792,7 +791,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool ShouldInstrumentGlobal(GlobalVariable *G);
+  bool canInstrumentAliasedGlob

[PATCH] D81591: [ASan][Test] Split out global alias test

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: thakis.
Herald added subscribers: cfe-commits, aaron.ballman.
Herald added a project: clang.

Some platforms do not support aliases. Split the test, and pass explicit
triple to avoid test failure.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D81591

Files:
  clang/test/CodeGen/asan-globals-alias.c
  clang/test/CodeGen/asan-globals.cpp


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -12,11 +12,9 @@
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
 
-int __attribute__((section("__DATA, __common"))) sectioned_global; // [KASAN] 
ignore globals in a section
+int __attribute__((section("__DATA, __common"))) sectioned_global; // KASAN - 
ignore globals in a section
 extern "C" {
-int aliased_global; // [KASAN] 
ignore globals prefixed by aliases with __-prefix [below]
-extern int __attribute__((alias("aliased_global"))) __global_alias; // [KASAN] 
aliased_global ignored
-int __special_global;   // [KASAN] 
ignore globals with __-prefix
+int __special_global; // KASAN - ignore globals with __-prefix
 }
 
 void func() {
@@ -26,8 +24,6 @@
 
 // ASAN: sectioned_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: sectioned_global{{.*}}i32
-// ASAN: @aliased_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
-// KASAN: @aliased_global{{.*}}i32
 // ASAN: @__special_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: @__special_global{{.*}}i32
 
@@ -36,7 +32,7 @@
 // ASAN-NEXT: call void @__asan_version_mismatch_check
 // KASAN-NOT: call void @__asan_init
 // KASAN-NOT: call void @__asan_version_mismatch_check
-// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 8)
+// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 7)
 // KASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 5)
 // CHECK-NEXT: ret void
 
@@ -44,7 +40,7 @@
 // CHECK-NEXT: call void @__asan_unregister_globals
 // CHECK-NEXT: ret void
 
-// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], 
!"extra_global", i1 false, i1 false}
 // CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
 // CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, 
i1 false}
@@ -55,16 +51,14 @@
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], 
!"sectioned_global", i1 false, i1 false}
 // CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 15, i32 
50}
-// CHECK: ![[ALIASED_GLOBAL]] = !{{{.*}} ![[ALIASED_GLOBAL_LOC:[0-9]+]], 
!"aliased_global", i1 false, i1 false}
-// CHECK: ![[ALIASED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[SPECIAL_GLOBAL]] = !{{{.*}} ![[SPECIAL_GLOBAL_LOC:[0-9]+]], 
!"__special_global", i1 false, i1 false}
-// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 19, i32 5}
+// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 
false, i1 false}
-// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 23, i32 14}
+// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 21, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
-// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 24, i32 25}
+// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 25}
 
-// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], 
!

[PATCH] D81591: [ASan][Test] Split out global alias test

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 269898.
melver added a comment.

Comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81591

Files:
  clang/test/CodeGen/asan-globals-alias.c
  clang/test/CodeGen/asan-globals.cpp


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -12,11 +12,9 @@
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
 
-int __attribute__((section("__DATA, __common"))) sectioned_global; // [KASAN] 
ignore globals in a section
+int __attribute__((section("__DATA, __common"))) sectioned_global; // KASAN - 
ignore globals in a section
 extern "C" {
-int aliased_global; // [KASAN] 
ignore globals prefixed by aliases with __-prefix [below]
-extern int __attribute__((alias("aliased_global"))) __global_alias; // [KASAN] 
aliased_global ignored
-int __special_global;   // [KASAN] 
ignore globals with __-prefix
+int __special_global; // KASAN - ignore globals with __-prefix
 }
 
 void func() {
@@ -26,8 +24,6 @@
 
 // ASAN: sectioned_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: sectioned_global{{.*}}i32
-// ASAN: @aliased_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
-// KASAN: @aliased_global{{.*}}i32
 // ASAN: @__special_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: @__special_global{{.*}}i32
 
@@ -36,7 +32,7 @@
 // ASAN-NEXT: call void @__asan_version_mismatch_check
 // KASAN-NOT: call void @__asan_init
 // KASAN-NOT: call void @__asan_version_mismatch_check
-// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 8)
+// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 7)
 // KASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 5)
 // CHECK-NEXT: ret void
 
@@ -44,7 +40,7 @@
 // CHECK-NEXT: call void @__asan_unregister_globals
 // CHECK-NEXT: ret void
 
-// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], 
!"extra_global", i1 false, i1 false}
 // CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
 // CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, 
i1 false}
@@ -55,16 +51,14 @@
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], 
!"sectioned_global", i1 false, i1 false}
 // CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 15, i32 
50}
-// CHECK: ![[ALIASED_GLOBAL]] = !{{{.*}} ![[ALIASED_GLOBAL_LOC:[0-9]+]], 
!"aliased_global", i1 false, i1 false}
-// CHECK: ![[ALIASED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[SPECIAL_GLOBAL]] = !{{{.*}} ![[SPECIAL_GLOBAL_LOC:[0-9]+]], 
!"__special_global", i1 false, i1 false}
-// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 19, i32 5}
+// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 
false, i1 false}
-// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 23, i32 14}
+// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 21, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
-// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 24, i32 25}
+// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 25}
 
-// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // BLACKLIST-SRC: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], 
!"extra_global", i1 false, i1 false}
 // BLACKLIST-SRC: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp",

[PATCH] D81591: [ASan][Test] Split out global alias test

2020-06-10 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0f04f104537b: [ASan][Test] Split out global alias test 
(authored by melver).

Changed prior to commit:
  https://reviews.llvm.org/D81591?vs=269898&id=269911#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81591

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  clang/test/CodeGen/asan-globals.cpp


Index: clang/test/CodeGen/asan-globals.cpp
===
--- clang/test/CodeGen/asan-globals.cpp
+++ clang/test/CodeGen/asan-globals.cpp
@@ -12,11 +12,9 @@
 int __attribute__((no_sanitize("address"))) attributed_global;
 int blacklisted_global;
 
-int __attribute__((section("__DATA, __common"))) sectioned_global; // [KASAN] 
ignore globals in a section
+int __attribute__((section("__DATA, __common"))) sectioned_global; // KASAN - 
ignore globals in a section
 extern "C" {
-int aliased_global; // [KASAN] 
ignore globals prefixed by aliases with __-prefix [below]
-extern int __attribute__((alias("aliased_global"))) __global_alias; // [KASAN] 
aliased_global ignored
-int __special_global;   // [KASAN] 
ignore globals with __-prefix
+int __special_global; // KASAN - ignore globals with __-prefix
 }
 
 void func() {
@@ -26,8 +24,6 @@
 
 // ASAN: sectioned_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: sectioned_global{{.*}}i32
-// ASAN: @aliased_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
-// KASAN: @aliased_global{{.*}}i32
 // ASAN: @__special_global{{.*}}{ i32, [60 x i8] }{{.*}}align 32
 // KASAN: @__special_global{{.*}}i32
 
@@ -36,7 +32,7 @@
 // ASAN-NEXT: call void @__asan_version_mismatch_check
 // KASAN-NOT: call void @__asan_init
 // KASAN-NOT: call void @__asan_version_mismatch_check
-// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 8)
+// ASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 7)
 // KASAN-NEXT: call void @__asan_register_globals({{.*}}, i{{32|64}} 5)
 // CHECK-NEXT: ret void
 
@@ -44,7 +40,7 @@
 // CHECK-NEXT: call void @__asan_unregister_globals
 // CHECK-NEXT: ret void
 
-// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// CHECK: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], ![[GLOBAL:[0-9]+]], 
![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // CHECK: ![[EXTRA_GLOBAL]] = !{{{.*}} ![[EXTRA_GLOBAL_LOC:[0-9]+]], 
!"extra_global", i1 false, i1 false}
 // CHECK: ![[EXTRA_GLOBAL_LOC]] = !{!"{{.*}}extra-source.cpp", i32 1, i32 5}
 // CHECK: ![[GLOBAL]] = !{{{.*}} ![[GLOBAL_LOC:[0-9]+]], !"global", i1 false, 
i1 false}
@@ -55,16 +51,14 @@
 // CHECK: ![[BLACKLISTED_GLOBAL]] = !{{{.*}}, null, null, i1 false, i1 true}
 // CHECK: ![[SECTIONED_GLOBAL]] = !{{{.*}} ![[SECTIONED_GLOBAL_LOC:[0-9]+]], 
!"sectioned_global", i1 false, i1 false}
 // CHECK: ![[SECTIONED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 15, i32 
50}
-// CHECK: ![[ALIASED_GLOBAL]] = !{{{.*}} ![[ALIASED_GLOBAL_LOC:[0-9]+]], 
!"aliased_global", i1 false, i1 false}
-// CHECK: ![[ALIASED_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[SPECIAL_GLOBAL]] = !{{{.*}} ![[SPECIAL_GLOBAL_LOC:[0-9]+]], 
!"__special_global", i1 false, i1 false}
-// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 19, i32 5}
+// CHECK: ![[SPECIAL_GLOBAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 17, i32 5}
 // CHECK: ![[STATIC_VAR]] = !{{{.*}} ![[STATIC_LOC:[0-9]+]], !"static_var", i1 
false, i1 false}
-// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 23, i32 14}
+// CHECK: ![[STATIC_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 21, i32 14}
 // CHECK: ![[LITERAL]] = !{{{.*}} ![[LITERAL_LOC:[0-9]+]], !"", i1 false, i1 false}
-// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 24, i32 25}
+// CHECK: ![[LITERAL_LOC]] = !{!"{{.*}}asan-globals.cpp", i32 22, i32 25}
 
-// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[ALIASED_GLOBAL:[0-9]+]], ![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], 
![[LITERAL:[0-9]+]]}
+// BLACKLIST-SRC: !llvm.asan.globals = !{![[EXTRA_GLOBAL:[0-9]+]], 
![[GLOBAL:[0-9]+]], ![[DYN_INIT_GLOBAL:[0-9]+]], ![[ATTR_GLOBAL:[0-9]+]], 
![[BLACKLISTED_GLOBAL:[0-9]+]], ![[SECTIONED_GLOBAL:[0-9]+]], 
![[SPECIAL_GLOBAL:[0-9]+]], ![[STATIC_VAR:[0-9]+]], ![[LITERAL:[0-9]+]]}
 // BLACKL

[PATCH] D73543: [clang] Add support for __builtin_memcpy_inline

2020-06-17 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/test/Sema/builtins-memcpy-inline.c:7
+#warning defined as expected
+// expected-warning@-1 {{defined as expected}}
+#endif

It appears that the expected-warning check here is guarded by the #if as well. 
Moving it after the #endif results in a failing test.

I noticed this as I was trying to use __has_feature(__builtin_memcpy_inline), 
but it somehow does not work, even though the compiler clearly supports 
__builtin_memcpy_inline.

Any idea what's wrong with the __has_feature test?

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73543



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


[PATCH] D81346: [KernelAddressSanitizer] Ensure global array size remains multiple of type-size

2020-07-31 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Note: We landed globals support for KASAN with 
https://reviews.llvm.org/rGd3f89314ff20ce1612bd5e09f9f90ff5dd5205a7


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81346

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


[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-08 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: vitalybuka.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This permits combining -fsanitize-coverage with -fsanitize=bounds or
-fsanitize=thread. Note that, GCC already supports combining these.

Bugzilla: https://bugs.llvm.org/show_bug.cgi?id=45831


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-coverage.c


Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target %itanium_abi_triple -fsanitize=float-divide-by-zero 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // CHECK-SANITIZE-COVERAGE-FUNC: fsanitize-coverage-type=1
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -43,11 +43,12 @@
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress |
 SanitizerKind::MemTag | SanitizerKind::Memory |
 SanitizerKind::KernelMemory | SanitizerKind::Leak |
-SanitizerKind::Undefined | SanitizerKind::Integer |
+SanitizerKind::Undefined | SanitizerKind::Integer | SanitizerKind::Bounds |
 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
 SanitizerKind::DataFlow | SanitizerKind::Fuzzer |
 SanitizerKind::FuzzerNoLink | SanitizerKind::FloatDivideByZero |
-SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack;
+SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack |
+SanitizerKind::Thread;
 static const SanitizerMask RecoverableByDefault =
 SanitizerKind::Undefined | SanitizerKind::Integer |
 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |


Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target %itanium_abi_triple -fsanitize=float-divide-by-zero -fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize-cover

[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-14 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 264109.
melver added a comment.

Add tests checking that when passing the combination of the sanitizer flags to 
Clang, we generate instrumentation for all enabled sanitizers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-coverage-bounds.c
  clang/test/CodeGen/sanitize-coverage-thread.c
  clang/test/Driver/fsanitize-coverage.c


Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target %itanium_abi_triple -fsanitize=float-divide-by-zero 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // CHECK-SANITIZE-COVERAGE-FUNC: fsanitize-coverage-type=1
Index: clang/test/CodeGen/sanitize-coverage-thread.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-coverage-thread.c
@@ -0,0 +1,25 @@
+// RUN: %clang %s -emit-llvm -S -fsanitize=thread 
-fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s
+
+int x = 0;
+
+// CHECK-LABEL: define dso_local void @foo(
+void foo(void) {
+// CHECK: call void @__sanitizer_cov_trace_pc
+
+// CHECK: call void @__tsan_read4(i8* bitcast (i32* @x to i8*))
+// CHECK-NEXT: load i32, i32* @x, align 4
+
+// CHECK: call void @__sanitizer_cov_trace_const_cmp4
+// CHECK: br
+
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: br
+if (x)
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: call void @__tsan_write4(i8* bitcast (i32* @x to i8*))
+// CHECK-NEXT: store i32 42, i32* @x, align 4
+// CHECK: br
+x = 42;
+
+// CHECK: ret void
+}
Index: clang/test/CodeGen/sanitize-coverage-bounds.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-coverage-bounds.c
@@ -0,0 +1,29 @@
+// RUN: %clang %s -emit-llvm -S -fsanitize=bounds 
-fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s
+
+int x[10];
+
+// CHECK-LABEL: define dso_local void @foo(
+void foo(int n) {
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: call void @__sanitizer_cov_trace_const_cmp
+// CHECK: br
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: br
+// CHECK: call void @__sanitizer_cov_trace_const_cmp
+// CHECK: br
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: br
+if (n)
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: call void @__ubsan_handle_out_of_bounds
+// CHECK: br
+// CHECK: getelementptr inbounds [10 x i32], [10 x i32]* @x
+// CHECK: call void @__sanitizer_cov_trace_const_cmp8
+// CHECK: br
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: store i32 42
+// CHECK: br
+x[n] = 42;
+
+// CHECK: ret void
+}
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -43,11 +43,12 @@
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress |
 SanitizerKind::MemTag | SanitizerKind::Memory |
 SanitizerKind::KernelMemory | SanitizerKind::Leak |
-SanitizerKind::Undefined | SanitizerKind::Integer |
+SanitizerKind::Undefined | SanitizerKind

[PATCH] D79628: [Clang][Driver] Add Bounds and Thread to SupportsCoverage list

2020-05-14 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 264112.
melver added a comment.

Fix formatting.

PTAL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D79628

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-coverage-bounds.c
  clang/test/CodeGen/sanitize-coverage-thread.c
  clang/test/Driver/fsanitize-coverage.c


Index: clang/test/Driver/fsanitize-coverage.c
===
--- clang/test/Driver/fsanitize-coverage.c
+++ clang/test/Driver/fsanitize-coverage.c
@@ -12,8 +12,10 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=kernel-memory 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=leak 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=undefined 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=bounds 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=bool 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=dataflow 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=thread 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target %itanium_abi_triple -fsanitize=float-divide-by-zero 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // RUN: %clang -target x86_64-linux-gnu 
-fsanitize-coverage=func,trace-pc %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-SANITIZE-COVERAGE-FUNC
 // CHECK-SANITIZE-COVERAGE-FUNC: fsanitize-coverage-type=1
Index: clang/test/CodeGen/sanitize-coverage-thread.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-coverage-thread.c
@@ -0,0 +1,25 @@
+// RUN: %clang %s -emit-llvm -S -fsanitize=thread 
-fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s
+
+int x = 0;
+
+// CHECK-LABEL: define dso_local void @foo(
+void foo(void) {
+  // CHECK: call void @__sanitizer_cov_trace_pc
+
+  // CHECK: call void @__tsan_read4(i8* bitcast (i32* @x to i8*))
+  // CHECK-NEXT: load i32, i32* @x, align 4
+
+  // CHECK: call void @__sanitizer_cov_trace_const_cmp4
+  // CHECK: br
+
+  // CHECK: call void @__sanitizer_cov_trace_pc
+  // CHECK: br
+  if (x)
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: call void @__tsan_write4(i8* bitcast (i32* @x to i8*))
+// CHECK-NEXT: store i32 42, i32* @x, align 4
+// CHECK: br
+x = 42;
+
+  // CHECK: ret void
+}
Index: clang/test/CodeGen/sanitize-coverage-bounds.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-coverage-bounds.c
@@ -0,0 +1,29 @@
+// RUN: %clang %s -emit-llvm -S -fsanitize=bounds 
-fsanitize-coverage=trace-pc,trace-cmp -o - | FileCheck %s
+
+int x[10];
+
+// CHECK-LABEL: define dso_local void @foo(
+void foo(int n) {
+  // CHECK: call void @__sanitizer_cov_trace_pc
+  // CHECK: call void @__sanitizer_cov_trace_const_cmp
+  // CHECK: br
+  // CHECK: call void @__sanitizer_cov_trace_pc
+  // CHECK: br
+  // CHECK: call void @__sanitizer_cov_trace_const_cmp
+  // CHECK: br
+  // CHECK: call void @__sanitizer_cov_trace_pc
+  // CHECK: br
+  if (n)
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: call void @__ubsan_handle_out_of_bounds
+// CHECK: br
+// CHECK: getelementptr inbounds [10 x i32], [10 x i32]* @x
+// CHECK: call void @__sanitizer_cov_trace_const_cmp8
+// CHECK: br
+// CHECK: call void @__sanitizer_cov_trace_pc
+// CHECK: store i32 42
+// CHECK: br
+x[n] = 42;
+
+  // CHECK: ret void
+}
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -43,11 +43,12 @@
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress |
 SanitizerKind::MemTag | SanitizerKind::Memory |
 SanitizerKind::KernelMemory | SanitizerKind::Leak |
-SanitizerKind::Undefined | SanitizerKind::Integer |
+SanitizerKind::Undefined | SanitizerKind::Integer | SanitizerKind::Bounds |
 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
 SanitizerKind::DataFlow | SanitizerKind::Fuzzer |
 SanitizerKind::FuzzerNoLink | SanitizerKind::Float

[PATCH] D78162: [CodeGen] Mark inline definitions of builtins as nobuiltin only if we plan to emit them.

2020-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

This seems to be causing problems for the Linux kernel with ASan 
instrumentation enabled: 
https://lkml.kernel.org/r/20200518180513.ga114...@google.com

Still investigating if it's the kernel, KASAN, or Clang that's doing something 
wrong. Any pointers welcome.

Many thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78162



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


[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-08-30 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 456608.
melver added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,34 @@
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=all \
+// RUN:   -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=atomics \
+// RUN:   -fno-experimental-sanitize-metadata=atomics \
+// RUN:   -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered \
+// RUN:   -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -100,6 +100,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid components. Returns a SanitizerMask.
 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
@@ -110,6 +115,11 @@
 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  bool DiagnoseErrors);
 
+/// Parse -f(no-)?sanitize-metadata= flag values, diagnosing any invalid
+/// components. Returns OR of members of \c BinaryMetadataFeature enumeration.
+static int parseBinaryMetadataFeatures(const Driver &D, const llvm::opt::Arg *A,
+   bool DiagnoseErrors);
+
 /// Produce an argument string from ArgList \p Args, which shows how it
 /// provides some sanitizer kind from \p Mask. For example, the argument list
 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
@@ -834,6 +844,22 @@
 DiagnoseErrors);
   }
 
+  // Parse -f(no-)?sanitize-metadata.
+  for (const auto *Arg :
+   Args.filtered(options::OPT_fexperimental_sanitize_metadata_EQ,
+ options::OPT_fno_experimental_sanitize_metadata_EQ)) {
+if (Arg->getOption().matches(
+options::OPT_fexperimental_sanitize_metadata_EQ)) {
+  Arg->claim();
+  BinaryMetadataFeatures |=
+  parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+} else {
+  Arg->claim();
+  BinaryMetadataFeatures &=
+  ~parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+}
+  }
+
   SharedRuntime =
   Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
@@ -1095,6 +1121,17 @@
   addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
 CoverageIgnorelistFiles);
 
+  // Translate available BinaryMetadataFeatures to corresponding clang-cc1
+  // flags. Does not depend on any other sanitizers.
+  const std::pair BinaryMetadataFlags[] = {
+  std::make

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-09-02 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 457543.
melver added a comment.

Add CodeGen test.

PTAL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-metadata.c
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,34 @@
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=all \
+// RUN:   -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=atomics \
+// RUN:   -fno-experimental-sanitize-metadata=atomics \
+// RUN:   -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered \
+// RUN:   -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/test/CodeGen/sanitize-metadata.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-metadata.c
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple x86_64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple aarch64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+
+int x, y;
+
+void empty() {
+// CHECK-NOT: define dso_local void @empty() {{.*}} !pcsections
+}
+
+int atomics() {
+// ATOMICS-LABEL: define dso_local i32 @atomics()
+// ATOMICS-SAME:  !pcsections ![[ATOMICS_COVERED:[0-9]+]]
+// ATOMICS-NEXT:  entry:
+// ATOMICS-NEXT:atomicrmw add {{.*}} !pcsections ![[ATOMIC_OP:[0-9]+]]
+// ATOMICS-NOT: load {{.*}} !pcsections
+  __atomic_fetch_add(&x, 1, __ATOMIC_RELAXED);
+  return y;
+}
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_ctor
+// ATOMICS: call void @__sanitizer_metadata_atomics_add(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_dtor
+// ATOMICS: call void @__sanitizer_metadata_atomics_del(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+
+// CHECK-LABEL: __sanitizer_metadata_covered.module_ctor
+// CHECK: call void @__sanitizer_metadata_covered_add(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+// CHECK-LABEL: __sanitizer_metadata_covered.module_dtor
+// CHECK: call void @__sanitizer_metadata_covered_del(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+
+// ATOMICS: ![[ATOMICS_COVERED]] = !{!"sanmd_covered", ![[ATOMICS_COVERED_AUX:[0-9]+]]}
+// ATOMICS: ![[ATOMICS_COVERED_AUX]] = !{i32 1}
+// ATOMICS: ![[ATOMIC_OP]] = !{!"sanmd_atomics"}
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -100,6 +100,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid compone

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-09-02 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 457637.
melver added a comment.

Don't split RUN lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-metadata.c
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,19 @@
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics -fno-experimental-sanitize-metadata=atomics -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/test/CodeGen/sanitize-metadata.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-metadata.c
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple x86_64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple aarch64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+
+int x, y;
+
+void empty() {
+// CHECK-NOT: define dso_local void @empty() {{.*}} !pcsections
+}
+
+int atomics() {
+// ATOMICS-LABEL: define dso_local i32 @atomics()
+// ATOMICS-SAME:  !pcsections ![[ATOMICS_COVERED:[0-9]+]]
+// ATOMICS-NEXT:  entry:
+// ATOMICS-NEXT:atomicrmw add {{.*}} !pcsections ![[ATOMIC_OP:[0-9]+]]
+// ATOMICS-NOT: load {{.*}} !pcsections
+  __atomic_fetch_add(&x, 1, __ATOMIC_RELAXED);
+  return y;
+}
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_ctor
+// ATOMICS: call void @__sanitizer_metadata_atomics_add(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_dtor
+// ATOMICS: call void @__sanitizer_metadata_atomics_del(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+
+// CHECK-LABEL: __sanitizer_metadata_covered.module_ctor
+// CHECK: call void @__sanitizer_metadata_covered_add(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+// CHECK-LABEL: __sanitizer_metadata_covered.module_dtor
+// CHECK: call void @__sanitizer_metadata_covered_del(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+
+// ATOMICS: ![[ATOMICS_COVERED]] = !{!"sanmd_covered", ![[ATOMICS_COVERED_AUX:[0-9]+]]}
+// ATOMICS: ![[ATOMICS_COVERED_AUX]] = !{i32 1}
+// ATOMICS: ![[ATOMIC_OP]] = !{!"sanmd_atomics"}
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -100,6 +100,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid components. Returns a SanitizerMask.
 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
@@ -110,6 +115,11 @@
 static int parseCoverageFeatures(const Driver &D, const llvm::opt:

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-09-03 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/test/Driver/fsanitize-metadata.c:1
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all 
-fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata

MaskRay wrote:
>  -fno-experimental-sanitize-metadata= works on bitmasks. You can change this 
> run line to remove one bit instead of all.
Added more tests to check removing one bit after =all, but left this in place 
for the extra coverage.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

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


[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-09-03 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 457779.
melver marked 3 inline comments as done.
melver added a comment.

- Options.td: s/f_clang_Group/f_Group/, remove NoXarchOption
- Driver test: also test -fexperimental-sanitize-metadata=all 
-fno-experimental-metadata=


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-metadata.c
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,23 @@
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics -fno-experimental-sanitize-metadata=atomics -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered -fno-experimental-sanitize-metadata=covered -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+// CHECK-ATOMICS-NOT: "-fexperimental-sanitize-metadata=covered"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/test/CodeGen/sanitize-metadata.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-metadata.c
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple x86_64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple aarch64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+
+int x, y;
+
+void empty() {
+// CHECK-NOT: define dso_local void @empty() {{.*}} !pcsections
+}
+
+int atomics() {
+// ATOMICS-LABEL: define dso_local i32 @atomics()
+// ATOMICS-SAME:  !pcsections ![[ATOMICS_COVERED:[0-9]+]]
+// ATOMICS-NEXT:  entry:
+// ATOMICS-NEXT:atomicrmw add {{.*}} !pcsections ![[ATOMIC_OP:[0-9]+]]
+// ATOMICS-NOT: load {{.*}} !pcsections
+  __atomic_fetch_add(&x, 1, __ATOMIC_RELAXED);
+  return y;
+}
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_ctor
+// ATOMICS: call void @__sanitizer_metadata_atomics_add(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_dtor
+// ATOMICS: call void @__sanitizer_metadata_atomics_del(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+
+// CHECK-LABEL: __sanitizer_metadata_covered.module_ctor
+// CHECK: call void @__sanitizer_metadata_covered_add(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+// CHECK-LABEL: __sanitizer_metadata_covered.module_dtor
+// CHECK: call void @__sanitizer_metadata_covered_del(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+
+// ATOMICS: ![[ATO

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-09-07 Thread Marco Elver 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 rGc4842bb2e98e: [Clang] Introduce 
-fexperimental-sanitize-metadata= (authored by melver).

Changed prior to commit:
  https://reviews.llvm.org/D130888?vs=457779&id=458532#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/CodeGen/sanitize-metadata.c
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,23 @@
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics -fno-experimental-sanitize-metadata=atomics -fexperimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered -fno-experimental-sanitize-metadata=covered -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all -fno-experimental-sanitize-metadata=covered %s -### 2>&1 | FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+// CHECK-ATOMICS-NOT: "-fexperimental-sanitize-metadata=covered"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/test/CodeGen/sanitize-metadata.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-metadata.c
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple x86_64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+// RUN: %clang_cc1 -O -fexperimental-sanitize-metadata=atomics -triple aarch64-gnu-linux -x c -S -emit-llvm %s -o - | FileCheck %s --check-prefixes=CHECK,ATOMICS
+
+int x, y;
+
+void empty() {
+// CHECK-NOT: define dso_local void @empty() {{.*}} !pcsections
+}
+
+int atomics() {
+// ATOMICS-LABEL: define dso_local i32 @atomics()
+// ATOMICS-SAME:  !pcsections ![[ATOMICS_COVERED:[0-9]+]]
+// ATOMICS-NEXT:  entry:
+// ATOMICS-NEXT:atomicrmw add {{.*}} !pcsections ![[ATOMIC_OP:[0-9]+]]
+// ATOMICS-NOT: load {{.*}} !pcsections
+  __atomic_fetch_add(&x, 1, __ATOMIC_RELAXED);
+  return y;
+}
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_ctor
+// ATOMICS: call void @__sanitizer_metadata_atomics_add(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+// ATOMICS-LABEL: __sanitizer_metadata_atomics.module_dtor
+// ATOMICS: call void @__sanitizer_metadata_atomics_del(i32 1, ptr @__start_sanmd_atomics, ptr @__stop_sanmd_atomics)
+
+// CHECK-LABEL: __sanitizer_metadata_covered.module_ctor
+// CHECK: call void @__sanitizer_metadata_covered_add(i32 1, ptr @__start_sanmd_covered, ptr @__stop_sanmd_covered)
+// CHECK-LABEL: __sanitizer_metadata_covered.module_dtor
+// CHECK: call void @__sanitizer_metadata_covered_del(i32 1, ptr @__start_sanm

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-08-01 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
Herald added a subscriber: ormris.
Herald added a project: All.
melver requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Introduces the frontend flag -fexperimental-sanitize-metadata=, which
enables SanitizerBinaryMetadata instrumentation.

The first intended user of the binary metadata emitted will be a variant
of GWP-TSan [1]. The plan is to open source a stable and production
quality version of GWP-TSan. The development of which, however, requires
upstream compiler support.

[1] https://llvm.org/devmtg/2020-09/slides/Morehouse-GWP-Tsan.pdf

Until the tool has been open sourced, we mark this kind of
instrumentation as "experimental", and reserve the option to change
binary format, remove features, and similar.

Depends on D130887 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,22 @@
+// RUN: %clang -target x86_64-linux-gnu %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang -target x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang -target x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata-covered"
+
+// RUN: %clang -target x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata-atomics"
+
+// RUN: %clang -target x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang -target x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata-covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata-atomics"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -98,6 +98,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid components. Returns a SanitizerMask.
 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
@@ -108,6 +113,11 @@
 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  bool DiagnoseErrors);
 
+/// Parse -f(no-)?sanitize-metadata= flag values, diagnosing any invalid
+/// components. Returns OR of members of \c BinaryMetadataFeature enumeration.
+static int parseBinaryMetadataFeatures(const Driver &D, const llvm::opt::Arg *A,
+   bool DiagnoseErrors);
+
 /// Produce an argument string from ArgList \p Args, which shows how it
 /// provides some sanitizer kind from \p Mask. For example, the argument list
 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
@@ -825,6 +835,21 @@
 DiagnoseErrors);
   }
 
+  // Parse -f(no-)?sanitize-metadata.
+  for (const auto *Arg : Args) {
+if (Arg->getOption().matches(
+options::OPT_fexperimental_sanitize_metadata)) {
+  Arg->claim();
+  BinaryMetadataFeatures |=
+  parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+} else if (Arg->getOption().matches(
+   options::OPT_fno_experimental_sanitize_metadata)) {
+  Arg->claim();
+  BinaryMetadataFeatures &=
+  ~parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+}
+  }
+
   SharedRuntime =
   Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
@@ -1086,6 +,17 @@
   addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
 CoverageIgnorelistFiles);
 
+  // Translate available BinaryMetadataFeatures to corresponding clang-cc1
+  // flags. Does not depend on any other sanitizers.
+  const std::pair BinaryMetadataFlags[] = {

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-08-03 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 449671.
melver marked 4 inline comments as done.
melver added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,34 @@
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=all \
+// RUN:   -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=atomics \
+// RUN:   -fno-experimental-sanitize-metadata=atomics \
+// RUN:   -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered \
+// RUN:   -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -98,6 +98,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid components. Returns a SanitizerMask.
 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
@@ -108,6 +113,11 @@
 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  bool DiagnoseErrors);
 
+/// Parse -f(no-)?sanitize-metadata= flag values, diagnosing any invalid
+/// components. Returns OR of members of \c BinaryMetadataFeature enumeration.
+static int parseBinaryMetadataFeatures(const Driver &D, const llvm::opt::Arg *A,
+   bool DiagnoseErrors);
+
 /// Produce an argument string from ArgList \p Args, which shows how it
 /// provides some sanitizer kind from \p Mask. For example, the argument list
 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
@@ -825,6 +835,22 @@
 DiagnoseErrors);
   }
 
+  // Parse -f(no-)?sanitize-metadata.
+  for (const auto *Arg :
+   Args.filtered(options::OPT_fexperimental_sanitize_metadata_EQ,
+ options::OPT_fno_experimental_sanitize_metadata_EQ)) {
+if (Arg->getOption().matches(
+options::OPT_fexperimental_sanitize_metadata_EQ)) {
+  Arg->claim();
+  BinaryMetadataFeatures |=
+  parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+} else {
+  Arg->claim();
+  BinaryMetadataFeatures &=
+  ~parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+}
+  }
+
   SharedRuntime =
   Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
@@ -1086,6 +1112,17 @@
   addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
 CoverageIgnorelistFiles);
 
+  // Translate available BinaryMetadataFeatures to corresponding clang-cc1
+  // flags. Does not depend on any other sanitizers.
+  const std

[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-08-03 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/lib/Driver/SanitizerArgs.cpp:839
+  // Parse -f(no-)?sanitize-metadata.
+  for (const auto *Arg : Args) {
+if (Arg->getOption().matches(

MaskRay wrote:
> Use `Args.getLastArg(...)`
This won't work if someone does:

  -fsanitize-metadata=feature1 -fsanitize-metadata=feature2

(instead of '-fsanitize-metadata=feature1,feature2')

Added a test case.



Comment at: clang/test/Driver/fsanitize-metadata.c:1
+// RUN: %clang -target x86_64-linux-gnu %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata

MaskRay wrote:
> This RUN line is redundant. For other opt-in features, we don't check that 
> the cc1 command line doesn't have an option. 
I've made the negative-presence test more useful by checking -fno- option works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

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


[PATCH] D130888: [Clang] Introduce -fexperimental-sanitize-metadata=

2022-08-04 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 450043.
melver added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D130888

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/SanitizerArgs.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize-metadata.c

Index: clang/test/Driver/fsanitize-metadata.c
===
--- /dev/null
+++ clang/test/Driver/fsanitize-metadata.c
@@ -0,0 +1,34 @@
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=all \
+// RUN:   -fno-experimental-sanitize-metadata=all %s -### 2>&1 | FileCheck %s
+// CHECK-NOT: -fexperimental-sanitize-metadata
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=bad_arg %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-INVALID %s
+// CHECK-INVALID: error: unsupported argument 'bad_arg' to option '-fexperimental-sanitize-metadata='
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=atomics \
+// RUN:   -fno-experimental-sanitize-metadata=atomics \
+// RUN:   -fexperimental-sanitize-metadata=covered %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-COVERED %s
+// CHECK-COVERED: "-fexperimental-sanitize-metadata=covered"
+// CHECK-COVERED-NOT: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ATOMICS %s
+// CHECK-ATOMICS: "-fexperimental-sanitize-metadata=atomics"
+
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered,atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu \
+// RUN:   -fexperimental-sanitize-metadata=covered \
+// RUN:   -fexperimental-sanitize-metadata=atomics %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// RUN: %clang --target=x86_64-linux-gnu -fexperimental-sanitize-metadata=all %s -### 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ALL %s
+// CHECK-ALL: "-fexperimental-sanitize-metadata=covered"
+// CHECK-ALL: "-fexperimental-sanitize-metadata=atomics"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -98,6 +98,11 @@
   CoverageTraceStores = 1 << 17,
 };
 
+enum BinaryMetadataFeature {
+  BinaryMetadataCovered = 1 << 0,
+  BinaryMetadataAtomics = 1 << 1,
+};
+
 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
 /// invalid components. Returns a SanitizerMask.
 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
@@ -108,6 +113,11 @@
 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  bool DiagnoseErrors);
 
+/// Parse -f(no-)?sanitize-metadata= flag values, diagnosing any invalid
+/// components. Returns OR of members of \c BinaryMetadataFeature enumeration.
+static int parseBinaryMetadataFeatures(const Driver &D, const llvm::opt::Arg *A,
+   bool DiagnoseErrors);
+
 /// Produce an argument string from ArgList \p Args, which shows how it
 /// provides some sanitizer kind from \p Mask. For example, the argument list
 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
@@ -825,6 +835,22 @@
 DiagnoseErrors);
   }
 
+  // Parse -f(no-)?sanitize-metadata.
+  for (const auto *Arg :
+   Args.filtered(options::OPT_fexperimental_sanitize_metadata_EQ,
+ options::OPT_fno_experimental_sanitize_metadata_EQ)) {
+if (Arg->getOption().matches(
+options::OPT_fexperimental_sanitize_metadata_EQ)) {
+  Arg->claim();
+  BinaryMetadataFeatures |=
+  parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+} else {
+  Arg->claim();
+  BinaryMetadataFeatures &=
+  ~parseBinaryMetadataFeatures(D, Arg, DiagnoseErrors);
+}
+  }
+
   SharedRuntime =
   Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
@@ -1086,6 +1112,17 @@
   addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
 CoverageIgnorelistFiles);
 
+  // Translate available BinaryMetadataFeatures to corresponding clang-cc1
+  // flags. Does not depend on any other sanitizers.
+  const std::pair BinaryMetadataFlags[] = {
+  std::make_p

[PATCH] D114421: [asan] Add support for disable_sanitizer_instrumentation attribute

2022-02-14 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

I think we dropped the ball on this - was it ever re-reverted?
Is it still worth trying to land this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114421

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


[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 310488.
melver added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,8 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA,
+ bool Rec = false) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1788,39 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
-  // In case this function should be expanded to include rules that do not just
-  // apply when CompileKernel is true, either guard all existing rules with an
-  // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
-  // should also apply to user space.
-  assert(CompileKernel && "Only expecting to be called when compiling kernel");
-
-  // When compiling the kernel, globals that are aliased by symbols prefixed
-  // by "__" are special and cannot be padded with a redzone.
-  if (GA.getName().startswith("__"))
-return false;
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA,
+ bool Rec) const {
+  if (!Rec) { // Non-recursive case.
+// In case this function should be expanded to include rules that do not
+// just apply when CompileKernel is true, either guard all existing rules
+// with an 'if (CompileKernel) { ... }' or be absolutely sure that all these
+// rules should also apply to user space.
+assert(CompileKernel &&
+   "Only expecting to be called when compiling kernel");
+
+// When compiling the kernel, globals that are aliased by symbols prefixed
+// by "__" are special and cannot be padded with a redzone.
+if (!GA.getName().startswith("__"))
+  return nullptr;
+  }
+
+  if (const auto *GV = dyn_cast(GA.getAliasee())) {
+// Find GlobalVariable from aliasee.
+return GV;
+  } else if (const auto *CE = dyn_cast(GA.getAliasee())) {
+// Pointer expression into GlobalVariable; find it from one of the operands.
+for (const Use &U : CE->operands()) {
+  if (const auto *GV = dyn_cast(U))
+return GV;
+}
+  } else if (const auto *GAA = dyn_cast(GA.getAliasee())) {
+// Recursive GlobalAlias
+return getExcludedAliasedGlobal(*GAA, true);
+  }
 
-  return true;
+  // Not a GlobalVariable alias, ignore.
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2272,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,36 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern 

[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 310492.
melver added a comment.

Simplify using stripPointerCastsAndAliases()


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,7 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1787,22 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
   // In case this function should be expanded to include rules that do not just
   // apply when CompileKernel is true, either guard all existing rules with an
   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
   // should also apply to user space.
   assert(CompileKernel && "Only expecting to be called when compiling kernel");
 
-  // When compiling the kernel, globals that are aliased by symbols prefixed
-  // by "__" are special and cannot be padded with a redzone.
-  if (GA.getName().startswith("__"))
-return false;
+  // When compiling the kernel, globals that are aliased by symbols prefixed by
+  // "__" are special and cannot be padded with a redzone.
+  if (GA.getName().startswith("__")) {
+return dyn_cast(
+GA.getAliasee()->stripPointerCastsAndAliases());
+  }
 
-  return true;
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2254,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,36 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern int __attribute__((alias("aliased_global"))) __global_alias; // KASAN - aliased_global ignored
+int global; // generate ctor for at least 1 global
+int aliased_global; // KASAN ignored
+extern int __attribute__((alias("aliased_global"))) __global_alias;
+
+// Recursive alias:
+int aliased_global_2; // KASAN ignored
+extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
+extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
+
+// Potential indirect alias:
+struct input_device_id {
+  unsigned long keybit[24];
+  unsigned long driver_info;
+};
+struct input_device_id joydev_ids[] = { { {1}, 1234 } }; // KASAN ignored
+extern struct input_device_id __attribute__((alias("joydev_ids"))) __mod_joydev_ids_device_table;
 
 // ASAN: @aliased_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @aliased_global_2{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @joydev_ids{{.*}} global { {{.*}}[56 x i8] zeroinitializer }, align 32
 // KASAN: @aliased_global{{.*}} global i32
+// KASAN: @aliased_global_2{{.*}} global i32
+//

[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D92846#2440118 , @dvyukov wrote:

> Have you checked if there is already a function that does this? Frequently 
> there is :)
> Some functions that look similar based on names:
> stripPointerCasts
> stripPointerCastsAndOffsets
> stripPointerCastsAndAliases
> canonicalizeAlias

Yup, stripPointerCastsAndAliases() works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

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


[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 310494.
melver added a comment.

Style


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,7 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1787,22 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
   // In case this function should be expanded to include rules that do not just
   // apply when CompileKernel is true, either guard all existing rules with an
   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
   // should also apply to user space.
   assert(CompileKernel && "Only expecting to be called when compiling kernel");
 
-  // When compiling the kernel, globals that are aliased by symbols prefixed
-  // by "__" are special and cannot be padded with a redzone.
+  const Constant *C = GA.getAliasee();
+
+  // When compiling the kernel, globals that are aliased by symbols prefixed by
+  // "__" are special and cannot be padded with a redzone.
   if (GA.getName().startswith("__"))
-return false;
+return dyn_cast(C->stripPointerCastsAndAliases());
 
-  return true;
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2254,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,36 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern int __attribute__((alias("aliased_global"))) __global_alias; // KASAN - aliased_global ignored
+int global; // generate ctor for at least 1 global
+int aliased_global; // KASAN ignored
+extern int __attribute__((alias("aliased_global"))) __global_alias;
+
+// Recursive alias:
+int aliased_global_2; // KASAN ignored
+extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
+extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
+
+// Potential indirect alias:
+struct input_device_id {
+  unsigned long keybit[24];
+  unsigned long driver_info;
+};
+struct input_device_id joydev_ids[] = { { {1}, 1234 } }; // KASAN ignored
+extern struct input_device_id __attribute__((alias("joydev_ids"))) __mod_joydev_ids_device_table;
 
 // ASAN: @aliased_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @aliased_global_2{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @joydev_ids{{.*}} global { {{.*}}[56 x i8] zeroinitializer }, align 32
 // KASAN: @aliased_global{{.*}} global i32
+// KASAN: @aliased_global_2{{.*}} global i32
+// KASAN: @joydev_ids{{.*}} global [1 x {{.*}}i64 1234 }], align 16

[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 310495.
melver added a comment.

Revert unnecessary reformat


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,7 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1787,22 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
   // In case this function should be expanded to include rules that do not just
   // apply when CompileKernel is true, either guard all existing rules with an
   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
   // should also apply to user space.
   assert(CompileKernel && "Only expecting to be called when compiling kernel");
 
+  const Constant *C = GA.getAliasee();
+
   // When compiling the kernel, globals that are aliased by symbols prefixed
   // by "__" are special and cannot be padded with a redzone.
   if (GA.getName().startswith("__"))
-return false;
+return dyn_cast(C->stripPointerCastsAndAliases());
 
-  return true;
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2254,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,36 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern int __attribute__((alias("aliased_global"))) __global_alias; // KASAN - aliased_global ignored
+int global; // generate ctor for at least 1 global
+int aliased_global; // KASAN ignored
+extern int __attribute__((alias("aliased_global"))) __global_alias;
+
+// Recursive alias:
+int aliased_global_2; // KASAN ignored
+extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
+extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
+
+// Potential indirect alias:
+struct input_device_id {
+  unsigned long keybit[24];
+  unsigned long driver_info;
+};
+struct input_device_id joydev_ids[] = { { {1}, 1234 } }; // KASAN ignored
+extern struct input_device_id __attribute__((alias("joydev_ids"))) __mod_joydev_ids_device_table;
 
 // ASAN: @aliased_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @aliased_global_2{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @joydev_ids{{.*}} global { {{.*}}[56 x i8] zeroinitializer }, align 32
 // KASAN: @aliased_global{{.*}} global i32
+// KASAN: @aliased_global_2{{.*}} global i32
+// KASAN: @joydev_ids{{.*}} global [1 x {{.*}}i64 1234 }], align 16
 
 // CHECK-LABEL: define internal void @asan.module_ctor
-// ASAN: call void @__asan_register_globals({{.*}}, i{{32|64

[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D92846#2442447 , @dvyukov wrote:

> The code looks reasonable to me. I see it only affects kernel, so assuming 
> you booted kernel, we should be fine.
> I can rubber-stamp it, but if you want more meaningful review, please wait 
> for Alex or Nick.

Added Nick.

I suppose all I'd like a 2nd confirmation on is if 
stripPointerCastsAndAliases() is the right thing to use here.

Nick or Alex, if you could have a brief look would be great -- thanks!

Thanks,

- Marco


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

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


[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-10 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/test/CodeGen/asan-globals-alias.cpp:30
+// KASAN: @aliased_global_2{{.*}} global i32
+// KASAN: @joydev_ids{{.*}} global [1 x {{.*}}i64 1234 }], align 16
 

nickdesaulniers wrote:
> Do we want to add checks for the aliases: `global_alias_2`, 
> `__global_alias_2_alias`, and `__mod_joydev_ids_device_table`?
I found that depending on optimization level, what the aliases end up aliasing 
varies (e.g. for the alias-of-alias at -O2 it turns it into an alias to the 
global_alias_2). Not sure how to best capture this in the test without it 
becoming flaky. I suppose we could check that the alias somehow references 
either what was specified directly or the final global, but I don't think 
that's the job of this test since it's not directly related to ASan or KASAN.

Or did you mean to just check they exist?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

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


[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-11 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 311157.
melver added a comment.

Check aliases exist in test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,7 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1787,22 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
   // In case this function should be expanded to include rules that do not just
   // apply when CompileKernel is true, either guard all existing rules with an
   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
   // should also apply to user space.
   assert(CompileKernel && "Only expecting to be called when compiling kernel");
 
+  const Constant *C = GA.getAliasee();
+
   // When compiling the kernel, globals that are aliased by symbols prefixed
   // by "__" are special and cannot be padded with a redzone.
   if (GA.getName().startswith("__"))
-return false;
+return dyn_cast(C->stripPointerCastsAndAliases());
 
-  return true;
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2254,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,42 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern int __attribute__((alias("aliased_global"))) __global_alias; // KASAN - aliased_global ignored
+int global; // generate ctor for at least 1 global
+int aliased_global; // KASAN ignored
+extern int __attribute__((alias("aliased_global"))) __global_alias;
+
+// Recursive alias:
+int aliased_global_2; // KASAN ignored
+extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
+extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
+
+// Potential indirect alias:
+struct input_device_id {
+  unsigned long keybit[24];
+  unsigned long driver_info;
+};
+struct input_device_id joydev_ids[] = { { {1}, 1234 } }; // KASAN ignored
+extern struct input_device_id __attribute__((alias("joydev_ids"))) __mod_joydev_ids_device_table;
 
 // ASAN: @aliased_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @aliased_global_2{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @joydev_ids{{.*}} global { {{.*}}[56 x i8] zeroinitializer }, align 32
 // KASAN: @aliased_global{{.*}} global i32
+// KASAN: @aliased_global_2{{.*}} global i32
+// KASAN: @joydev_ids{{.*}} global [1 x {{.*}}i64 1234 }], align 16
+
+// Check the aliases exist:
+// CHECK: @__global_alias = alias
+// CHECK: @global_alias_2 = alias
+// CHECK: @__glob

[PATCH] D92846: [KernelAddressSanitizer] Fix globals exclusion for indirect aliases

2020-12-11 Thread Marco Elver 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 rGc28b18af1962: [KernelAddressSanitizer] Fix globals exclusion 
for indirect aliases (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92846

Files:
  clang/test/CodeGen/asan-globals-alias.cpp
  llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp

Index: llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
===
--- llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -792,7 +792,7 @@
   StringRef InternalSuffix);
   Instruction *CreateAsanModuleDtor(Module &M);
 
-  bool canInstrumentAliasedGlobal(const GlobalAlias &GA) const;
+  const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
   bool shouldInstrumentGlobal(GlobalVariable *G) const;
   bool ShouldUseMachOGlobalsSection() const;
   StringRef getGlobalMetadataSection() const;
@@ -1787,20 +1787,22 @@
   }
 }
 
-bool ModuleAddressSanitizer::canInstrumentAliasedGlobal(
-const GlobalAlias &GA) const {
+const GlobalVariable *
+ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
   // In case this function should be expanded to include rules that do not just
   // apply when CompileKernel is true, either guard all existing rules with an
   // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
   // should also apply to user space.
   assert(CompileKernel && "Only expecting to be called when compiling kernel");
 
+  const Constant *C = GA.getAliasee();
+
   // When compiling the kernel, globals that are aliased by symbols prefixed
   // by "__" are special and cannot be padded with a redzone.
   if (GA.getName().startswith("__"))
-return false;
+return dyn_cast(C->stripPointerCastsAndAliases());
 
-  return true;
+  return nullptr;
 }
 
 bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
@@ -2252,14 +2254,12 @@
   *CtorComdat = false;
 
   // Build set of globals that are aliased by some GA, where
-  // canInstrumentAliasedGlobal(GA) returns false.
+  // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
   SmallPtrSet AliasedGlobalExclusions;
   if (CompileKernel) {
 for (auto &GA : M.aliases()) {
-  if (const auto *GV = dyn_cast(GA.getAliasee())) {
-if (!canInstrumentAliasedGlobal(GA))
-  AliasedGlobalExclusions.insert(GV);
-  }
+  if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
+AliasedGlobalExclusions.insert(GV);
 }
   }
 
Index: clang/test/CodeGen/asan-globals-alias.cpp
===
--- clang/test/CodeGen/asan-globals-alias.cpp
+++ clang/test/CodeGen/asan-globals-alias.cpp
@@ -1,17 +1,42 @@
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang_cc1 -triple x86_64-linux -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
+// RUN: %clang_cc1 -triple x86_64-linux -O2 -fsanitize=kernel-address -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,KASAN
 //
 // Not all platforms support aliases - test for Linux only.
 
-int global; // to generate ctor for at least 1 global
-int aliased_global; // KASAN - ignore globals prefixed by aliases with __-prefix (below)
-extern int __attribute__((alias("aliased_global"))) __global_alias; // KASAN - aliased_global ignored
+int global; // generate ctor for at least 1 global
+int aliased_global; // KASAN ignored
+extern int __attribute__((alias("aliased_global"))) __global_alias;
+
+// Recursive alias:
+int aliased_global_2; // KASAN ignored
+extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
+extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
+
+// Potential indirect alias:
+struct input_device_id {
+  unsigned long keybit[24];
+  unsigned long driver_info;
+};
+struct input_device_id joydev_ids[] = { { {1}, 1234 } }; // KASAN ignored
+extern struct input_device_id __attribute__((alias("joydev_ids"))) __mod_joydev_ids_device_table;
 
 // ASAN: @aliased_global{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @aliased_global_2{{.*}} global { i32, [60 x i8] }{{.*}}, align 32
+// ASAN: @joydev_ids{{.*}} global { {{.*}}[56 x i8] zeroinitializer }, align 32
 // KASAN: @aliased_global{{.*}} global i32
+// KASAN: @aliased_global_2{{.*}} global i32
+// KASAN: @joydev_ids{{.*}} glob

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added reviewers: vitalybuka, morehouse, glider, dvyukov.
Herald added subscribers: dexonsmith, jdoerfert, pengfei, hiraditya.
Herald added a reviewer: aaron.ballman.
melver requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

We really ought to support no_sanitize("coverage") in line with other
sanitizers. This came up again in discussions on the Linux-kernel
mailing lists, because we currently do workarounds using objtool to
remove coverage instrumentation. Since that support is only on x86, to
continue support coverage instrumentation on other architectures, we
must support selectively disabling coverage instrumentation via function
attributes.

Unfortunately, for SanitizeCoverage, it has not been implemented as a
sanitizer via fsanitize= and associated options in Sanitizers.def, but
rolls its own option fsanitize-coverage. This meant that we never got
"automatic" no_sanitize attribute support.

Implement no_sanitize attribute support by special-casing the string
"coverage" in the NoSanitizeAttr implementation. To keep the feature as
unintrusive to existing IR generation as possible, define a new negative
function attribute NoSanitizeCoverage to propagate the information
through to the instrumentation pass.

Fixes: https://bugs.llvm.org/show_bug.cgi?id=49035


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -954,6 +954,7 @@
   case Attribute::NonLazyBind:
   case Attribute::NoRedZone:
   case Attribute::NoUnwind:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::NullPointerIsValid:
   case Attribute::OptForFuzzing:
   case Attribute::OptimizeNone:
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -621,6 +621,8 @@
 return;
   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
 return;
+  if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
+return;
   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
   SmallVector IndirCalls;
Index: llvm/lib/IR/Verifier.cpp
===
--- llvm/lib/IR/Verifier.cpp
+++ llvm/lib/IR/Verifier.cpp
@@ -1661,6 +1661,7 @@
   case Attribute::NoCfCheck:
   case Attribute::NoUnwind:
   case Attribute::NoInline:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::AlwaysInline:
   case Attribute::OptimizeForSize:
   case Attribute::StackProtect:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -442,6 +442,8 @@
 return "noprofile";
   if (hasAttribute(Attribute::NoUnwind))
 return "nounwind";
+  if (hasAttribute(Attribute::NoSanitizeCoverage))
+return "no_sanitize_coverage";
   if (hasAttribute(Attribute::OptForFuzzing))
 return "optforfuzzing";
   if (hasAttribute(Attribute::OptimizeNone))
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -686,6 +686,8 @@
 return bitc::ATTR_KIND_NO_PROFILE;
   case Attribute::NoUnwind:
 return bitc::ATTR_KIND_NO_UNWIND;
+  case Attribute::NoSanitizeCoverage:
+return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
   case Attribute::NullPointerIsValid:
 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
   case Attribute::OptForFuzzing:
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1474,6 +1474,8 @@
 return Attribute::NoCfCheck;
   case bitc::ATTR_KIND_NO_UNWIND:
 return Attribute::NoUnwind;
+  case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
+return Attribute::NoSanitizeCoverage;
   case bitc::

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 346452.
melver marked 2 inline comments as done.
melver added a comment.

Address Aaron's comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -954,6 +954,7 @@
   case Attribute::NonLazyBind:
   case Attribute::NoRedZone:
   case Attribute::NoUnwind:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::NullPointerIsValid:
   case Attribute::OptForFuzzing:
   case Attribute::OptimizeNone:
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -621,6 +621,8 @@
 return;
   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
 return;
+  if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
+return;
   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
   SmallVector IndirCalls;
Index: llvm/lib/IR/Verifier.cpp
===
--- llvm/lib/IR/Verifier.cpp
+++ llvm/lib/IR/Verifier.cpp
@@ -1661,6 +1661,7 @@
   case Attribute::NoCfCheck:
   case Attribute::NoUnwind:
   case Attribute::NoInline:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::AlwaysInline:
   case Attribute::OptimizeForSize:
   case Attribute::StackProtect:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -442,6 +442,8 @@
 return "noprofile";
   if (hasAttribute(Attribute::NoUnwind))
 return "nounwind";
+  if (hasAttribute(Attribute::NoSanitizeCoverage))
+return "no_sanitize_coverage";
   if (hasAttribute(Attribute::OptForFuzzing))
 return "optforfuzzing";
   if (hasAttribute(Attribute::OptimizeNone))
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -686,6 +686,8 @@
 return bitc::ATTR_KIND_NO_PROFILE;
   case Attribute::NoUnwind:
 return bitc::ATTR_KIND_NO_UNWIND;
+  case Attribute::NoSanitizeCoverage:
+return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
   case Attribute::NullPointerIsValid:
 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
   case Attribute::OptForFuzzing:
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1474,6 +1474,8 @@
 return Attribute::NoCfCheck;
   case bitc::ATTR_KIND_NO_UNWIND:
 return Attribute::NoUnwind;
+  case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
+return Attribute::NoSanitizeCoverage;
   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
 return Attribute::NullPointerIsValid;
   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
Index: llvm/include/llvm/IR/Attributes.td
===
--- llvm/include/llvm/IR/Attributes.td
+++ llvm/include/llvm/IR/Attributes.td
@@ -154,6 +154,9 @@
 /// Function doesn't unwind stack.
 def NoUnwind : EnumAttr<"nounwind">;
 
+/// No SanitizeCoverage instrumentation.
+def NoSanitizeCoverage : EnumAttr<"no_sanitize_coverage">;
+
 /// Null pointer in address space zero is valid.
 def NullPointerIsValid : EnumAttr<"null_pointer_is_valid">;
 
Index: llvm/include/llvm/Bitcode/LLVMBitCodes.h
===
--- llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -666,6 +666,7 @@
   ATTR_KIND_NO_PROFILE = 73,
   ATTR_KIND_VSCALE_RANGE = 74,
   ATTR_KIND_SWIFT_ASYNC = 75,
+  ATTR_KIND_NO_SANITIZE_COVERAGE = 76,
 };
 
 enum ComdatSelectionKindCodes {
Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/Co

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 346484.
melver added a comment.

Test that always_inline works as expected with no_sanitize("coverage")


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp

Index: llvm/lib/Transforms/Utils/CodeExtractor.cpp
===
--- llvm/lib/Transforms/Utils/CodeExtractor.cpp
+++ llvm/lib/Transforms/Utils/CodeExtractor.cpp
@@ -954,6 +954,7 @@
   case Attribute::NonLazyBind:
   case Attribute::NoRedZone:
   case Attribute::NoUnwind:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::NullPointerIsValid:
   case Attribute::OptForFuzzing:
   case Attribute::OptimizeNone:
Index: llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
===
--- llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -621,6 +621,8 @@
 return;
   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
 return;
+  if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
+return;
   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
   SmallVector IndirCalls;
Index: llvm/lib/IR/Verifier.cpp
===
--- llvm/lib/IR/Verifier.cpp
+++ llvm/lib/IR/Verifier.cpp
@@ -1661,6 +1661,7 @@
   case Attribute::NoCfCheck:
   case Attribute::NoUnwind:
   case Attribute::NoInline:
+  case Attribute::NoSanitizeCoverage:
   case Attribute::AlwaysInline:
   case Attribute::OptimizeForSize:
   case Attribute::StackProtect:
Index: llvm/lib/IR/Attributes.cpp
===
--- llvm/lib/IR/Attributes.cpp
+++ llvm/lib/IR/Attributes.cpp
@@ -442,6 +442,8 @@
 return "noprofile";
   if (hasAttribute(Attribute::NoUnwind))
 return "nounwind";
+  if (hasAttribute(Attribute::NoSanitizeCoverage))
+return "no_sanitize_coverage";
   if (hasAttribute(Attribute::OptForFuzzing))
 return "optforfuzzing";
   if (hasAttribute(Attribute::OptimizeNone))
Index: llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
===
--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -686,6 +686,8 @@
 return bitc::ATTR_KIND_NO_PROFILE;
   case Attribute::NoUnwind:
 return bitc::ATTR_KIND_NO_UNWIND;
+  case Attribute::NoSanitizeCoverage:
+return bitc::ATTR_KIND_NO_SANITIZE_COVERAGE;
   case Attribute::NullPointerIsValid:
 return bitc::ATTR_KIND_NULL_POINTER_IS_VALID;
   case Attribute::OptForFuzzing:
Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp
===
--- llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1474,6 +1474,8 @@
 return Attribute::NoCfCheck;
   case bitc::ATTR_KIND_NO_UNWIND:
 return Attribute::NoUnwind;
+  case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
+return Attribute::NoSanitizeCoverage;
   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
 return Attribute::NullPointerIsValid;
   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
Index: llvm/include/llvm/IR/Attributes.td
===
--- llvm/include/llvm/IR/Attributes.td
+++ llvm/include/llvm/IR/Attributes.td
@@ -154,6 +154,9 @@
 /// Function doesn't unwind stack.
 def NoUnwind : EnumAttr<"nounwind">;
 
+/// No SanitizeCoverage instrumentation.
+def NoSanitizeCoverage : EnumAttr<"no_sanitize_coverage">;
+
 /// Null pointer in address space zero is valid.
 def NullPointerIsValid : EnumAttr<"null_pointer_is_valid">;
 
Index: llvm/include/llvm/Bitcode/LLVMBitCodes.h
===
--- llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -666,6 +666,7 @@
   ATTR_KIND_NO_PROFILE = 73,
   ATTR_KIND_VSCALE_RANGE = 74,
   ATTR_KIND_SWIFT_ASYNC = 75,
+  ATTR_KIND_NO_SANITIZE_COVERAGE = 76,
 };
 
 enum ComdatSelectionKindCodes {
Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/te

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:7276-7278
 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
-SanitizerMask())
+SanitizerMask() &&
+SanitizerName != "coverage")

aaron.ballman wrote:
> The formatting looks rather off here to my eyes, but if this is what 
> clang-format produces for you, then I'm fine with it.
Yeah, I had something else here, but then clang-format suggested this and I 
don't like it either.

Could remove the /*AllowGroups=*/ bit, for the sake of formatting better?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

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


[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-19 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 346577.
melver added a comment.
Herald added a subscriber: steven_wu.

Rest of long-tail of IR changes related to introducing a new attributes...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/bindings/go/llvm/ir_test.go
  llvm/docs/BitCodeFormat.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/AsmParser/LLToken.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp
  llvm/test/Bitcode/attributes.ll
  llvm/test/Bitcode/compatibility.ll
  llvm/utils/emacs/llvm-mode.el
  llvm/utils/llvm.grm
  llvm/utils/vim/syntax/llvm.vim
  llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml

Index: llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
===
--- llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
+++ llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
@@ -237,6 +237,7 @@
 \\bnosync\\b|\
 \\bnoundef\\b|\
 \\bnounwind\\b|\
+\\bno_sanitize_coverage\\b|\
 \\bnull_pointer_is_valid\\b|\
 \\boptforfuzzing\\b|\
 \\boptnone\\b|\
Index: llvm/utils/vim/syntax/llvm.vim
===
--- llvm/utils/vim/syntax/llvm.vim
+++ llvm/utils/vim/syntax/llvm.vim
@@ -138,6 +138,7 @@
   \ nosync
   \ noundef
   \ nounwind
+  \ no_sanitize_coverage
   \ null_pointer_is_valid
   \ optforfuzzing
   \ optnone
Index: llvm/utils/llvm.grm
===
--- llvm/utils/llvm.grm
+++ llvm/utils/llvm.grm
@@ -176,6 +176,7 @@
  | sanitize_thread
  | sanitize_memory
  | mustprogress
+ | no_sanitize_coverage
  ;
 
 OptFuncAttrs  ::= + _ | OptFuncAttrs FuncAttr ;
Index: llvm/utils/emacs/llvm-mode.el
===
--- llvm/utils/emacs/llvm-mode.el
+++ llvm/utils/emacs/llvm-mode.el
@@ -25,7 +25,7 @@
'("alwaysinline" "argmemonly" "allocsize" "builtin" "cold" "convergent" "dereferenceable" "dereferenceable_or_null" "hot" "inaccessiblememonly"
  "inaccessiblemem_or_argmemonly" "inalloca" "inlinehint" "jumptable" "minsize" "mustprogress" "naked" "nobuiltin" "nonnull"
  "nocallback" "nocf_check" "noduplicate" "nofree" "noimplicitfloat" "noinline" "nomerge" "nonlazybind" "noprofile" "noredzone" "noreturn"
- "norecurse" "nosync" "noundef" "nounwind" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
+ "norecurse" "nosync" "noundef" "nounwind" "no_sanitize_coverage" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
  "shadowcallstack" "speculatable" "speculative_load_hardening" "ssp" "sspreq" "sspstrong" "safestack" "sanitize_address" "sanitize_hwaddress" "sanitize_memtag"
  "sanitize_thread" "sanitize_memory" "strictfp" "swifterror" "uwtable" "vscale_range" "willreturn" "writeonly" "immarg") 'symbols) . font-lock-constant-face)
;; Variables
Index: llvm/test/Bitcode/compatibility.ll
===
--- llvm/test/Bitcode/compatibility.ll
+++ llvm/test/Bitcode/compatibility.ll
@@ -1510,7 +1510,7 @@
   ; CHECK: select <2 x i1> , <2 x i8> , <2 x i8> 
 
   call void @f.nobuiltin() builtin
-  ; CHECK: call void @f.nobuiltin() #44
+  ; CHECK: call void @f.nobuiltin() #45
 
   call fastcc noalias i32* @f.noalias() noinline
   ; CHECK: call fastcc noalias i32* @f.noalias() #12
@@ -1904,6 +1904,9 @@
   ret void
 }
 
+declare void @f.no_sanitize_coverage() no_sanitize_coverage
+; CHECK: declare void @f.no_sanitize_coverage() #44
+
 ; immarg attribute
 declare void @llvm.test.immarg.intrinsic(i32 immarg)
 ; CHECK: declare void @llvm.test.immarg.intrinsic(i32 immarg)
@@ -1961,7 +1964,8 @@
 ; CHECK: attributes #41 = { writeonly }
 ; CHECK: attributes #42 = { speculatable }
 ; CHECK: attributes #43 = { strictfp }
-; CHECK: attributes #44 = { builtin }
+; CHECK: attributes #44 = { no_sanitize_coverage }
+; CHECK: attributes #45 = { builtin }
 
 ;; Metadata
 
Index: llvm/test/Bitcode/attributes.ll
===

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/test/CodeGen/sanitize-coverage.c:23-87
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) 
{
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc

vitalybuka wrote:
> you are adding tests for unrelated code.
> Could you please land is as a separate NFC patch first?
Which bits in particular? Just the 


```
static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) {
  if (n)
x[n] = 42;
}
// CHECK-LABEL: define dso_local void @test_always_inline(
void test_always_inline(int n) {
  // CHECK-DAG: call void @__sanitizer_cov_trace_pc
  // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
  always_inlined_fn(n);
}
```

part?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

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


[PATCH] D102927: [NFC][CodeGenOptions] Refactor checking SanitizeCoverage options

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: vitalybuka.
Herald added a subscriber: dexonsmith.
melver requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Refactor checking SanitizeCoverage options into
CodeGenOptions::hasSanitizeCoverage().


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D102927

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/CodeGen/BackendUtil.cpp


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -736,9 +736,7 @@
addBoundsCheckingPass);
   }
 
-  if (CodeGenOpts.SanitizeCoverageType ||
-  CodeGenOpts.SanitizeCoverageIndirectCalls ||
-  CodeGenOpts.SanitizeCoverageTraceCmp) {
+  if (CodeGenOpts.hasSanitizeCoverage()) {
 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
addSanitizerCoveragePass);
 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
@@ -1108,9 +1106,7 @@
   const LangOptions &LangOpts, PassBuilder &PB) {
   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
  PassBuilder::OptimizationLevel Level) 
{
-if (CodeGenOpts.SanitizeCoverageType ||
-CodeGenOpts.SanitizeCoverageIndirectCalls ||
-CodeGenOpts.SanitizeCoverageTraceCmp) {
+if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(ModuleSanitizerCoveragePass(
   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -452,6 +452,12 @@
   bool hasMaybeUnusedDebugInfo() const {
 return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
   }
+
+  // Check if any one of SanitizeCoverage* is enabled.
+  bool hasSanitizeCoverage() const {
+return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
+   SanitizeCoverageTraceCmp;
+  }
 };
 
 }  // end namespace clang


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -736,9 +736,7 @@
addBoundsCheckingPass);
   }
 
-  if (CodeGenOpts.SanitizeCoverageType ||
-  CodeGenOpts.SanitizeCoverageIndirectCalls ||
-  CodeGenOpts.SanitizeCoverageTraceCmp) {
+  if (CodeGenOpts.hasSanitizeCoverage()) {
 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
addSanitizerCoveragePass);
 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
@@ -1108,9 +1106,7 @@
   const LangOptions &LangOpts, PassBuilder &PB) {
   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
  PassBuilder::OptimizationLevel Level) {
-if (CodeGenOpts.SanitizeCoverageType ||
-CodeGenOpts.SanitizeCoverageIndirectCalls ||
-CodeGenOpts.SanitizeCoverageTraceCmp) {
+if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(ModuleSanitizerCoveragePass(
   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -452,6 +452,12 @@
   bool hasMaybeUnusedDebugInfo() const {
 return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
   }
+
+  // Check if any one of SanitizeCoverage* is enabled.
+  bool hasSanitizeCoverage() const {
+return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
+   SanitizeCoverageTraceCmp;
+  }
 };
 
 }  // end namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102929: [NFC][SanitizeCoverage] Test always_inline functions work

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added a reviewer: vitalybuka.
melver requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Test that always_inline functions are instrumented as expected.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D102929

Files:
  clang/test/CodeGen/sanitize-coverage.c


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -19,4 +19,16 @@
   if (n)
 x[n] = 42;
 }
+
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) 
{
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc
+  // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
+  always_inlined_fn(n);
+}
+
 // CHECK-LABEL: declare void


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -19,4 +19,16 @@
   if (n)
 x[n] = 42;
 }
+
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) {
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc
+  // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
+  always_inlined_fn(n);
+}
+
 // CHECK-LABEL: declare void
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 347062.
melver marked 3 inline comments as done.
melver added a comment.

- Refactor test and SanitizeCoverage* checking.
- s/no_sanitize_coverage/nosanitize_coverage/

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/bindings/go/llvm/ir_test.go
  llvm/docs/BitCodeFormat.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/AsmParser/LLToken.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp
  llvm/test/Bitcode/attributes.ll
  llvm/test/Bitcode/compatibility.ll
  llvm/utils/emacs/llvm-mode.el
  llvm/utils/llvm.grm
  llvm/utils/vim/syntax/llvm.vim
  llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml

Index: llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
===
--- llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
+++ llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
@@ -237,6 +237,7 @@
 \\bnosync\\b|\
 \\bnoundef\\b|\
 \\bnounwind\\b|\
+\\bnosanitize_coverage\\b|\
 \\bnull_pointer_is_valid\\b|\
 \\boptforfuzzing\\b|\
 \\boptnone\\b|\
Index: llvm/utils/vim/syntax/llvm.vim
===
--- llvm/utils/vim/syntax/llvm.vim
+++ llvm/utils/vim/syntax/llvm.vim
@@ -138,6 +138,7 @@
   \ nosync
   \ noundef
   \ nounwind
+  \ nosanitize_coverage
   \ null_pointer_is_valid
   \ optforfuzzing
   \ optnone
Index: llvm/utils/llvm.grm
===
--- llvm/utils/llvm.grm
+++ llvm/utils/llvm.grm
@@ -176,6 +176,7 @@
  | sanitize_thread
  | sanitize_memory
  | mustprogress
+ | nosanitize_coverage
  ;
 
 OptFuncAttrs  ::= + _ | OptFuncAttrs FuncAttr ;
Index: llvm/utils/emacs/llvm-mode.el
===
--- llvm/utils/emacs/llvm-mode.el
+++ llvm/utils/emacs/llvm-mode.el
@@ -25,7 +25,7 @@
'("alwaysinline" "argmemonly" "allocsize" "builtin" "cold" "convergent" "dereferenceable" "dereferenceable_or_null" "hot" "inaccessiblememonly"
  "inaccessiblemem_or_argmemonly" "inalloca" "inlinehint" "jumptable" "minsize" "mustprogress" "naked" "nobuiltin" "nonnull"
  "nocallback" "nocf_check" "noduplicate" "nofree" "noimplicitfloat" "noinline" "nomerge" "nonlazybind" "noprofile" "noredzone" "noreturn"
- "norecurse" "nosync" "noundef" "nounwind" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
+ "norecurse" "nosync" "noundef" "nounwind" "nosanitize_coverage" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
  "shadowcallstack" "speculatable" "speculative_load_hardening" "ssp" "sspreq" "sspstrong" "safestack" "sanitize_address" "sanitize_hwaddress" "sanitize_memtag"
  "sanitize_thread" "sanitize_memory" "strictfp" "swifterror" "uwtable" "vscale_range" "willreturn" "writeonly" "immarg") 'symbols) . font-lock-constant-face)
;; Variables
Index: llvm/test/Bitcode/compatibility.ll
===
--- llvm/test/Bitcode/compatibility.ll
+++ llvm/test/Bitcode/compatibility.ll
@@ -1510,7 +1510,7 @@
   ; CHECK: select <2 x i1> , <2 x i8> , <2 x i8> 
 
   call void @f.nobuiltin() builtin
-  ; CHECK: call void @f.nobuiltin() #44
+  ; CHECK: call void @f.nobuiltin() #45
 
   call fastcc noalias i32* @f.noalias() noinline
   ; CHECK: call fastcc noalias i32* @f.noalias() #12
@@ -1904,6 +1904,9 @@
   ret void
 }
 
+declare void @f.nosanitize_coverage() nosanitize_coverage
+; CHECK: declare void @f.nosanitize_coverage() #44
+
 ; immarg attribute
 declare void @llvm.test.immarg.intrinsic(i32 immarg)
 ; CHECK: declare void @llvm.test.immarg.intrinsic(i32 immarg)
@@ -1961,7 +1964,8 @@
 ; CHECK: attributes #41 = { writeonly }
 ; CHECK: attributes #42 = { speculatable }
 ; CHECK: attributes #43 = { strictfp }
-; CHECK: attributes #44 = { builtin }
+; CHECK: attributes #44 = { nosanitize_coverage }
+; CHECK: attributes #45 = { builtin }
 
 ;; Metadata
 
Index: llvm/test/Bitcode/attributes.ll

[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:757-760
+bool HaveSanitizeCoverage =
+CGM.getCodeGenOpts().SanitizeCoverageType ||
+CGM.getCodeGenOpts().SanitizeCoverageIndirectCalls ||
+CGM.getCodeGenOpts().SanitizeCoverageTraceCmp;

vitalybuka wrote:
> consider adding method into CodeGenOptions and replace here and and the rest 
> ideally in a separate patch
> 
https://reviews.llvm.org/D102927



Comment at: clang/test/CodeGen/sanitize-coverage.c:23-87
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) 
{
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc

melver wrote:
> vitalybuka wrote:
> > you are adding tests for unrelated code.
> > Could you please land is as a separate NFC patch first?
> Which bits in particular? Just the 
> 
> 
> ```
> static inline __attribute__((__always_inline__)) void always_inlined_fn(int 
> n) {
>   if (n)
> x[n] = 42;
> }
> // CHECK-LABEL: define dso_local void @test_always_inline(
> void test_always_inline(int n) {
>   // CHECK-DAG: call void @__sanitizer_cov_trace_pc
>   // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
>   always_inlined_fn(n);
> }
> ```
> 
> part?
https://reviews.llvm.org/D102929



Comment at: llvm/lib/AsmParser/LLLexer.cpp:674
   KEYWORD(nounwind);
+  KEYWORD(no_sanitize_coverage);
   KEYWORD(null_pointer_is_valid);

vitalybuka wrote:
> looking at the rest, seems "nosanitize_coverage" follows pattern better :)
I wasn't sure myself, it's a bit inconsistent with "no_sanitize", but I've 
changed it. ;-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

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


[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-21 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

Please have a look at the other 2 patches which are now a dependency for this. 
Once you're happy with all 3 I'll push them all together.
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

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


[PATCH] D102927: [NFC][CodeGenOptions] Refactor checking SanitizeCoverage options

2021-05-25 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGca6df734069a: [NFC][CodeGenOptions] Refactor checking 
SanitizeCoverage options (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102927

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/lib/CodeGen/BackendUtil.cpp


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -727,9 +727,7 @@
addBoundsCheckingPass);
   }
 
-  if (CodeGenOpts.SanitizeCoverageType ||
-  CodeGenOpts.SanitizeCoverageIndirectCalls ||
-  CodeGenOpts.SanitizeCoverageTraceCmp) {
+  if (CodeGenOpts.hasSanitizeCoverage()) {
 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
addSanitizerCoveragePass);
 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
@@ -1099,9 +1097,7 @@
   const LangOptions &LangOpts, PassBuilder &PB) {
   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
  PassBuilder::OptimizationLevel Level) 
{
-if (CodeGenOpts.SanitizeCoverageType ||
-CodeGenOpts.SanitizeCoverageIndirectCalls ||
-CodeGenOpts.SanitizeCoverageTraceCmp) {
+if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(ModuleSanitizerCoveragePass(
   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -452,6 +452,12 @@
   bool hasMaybeUnusedDebugInfo() const {
 return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
   }
+
+  // Check if any one of SanitizeCoverage* is enabled.
+  bool hasSanitizeCoverage() const {
+return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
+   SanitizeCoverageTraceCmp;
+  }
 };
 
 }  // end namespace clang


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -727,9 +727,7 @@
addBoundsCheckingPass);
   }
 
-  if (CodeGenOpts.SanitizeCoverageType ||
-  CodeGenOpts.SanitizeCoverageIndirectCalls ||
-  CodeGenOpts.SanitizeCoverageTraceCmp) {
+  if (CodeGenOpts.hasSanitizeCoverage()) {
 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
addSanitizerCoveragePass);
 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
@@ -1099,9 +1097,7 @@
   const LangOptions &LangOpts, PassBuilder &PB) {
   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
  PassBuilder::OptimizationLevel Level) {
-if (CodeGenOpts.SanitizeCoverageType ||
-CodeGenOpts.SanitizeCoverageIndirectCalls ||
-CodeGenOpts.SanitizeCoverageTraceCmp) {
+if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(ModuleSanitizerCoveragePass(
   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
Index: clang/include/clang/Basic/CodeGenOptions.h
===
--- clang/include/clang/Basic/CodeGenOptions.h
+++ clang/include/clang/Basic/CodeGenOptions.h
@@ -452,6 +452,12 @@
   bool hasMaybeUnusedDebugInfo() const {
 return getDebugInfo() >= codegenoptions::UnusedTypeInfo;
   }
+
+  // Check if any one of SanitizeCoverage* is enabled.
+  bool hasSanitizeCoverage() const {
+return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
+   SanitizeCoverageTraceCmp;
+  }
 };
 
 }  // end namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102929: [NFC][SanitizeCoverage] Test always_inline functions work

2021-05-25 Thread Marco Elver via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG85feebf5a340: [NFC][SanitizeCoverage] Test always_inline 
functions work (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102929

Files:
  clang/test/CodeGen/sanitize-coverage.c


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -19,4 +19,16 @@
   if (n)
 x[n] = 42;
 }
+
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) 
{
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc
+  // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
+  always_inlined_fn(n);
+}
+
 // CHECK-LABEL: declare void


Index: clang/test/CodeGen/sanitize-coverage.c
===
--- clang/test/CodeGen/sanitize-coverage.c
+++ clang/test/CodeGen/sanitize-coverage.c
@@ -19,4 +19,16 @@
   if (n)
 x[n] = 42;
 }
+
+static inline __attribute__((__always_inline__)) void always_inlined_fn(int n) {
+  if (n)
+x[n] = 42;
+}
+// CHECK-LABEL: define dso_local void @test_always_inline(
+void test_always_inline(int n) {
+  // CHECK-DAG: call void @__sanitizer_cov_trace_pc
+  // CHECK-DAG: call void @__sanitizer_cov_trace_const_cmp
+  always_inlined_fn(n);
+}
+
 // CHECK-LABEL: declare void
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D102772: [SanitizeCoverage] Add support for NoSanitizeCoverage function attribute

2021-05-25 Thread Marco Elver 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 rG280333021e95: [SanitizeCoverage] Add support for 
NoSanitizeCoverage function attribute (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102772

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/sanitize-coverage.c
  llvm/bindings/go/llvm/ir_test.go
  llvm/docs/BitCodeFormat.rst
  llvm/docs/LangRef.rst
  llvm/include/llvm/AsmParser/LLToken.h
  llvm/include/llvm/Bitcode/LLVMBitCodes.h
  llvm/include/llvm/IR/Attributes.td
  llvm/lib/AsmParser/LLLexer.cpp
  llvm/lib/AsmParser/LLParser.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
  llvm/lib/IR/Attributes.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Transforms/IPO/ForceFunctionAttrs.cpp
  llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
  llvm/lib/Transforms/Utils/CodeExtractor.cpp
  llvm/test/Bitcode/attributes.ll
  llvm/test/Bitcode/compatibility.ll
  llvm/utils/emacs/llvm-mode.el
  llvm/utils/llvm.grm
  llvm/utils/vim/syntax/llvm.vim
  llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml

Index: llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
===
--- llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
+++ llvm/utils/vscode/llvm/syntaxes/ll.tmLanguage.yaml
@@ -237,6 +237,7 @@
 \\bnosync\\b|\
 \\bnoundef\\b|\
 \\bnounwind\\b|\
+\\bnosanitize_coverage\\b|\
 \\bnull_pointer_is_valid\\b|\
 \\boptforfuzzing\\b|\
 \\boptnone\\b|\
Index: llvm/utils/vim/syntax/llvm.vim
===
--- llvm/utils/vim/syntax/llvm.vim
+++ llvm/utils/vim/syntax/llvm.vim
@@ -138,6 +138,7 @@
   \ nosync
   \ noundef
   \ nounwind
+  \ nosanitize_coverage
   \ null_pointer_is_valid
   \ optforfuzzing
   \ optnone
Index: llvm/utils/llvm.grm
===
--- llvm/utils/llvm.grm
+++ llvm/utils/llvm.grm
@@ -176,6 +176,7 @@
  | sanitize_thread
  | sanitize_memory
  | mustprogress
+ | nosanitize_coverage
  ;
 
 OptFuncAttrs  ::= + _ | OptFuncAttrs FuncAttr ;
Index: llvm/utils/emacs/llvm-mode.el
===
--- llvm/utils/emacs/llvm-mode.el
+++ llvm/utils/emacs/llvm-mode.el
@@ -25,7 +25,7 @@
'("alwaysinline" "argmemonly" "allocsize" "builtin" "cold" "convergent" "dereferenceable" "dereferenceable_or_null" "hot" "inaccessiblememonly"
  "inaccessiblemem_or_argmemonly" "inalloca" "inlinehint" "jumptable" "minsize" "mustprogress" "naked" "nobuiltin" "nonnull"
  "nocallback" "nocf_check" "noduplicate" "nofree" "noimplicitfloat" "noinline" "nomerge" "nonlazybind" "noprofile" "noredzone" "noreturn"
- "norecurse" "nosync" "noundef" "nounwind" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
+ "norecurse" "nosync" "noundef" "nounwind" "nosanitize_coverage" "null_pointer_is_valid" "optforfuzzing" "optnone" "optsize" "preallocated" "readnone" "readonly" "returned" "returns_twice"
  "shadowcallstack" "speculatable" "speculative_load_hardening" "ssp" "sspreq" "sspstrong" "safestack" "sanitize_address" "sanitize_hwaddress" "sanitize_memtag"
  "sanitize_thread" "sanitize_memory" "strictfp" "swifterror" "uwtable" "vscale_range" "willreturn" "writeonly" "immarg") 'symbols) . font-lock-constant-face)
;; Variables
Index: llvm/test/Bitcode/compatibility.ll
===
--- llvm/test/Bitcode/compatibility.ll
+++ llvm/test/Bitcode/compatibility.ll
@@ -1510,7 +1510,7 @@
   ; CHECK: select <2 x i1> , <2 x i8> , <2 x i8> 
 
   call void @f.nobuiltin() builtin
-  ; CHECK: call void @f.nobuiltin() #44
+  ; CHECK: call void @f.nobuiltin() #45
 
   call fastcc noalias i32* @f.noalias() noinline
   ; CHECK: call fastcc noalias i32* @f.noalias() #12
@@ -1904,6 +1904,9 @@
   ret void
 }
 
+declare void @f.nosanitize_coverage() nosanitize_coverage
+; CHECK: declare void @f.nosanitize_coverage() #44
+
 ; immarg attribute
 declare void @llvm.test.immarg.intrinsic(i32 immarg)
 ; CHECK: declare void @llvm.test.immarg.intrinsic(i32 immarg)
@@ -1961,7 +1964,8 @@
 ; CHECK: attributes #41 = { writeonly }
 ; CHECK: attributes #42 = { speculatable }
 ; CHECK: attributes #43 = { strictfp }
-; CHECK: attributes #44 = { builtin }
+; CHECK: attributes #44 = { nosanitize_coverage }
+; CHECK: attributes #45 = { builtin }
 
 ;; Metadata
 
Index: llvm/test/Bitcod

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
melver added reviewers: aaron.ballman, vitalybuka, morehouse, nickdesaulniers.
Herald added a subscriber: dexonsmith.
melver requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Like other sanitizers, enable __has_feature(coverage_sanitizer) if clang
has enabled at least one SanitizerCoverage instrumentation type.

Because coverage instrumentation selection is not handled via normal
-fsanitize= (and thus not in SanitizeSet), passing this information
through to LangOptions required propagating the already parsed
-fsanitize-coverage= options from CodeGenOptions through to LangOptions
in FixupInvocation().


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103159

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Lexer/has_feature_coverage_sanitizer.cpp


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)
Index: clang/docs/SanitizerCoverage.rst
===
--- clang/docs/SanitizerCoverage.rst
+++ clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. This attribute
+may not be supported by other compilers, and suggest to use it together with
+``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang 

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 347936.
melver added a comment.

Documentation wording.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Lexer/has_feature_coverage_sanitizer.cpp


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)
Index: clang/docs/SanitizerCoverage.rst
===
--- clang/docs/SanitizerCoverage.rst
+++ clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. Since this
+attribute may not be supported by other compilers, it is recommended to use it
+together with ``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
=

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/include/clang/Basic/Features.def:52
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)

aaron.ballman wrote:
> I think this is likely fine, but wanted to call it out explicitly in case 
> others had opinions.
> 
> `FEATURE` is supposed to be used for standard features and `EXTENSION` used 
> for Clang extensions. This is an extension, not a standard feature, so it's 
> wrong in that way. However, it's following the same pattern as the other 
> sanitizers which is consistent. I think consistently wrong is better than 
> inconsistently right for this case, but I have no idea how others feel.
Yes, you are correct of course, and I was pondering the same thing.

In the end I'd like all sanitizers be queryable via `__has_feature()` and not 
have this be the odd one out requiring `__has_extension()` as that's also going 
to lead to confusion/errors on the user side. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver updated this revision to Diff 348021.
melver marked an inline comment as done.
melver added a comment.

s/Since/Because/


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Lexer/has_feature_coverage_sanitizer.cpp


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)
Index: clang/docs/SanitizerCoverage.rst
===
--- clang/docs/SanitizerCoverage.rst
+++ clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. Because this
+attribute may not be supported by other compilers, it is recommended to use it
+together with ``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-26 Thread Marco Elver via Phabricator via cfe-commits
melver added inline comments.



Comment at: clang/include/clang/Basic/Features.def:52
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)

ojeda wrote:
> melver wrote:
> > aaron.ballman wrote:
> > > I think this is likely fine, but wanted to call it out explicitly in case 
> > > others had opinions.
> > > 
> > > `FEATURE` is supposed to be used for standard features and `EXTENSION` 
> > > used for Clang extensions. This is an extension, not a standard feature, 
> > > so it's wrong in that way. However, it's following the same pattern as 
> > > the other sanitizers which is consistent. I think consistently wrong is 
> > > better than inconsistently right for this case, but I have no idea how 
> > > others feel.
> > Yes, you are correct of course, and I was pondering the same thing.
> > 
> > In the end I'd like all sanitizers be queryable via `__has_feature()` and 
> > not have this be the odd one out requiring `__has_extension()` as that's 
> > also going to lead to confusion/errors on the user side. 
> Perhaps add both, deprecate `__has_feature()` for non-standard features like 
> these ones, and remove them after a couple releases? :)
> 
> Regardless of the way, //any// is better than a version check, so thanks!
I think realistically we have to pick one, and that's the one we keep for all 
eternity. :-)

Because if we deprecate/remove something, some codebases would require version 
checks, which is a non-starter again. Not every project is on top of what their 
compilers deprecates/removes. (And, unlike the Linux kernel, some codebases 
just never upgrade their compiler requirements, but still expect newer 
compilers to work.)

So if we want consistency with other sanitizers, it has to be `__has_feature()`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver marked 3 inline comments as done.
melver added a comment.

Ping.

To reviewers: Do note the `feature` vs. `extension` discussion.
Summary: We think to be consistent with other sanitizers and avoid confusion, 
we must make this a `feature`, too.

Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver 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 rG4fbc66cd6d90: [Clang] Enable 
__has_feature(coverage_sanitizer) (authored by melver).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

Files:
  clang/docs/SanitizerCoverage.rst
  clang/include/clang/Basic/Features.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Lexer/has_feature_coverage_sanitizer.cpp


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck 
--check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCOV: SancovEnabled
+// CHECK-NO-SANCOV: SancovDisabled
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -453,7 +453,7 @@
   CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
   CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
   FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
-
+  LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
   LangOpts.CurrentModule = LangOpts.ModuleName;
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -280,6 +280,8 @@
 
   /// Set of enabled sanitizers.
   SanitizerSet Sanitize;
+  /// Is at least one coverage instrumentation type enabled.
+  bool SanitizeCoverage = false;
 
   /// Paths to files specifying which objects
   /// (files, functions, variables) should not be instrumented.
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -49,6 +49,7 @@
 FEATURE(xray_instrument, LangOpts.XRayInstrument)
 FEATURE(undefined_behavior_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Undefined))
+FEATURE(coverage_sanitizer, LangOpts.SanitizeCoverage)
 FEATURE(assume_nonnull, true)
 FEATURE(attribute_analyzer_noreturn, true)
 FEATURE(attribute_availability, true)
Index: clang/docs/SanitizerCoverage.rst
===
--- clang/docs/SanitizerCoverage.rst
+++ clang/docs/SanitizerCoverage.rst
@@ -316,7 +316,9 @@
 ===
 
 It is possible to disable coverage instrumentation for select functions via the
-function attribute ``__attribute__((no_sanitize("coverage")))``.
+function attribute ``__attribute__((no_sanitize("coverage")))``. Because this
+attribute may not be supported by other compilers, it is recommended to use it
+together with ``__has_feature(coverage_sanitizer)``.
 
 Disabling instrumentation without source modification
 =


Index: clang/test/Lexer/has_feature_coverage_sanitizer.cpp
===
--- /dev/null
+++ clang/test/Lexer/has_feature_coverage_sanitizer.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang -E -fsanitize-coverage=indirect-calls %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=inline-8bit-counters %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-cmp %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E -fsanitize-coverage=trace-pc-guard %s -o - | FileCheck --check-prefix=CHECK-SANCOV %s
+// RUN: %clang -E  %s -o - | FileCheck --check-prefix=CHECK-NO-SANCOV %s
+
+#if __has_feature(coverage_sanitizer)
+int SancovEnabled();
+#else
+int SancovDisabled();
+#endif
+
+// CHECK-SANCO

[PATCH] D103159: [Clang] Enable __has_feature(coverage_sanitizer)

2021-05-27 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D103159#2784926 , @aaron.ballman 
wrote:

> In D103159#2784845 , @melver wrote:
>
>> Ping.
>
> FWIW, the usual practice is to ping after no activity on the review for about 
> a week.
>
> That said, LGTM!

Thanks! And sorry for the early Ping. 
We had an earlier version of a patch using the no_sanitize("coverage") 
attribute in Linux -next and it was causing build robots to complain because 
they somehow want to use a pre-release of Clang 13 (they probably shouldn't, 
and also probably not a big deal about them suddenly crashing as they should 
just upgrade).
In any case, I thought we should get this fixed sooner than later -- and I just 
sent this: https://lkml.kernel.org/r/20210527162655.3246381-1-el...@google.com


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103159

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


[PATCH] D103958: [WIP] Support MustControl conditional control attribute

2021-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver created this revision.
Herald added subscribers: dexonsmith, jfb, hiraditya.
Herald added a reviewer: aaron.ballman.
melver requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, jdoerfert.
Herald added projects: clang, LLVM.

[ WIP, only high-level comments for now ]

Introduce a new attribute, 'MustControl'/'mustcontrol', which denotes that a
conditional control statement must result in true control-flow and not
be optimized away. The attribute otherwise has no semantic relevance.

However, the existence of a true branch is of relevance when branch
execution has side-effects on machine state that the programmer is
interested in, for example in OS kernels.

The Linux kernel, for one, relies on the existence of true conditional
branches for the enforcement of memory orders, per Linux-kernel memory
consistency model (LKMM) [1]. With the 'mustcontrol' attribute, Clang
would provide a primitive required for the Linux kernel to ensure a true
branch is emitted without resorting to inline assembly (which often
results in poor codegen). The primitive is simple and low-level enough,
that the compiler can remain blissfully unaware of the LKMM and leave
the semantics of Linux's memory model to the kernel community.

[1] https://lkml.kernel.org/r/yln8dzbnwvqrq...@hirez.programming.kicks-ass.net


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103958

Files:
  clang/include/clang/Basic/Attr.td
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/CodeGenCXX/attr-mustcontrol.cpp
  llvm/include/llvm/IR/FixedMetadataKinds.def
  llvm/include/llvm/IR/IRBuilder.h
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/IR/MDBuilder.h
  llvm/lib/CodeGen/BranchFolding.cpp
  llvm/lib/IR/IRBuilder.cpp
  llvm/lib/IR/MDBuilder.cpp

Index: llvm/lib/IR/MDBuilder.cpp
===
--- llvm/lib/IR/MDBuilder.cpp
+++ llvm/lib/IR/MDBuilder.cpp
@@ -56,6 +56,8 @@
   return MDNode::get(Context, None);
 }
 
+MDNode *MDBuilder::createMustControl() { return MDNode::get(Context, None); }
+
 MDNode *MDBuilder::createFunctionEntryCount(
 uint64_t Count, bool Synthetic,
 const DenseSet *Imports) {
Index: llvm/lib/IR/IRBuilder.cpp
===
--- llvm/lib/IR/IRBuilder.cpp
+++ llvm/lib/IR/IRBuilder.cpp
@@ -960,7 +960,7 @@
   if (MDFrom) {
 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
-Sel = addBranchMetadata(Sel, Prof, Unpred);
+Sel = addBranchMetadata(Sel, Prof, Unpred, nullptr /*TODO*/);
   }
   if (isa(Sel))
 setFPAttrs(Sel, nullptr /* MDNode* */, FMF);
Index: llvm/lib/CodeGen/BranchFolding.cpp
===
--- llvm/lib/CodeGen/BranchFolding.cpp
+++ llvm/lib/CodeGen/BranchFolding.cpp
@@ -1217,7 +1217,19 @@
 // Blocks should be considered empty if they contain only debug info;
 // else the debug info would affect codegen.
 static bool IsEmptyBlock(MachineBasicBlock *MBB) {
-  return MBB->getFirstNonDebugInstr(true) == MBB->end();
+  if (MBB->getFirstNonDebugInstr(true) != MBB->end())
+return false;
+
+  // Even though this block is empty, check if we should preserve it.
+  if (const auto *BB = MBB->getBasicBlock()) {
+for (const BasicBlock *PredBB : predecessors(BB)) {
+  const auto *PredBr = dyn_cast(PredBB->getTerminator());
+  if (PredBr && PredBr->getMetadata(LLVMContext::MD_mustcontrol))
+return false;
+}
+  }
+
+  return true;
 }
 
 // Blocks with only debug info and branches should be considered the same
Index: llvm/include/llvm/IR/MDBuilder.h
===
--- llvm/include/llvm/IR/MDBuilder.h
+++ llvm/include/llvm/IR/MDBuilder.h
@@ -66,6 +66,9 @@
   /// Return metadata specifying that a branch or switch is unpredictable.
   MDNode *createUnpredictable();
 
+  /// Return metadata specifying that a branch or switch must not be removed.
+  MDNode *createMustControl();
+
   /// Return metadata containing the entry \p Count for a function, a boolean
   /// \Synthetic indicating whether the counts were synthetized, and the
   /// GUIDs stored in \p Imports that need to be imported for sample PGO, to
Index: llvm/include/llvm/IR/Intrinsics.td
===
--- llvm/include/llvm/IR/Intrinsics.td
+++ llvm/include/llvm/IR/Intrinsics.td
@@ -1326,7 +1326,8 @@
 // has having opaque side effects. This may be inserted into loops to ensure
 // that they are not removed even if they turn out to be empty, for languages
 // which specify that infinite loops must be preserved.
-def int_sideeffect : DefaultAttrsIntrinsic<[], [], [IntrInaccessibleMemOnly, IntrWillReturn]>;
+def int_sideeffect : Defau

[PATCH] D103958: [WIP] Support MustControl conditional control attribute

2021-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D103958#2807811 , @lebedev.ri 
wrote:

> This is missing langref changes, and a RFC to llvm-dev.

We're not there yet, but will send something. Having real code helped me 
understand what out the myriad of options that were discussed were actually 
reasonable to implement. (Perhaps I should have uploaded WIP code elsewhere, 
sorry about that.)

> I'm rather skeptical of this.

We're trying to solve a serious problem, and the Linux kernel is an important 
usecase. We'd be very glad to hear constructive criticism, the LKML thread is 
still ongoing: 
https://lore.kernel.org/linux-arch/yln8dzbnwvqrq...@hirez.programming.kicks-ass.net/

Thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D103958

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


[PATCH] D103958: [WIP] Support MustControl conditional control attribute

2021-06-09 Thread Marco Elver via Phabricator via cfe-commits
melver added a comment.

In D103958#2808861 , @efriedma wrote:

> I don't like using metadata like this.  Dropping metadata should generally 
> preserve the semantics of the code.

Anything better for this without introducing new instructions? Would an 
argument be reasonable?

>> without resorting to inline assembly (which often results in poor codegen).
>
> Could you give an example of the resulting assembly with mustcontrol vs. this 
> patch?

For one of the pathological cases:

  int x, y, z;  


   



 
  int main(int argc, char *argv[]) {


   
  z = 42;   


 



 
volatile_if (READ_ONCE(x)) {


   
WRITE_ONCE(y, z);   


 
  } else {  


 
WRITE_ONCE(y, z);   


 
  } 


 



 
  return 0; 


 
  }

Doing nothing:

  define dso_local i32 @main(i32 %argc, i8** nocapture readnone %argv) 
local_unnamed_addr #0 {
  entry:
store i32 42, i32* @z, align 4, !tbaa !3
%0 = load volatile i32, i32* @x, align 4, !tbaa !3
store volatile i32 42, i32* @y, align 4, !tbaa !3
ret i32 0
  }

No branch here.

Their latest proposal using compiler barriers (and not asmgoto):

  define dso_local i32 @main(i32 %0, i8** nocapture readnone %1) 
local_unnamed_addr #0 {
store i32 42, i32* @z, align 4, !tbaa !2
%3 = load volatile i32, i32* @x, align 4, !tbaa !2
%4 = icmp eq i32 %3, 0
br i1 %4, label %7, label %5
  
  5:; preds = %2
tail call void asm sideeffect "", 
"i,~{memory},~{dirflag},~{fpsr},~{flags}"(i32 0) #1, !srcloc !6 
   
%6 = load i32, i32* @z, align 4, !tbaa !2
br label %7
  
  7:; preds = %2, %5
%8 = phi i32 [ %6, %5 ], [ 42, %2 ]
store volatile i32 %8, i32* @y, align 4, !tbaa !2
ret i32 0
  }

You can see the unnecessary load to z.

With mustcontrol:

  define dso_local i32 @main(i32 %argc, i8** nocapture readnone %argv) 
local_unnamed_addr #0 {
  entry:
store i32 42, i32* @z, align 4, !tbaa !3
%0 = load volatile i32, i32* @x, align 4, !tbaa !3
 

  1   2   >