r328857 - [Modules] Improve fixit for framework private module maps

2018-03-29 Thread Bruno Cardoso Lopes via cfe-commits
Author: bruno
Date: Thu Mar 29 22:17:58 2018
New Revision: 328857

URL: http://llvm.org/viewvc/llvm-project?rev=328857=rev
Log:
[Modules] Improve fixit for framework private module maps

The wrong source range was being provided in some case, fix that to get
a better fixit.

rdar://problem/38520199

Modified:
cfe/trunk/lib/Lex/ModuleMap.cpp
cfe/trunk/test/Modules/implicit-private-with-submodule.m

Modified: cfe/trunk/lib/Lex/ModuleMap.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/ModuleMap.cpp?rev=328857=328856=328857=diff
==
--- cfe/trunk/lib/Lex/ModuleMap.cpp (original)
+++ cfe/trunk/lib/Lex/ModuleMap.cpp Thu Mar 29 22:17:58 2018
@@ -1630,14 +1630,15 @@ namespace {
 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
 static void diagnosePrivateModules(const ModuleMap ,
DiagnosticsEngine ,
-   const Module *ActiveModule) {
+   const Module *ActiveModule,
+   SourceLocation InlineParent) {
 
   auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
- const Module *M) {
+ const Module *M, SourceRange ReplLoc) {
 auto D = Diags.Report(ActiveModule->DefinitionLoc,
   diag::note_mmap_rename_top_level_private_module);
 D << BadName << M->Name;
-D << FixItHint::CreateReplacement(ActiveModule->DefinitionLoc, Canonical);
+D << FixItHint::CreateReplacement(ReplLoc, Canonical);
   };
 
   for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
@@ -1657,7 +1658,8 @@ static void diagnosePrivateModules(const
   Diags.Report(ActiveModule->DefinitionLoc,
diag::warn_mmap_mismatched_private_submodule)
   << FullName;
-  GenNoteAndFixIt(FullName, Canonical, M);
+  GenNoteAndFixIt(FullName, Canonical, M,
+  SourceRange(InlineParent, ActiveModule->DefinitionLoc));
   continue;
 }
 
@@ -1667,7 +1669,8 @@ static void diagnosePrivateModules(const
   Diags.Report(ActiveModule->DefinitionLoc,
diag::warn_mmap_mismatched_private_module_name)
   << ActiveModule->Name;
-  GenNoteAndFixIt(ActiveModule->Name, Canonical, M);
+  GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
+  SourceRange(ActiveModule->DefinitionLoc));
 }
   }
 }
@@ -1753,6 +1756,7 @@ void ModuleMapParser::parseModuleDecl()
   }
   
   Module *PreviousActiveModule = ActiveModule;  
+  SourceLocation LastInlineParentLoc = SourceLocation();
   if (Id.size() > 1) {
 // This module map defines a submodule. Go find the module of which it
 // is a submodule.
@@ -1763,6 +1767,7 @@ void ModuleMapParser::parseModuleDecl()
 if (I == 0)
   TopLevelModule = Next;
 ActiveModule = Next;
+LastInlineParentLoc = Id[I].second;
 continue;
   }
   
@@ -1882,7 +1887,7 @@ void ModuleMapParser::parseModuleDecl()
StartLoc) &&
   (MapFileName.endswith("module.private.modulemap") ||
MapFileName.endswith("module_private.map")))
-diagnosePrivateModules(Map, Diags, ActiveModule);
+diagnosePrivateModules(Map, Diags, ActiveModule, LastInlineParentLoc);
 
   bool Done = false;
   do {

Modified: cfe/trunk/test/Modules/implicit-private-with-submodule.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/implicit-private-with-submodule.m?rev=328857=328856=328857=diff
==
--- cfe/trunk/test/Modules/implicit-private-with-submodule.m (original)
+++ cfe/trunk/test/Modules/implicit-private-with-submodule.m Thu Mar 29 
22:17:58 2018
@@ -13,7 +13,7 @@
 
 // 
expected-warning@Inputs/implicit-private-with-submodule/A.framework/Modules/module.private.modulemap:1{{private
 submodule 'A.Private' in private module map, expected top-level module}}
 // 
expected-note@Inputs/implicit-private-with-submodule/A.framework/Modules/module.private.modulemap:1{{rename
 'A.Private' to ensure it can be found by name}}
-// CHECK: fix-it:"{{.*}}module.private.modulemap":{1:20-1:27}:"A_Private"
+// CHECK: fix-it:"{{.*}}module.private.modulemap":{1:18-1:27}:"A_Private"
 
 #ifndef HEADER
 #define HEADER


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


[PATCH] D45058: [X86] Disable SGX for Skylake Server

2018-03-29 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rC Clang

https://reviews.llvm.org/D45058



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


[PATCH] D44764: [clangd] Use operator<< to prevent printers issues in Gtest

2018-03-29 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle added inline comments.



Comment at: clangd/Protocol.h:673
 json::Expr toJSON(const CompletionItem &);
+std::ostream <<(std::ostream &, const CompletionItem &);
 

sammccall wrote:
> I think raw_ostream should work fine here, it's what we've done elsewhere.
> Is there a reason to use std::ostream?
> 
> (llvm's gtest is specially modified so raw_ostream printers can be used)
No reason, I changed it.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44764



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


[PATCH] D44764: [clangd] Use operator<< to prevent printers issues in Gtest

2018-03-29 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle updated this revision to Diff 140382.
malaperle marked an inline comment as done.
malaperle added a comment.

Use raw_ostream instead.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44764

Files:
  clangd/Protocol.cpp
  clangd/Protocol.h
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/JSONExprTests.cpp
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- unittests/clangd/XRefsTests.cpp
+++ unittests/clangd/XRefsTests.cpp
@@ -24,15 +24,6 @@
 namespace clangd {
 using namespace llvm;
 
-void PrintTo(const DocumentHighlight , std::ostream *O) {
-  llvm::raw_os_ostream OS(*O);
-  OS << V.range;
-  if (V.kind == DocumentHighlightKind::Read)
-OS << "(r)";
-  if (V.kind == DocumentHighlightKind::Write)
-OS << "(w)";
-}
-
 namespace {
 using testing::ElementsAre;
 using testing::Field;
Index: unittests/clangd/JSONExprTests.cpp
===
--- unittests/clangd/JSONExprTests.cpp
+++ unittests/clangd/JSONExprTests.cpp
@@ -15,9 +15,7 @@
 namespace clang {
 namespace clangd {
 namespace json {
-void PrintTo(const Expr , std::ostream *OS) {
-  llvm::raw_os_ostream(*OS) << llvm::formatv("{0:2}", E);
-}
+
 namespace {
 
 std::string s(const Expr ) { return llvm::formatv("{0}", E).str(); }
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -22,33 +22,6 @@
 
 namespace clang {
 namespace clangd {
-// Let GMock print completion items and signature help.
-void PrintTo(const CompletionItem , std::ostream *O) {
-  llvm::raw_os_ostream OS(*O);
-  OS << I.label << " - " << toJSON(I);
-}
-void PrintTo(const std::vector , std::ostream *O) {
-  *O << "{\n";
-  for (const auto  : V) {
-*O << "\t";
-PrintTo(I, O);
-*O << "\n";
-  }
-  *O << "}";
-}
-void PrintTo(const SignatureInformation , std::ostream *O) {
-  llvm::raw_os_ostream OS(*O);
-  OS << I.label << " - " << toJSON(I);
-}
-void PrintTo(const std::vector , std::ostream *O) {
-  *O << "{\n";
-  for (const auto  : V) {
-*O << "\t";
-PrintTo(I, O);
-*O << "\n";
-  }
-  *O << "}";
-}
 
 namespace {
 using namespace llvm;
Index: clangd/Protocol.h
===
--- clangd/Protocol.h
+++ clangd/Protocol.h
@@ -670,6 +670,7 @@
   //  between a completion and a completion resolve request.
 };
 json::Expr toJSON(const CompletionItem &);
+llvm::raw_ostream <<(llvm::raw_ostream &, const CompletionItem &);
 
 bool operator<(const CompletionItem &, const CompletionItem &);
 
@@ -708,6 +709,8 @@
   std::vector parameters;
 };
 json::Expr toJSON(const SignatureInformation &);
+llvm::raw_ostream <<(llvm::raw_ostream &,
+  const SignatureInformation &);
 
 /// Represents the signature of a callable.
 struct SignatureHelp {
@@ -761,6 +764,7 @@
   }
 };
 json::Expr toJSON(const DocumentHighlight );
+llvm::raw_ostream <<(llvm::raw_ostream &, const DocumentHighlight &);
 
 } // namespace clangd
 } // namespace clang
Index: clangd/Protocol.cpp
===
--- clangd/Protocol.cpp
+++ clangd/Protocol.cpp
@@ -446,6 +446,11 @@
   return std::move(Result);
 }
 
+llvm::raw_ostream <<(llvm::raw_ostream , const CompletionItem ) {
+  O << I.label << " - " << toJSON(I);
+  return O;
+}
+
 bool operator<(const CompletionItem , const CompletionItem ) {
   return (L.sortText.empty() ? L.label : L.sortText) <
  (R.sortText.empty() ? R.label : R.sortText);
@@ -477,6 +482,12 @@
   return std::move(Result);
 }
 
+llvm::raw_ostream <<(llvm::raw_ostream ,
+  const SignatureInformation ) {
+  O << I.label << " - " << toJSON(I);
+  return O;
+}
+
 json::Expr toJSON(const SignatureHelp ) {
   assert(SH.activeSignature >= 0 &&
  "Unexpected negative value for number of active signatures.");
@@ -502,6 +513,16 @@
   };
 }
 
+llvm::raw_ostream <<(llvm::raw_ostream ,
+  const DocumentHighlight ) {
+  O << V.range;
+  if (V.kind == DocumentHighlightKind::Read)
+O << "(r)";
+  if (V.kind == DocumentHighlightKind::Write)
+O << "(w)";
+  return O;
+}
+
 bool fromJSON(const json::Expr , DidChangeConfigurationParams ) {
   json::ObjectMapper O(Params);
   return O && O.map("settings", CCP.settings);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


RE: r328837 - [analyzer] Fix target triple for autorelease-write-checker test

2018-03-29 Thread via cfe-commits
I've added "UNSUPPORTED: system-windows" in r328853. Hopefully that should 
disable it on Windows until you can get a chance to figure out the problem.

Douglas Yung

> -Original Message-
> From: ekarpen...@apple.com [mailto:ekarpen...@apple.com]
> Sent: Thursday, March 29, 2018 18:22
> To: Yung, Douglas
> Subject: Re: r328837 - [analyzer] Fix target triple for autorelease-write-
> checker test
> 
> Hi Douglas,
> 
> I am not at computer right now, maybe you could add UNSUPPORTED: windows or
> similar?
> 
> Sent from my iPhone
> 
> > On Mar 29, 2018, at 18:20, douglas.y...@sony.com wrote:
> >
> > Hi George,
> >
> > This test is still failing on a bot (http://lab.llvm.org:8011/builders/llvm-
> clang-lld-x86_64-scei-ps4-windows10pro-fast/builds/16152):
> >
> > FAIL: Clang :: Analysis/autoreleasewritechecker_test.m (2908 of 39213)
> >  TEST 'Clang ::
> > Analysis/autoreleasewritechecker_test.m' FAILED 
> > Script:
> > --
> > c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.obj\bin\clang.EXE -cc1 -internal-isystem
> > c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.obj\lib\clang\7.0.0\include -nostdsysteminc -analyze -DARC
> > -fobjc-arc -analyzer-checker=core,osx.cocoa.AutoreleaseWrite
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
> > -triple x86_64-darwin -fblocks -verify
> > c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.obj\bin\clang.EXE -cc1 -internal-isystem
> > c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.obj\lib\clang\7.0.0\include -nostdsysteminc -analyze -DNOARC
> > -analyzer-checker=core,osx.cocoa.AutoreleaseWrite
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
> > -fblocks -triple x86_64-darwin -verify
> > --
> > Exit Code: 1
> >
> > Command Output (stdout):
> > --
> > $ "c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-
> fast\llvm.obj\bin\clang.EXE" "-cc1" "-internal-isystem" "c:\ps4-
> buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-
> fast\llvm.obj\lib\clang\7.0.0\include" "-nostdsysteminc" "-analyze" "-DARC" "-
> fobjc-arc" "-analyzer-checker=core,osx.cocoa.AutoreleaseWrite" "C:\ps4-
> buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-
> fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m" "-
> triple" "x86_64-darwin" "-fblocks" "-verify"
> > # command stderr:
> > error: 'warning' diagnostics expected but not seen:
> >
> >  File
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m Line
> > 71: Writing into an auto-releasing out parameter inside autorelease
> > pool that may exit before method returns
> >
> >  File
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m Line
> > 125: Writing into an auto-releasing out
> >
> >  File
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m Line
> > 131: Writing into an auto-releasing out
> >
> >  File
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m Line
> > 132: Writing into an auto-releasing out
> >
> >  File
> > C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\ll
> > vm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m Line
> > 152: Writing into an auto-releasing out
> >
> > 5 errors generated.
> >
> >
> > error: command failed with exit status: 1
> >
> >
> >
> > Could you please take a look?
> >
> > Douglas Yung
> >
> >> -Original Message-
> >> From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On
> >> Behalf Of George Karpenkov via cfe-commits
> >> Sent: Thursday, March 29, 2018 15:28
> >> To: cfe-commits@lists.llvm.org
> >> Subject: r328837 - [analyzer] Fix target triple for
> >> autorelease-write-checker test
> >>
> >> Author: george.karpenkov
> >> Date: Thu Mar 29 15:28:04 2018
> >> New Revision: 328837
> >>
> >> URL: http://llvm.org/viewvc/llvm-project?rev=328837=rev
> >> Log:
> >> [analyzer] Fix target triple for autorelease-write-checker test
> >>
> >> Modified:
> >>cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
> >>
> >> Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
> >> URL: http://llvm.org/viewvc/llvm-
> >> project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=32
> >> 8837=3
> >> 28836=328837=diff
> >> =
> >> =
> >> --- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
> >> +++ 

r328853 - Adding UNSUPPORTED: system-windows at George's request until the problem can be debugged.

2018-03-29 Thread Douglas Yung via cfe-commits
Author: dyung
Date: Thu Mar 29 18:29:07 2018
New Revision: 328853

URL: http://llvm.org/viewvc/llvm-project?rev=328853=rev
Log:
Adding UNSUPPORTED: system-windows at George's request until the problem can be 
debugged.


Modified:
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m

Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=328853=328852=328853=diff
==
--- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
+++ cfe/trunk/test/Analysis/autoreleasewritechecker_test.m Thu Mar 29 18:29:07 
2018
@@ -1,3 +1,4 @@
+// UNSUPPORTED: system-windows
 // RUN: %clang_analyze_cc1 -DARC -fobjc-arc 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -triple x86_64-darwin 
-fblocks -verify
 // RUN: %clang_analyze_cc1 -DNOARC 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -fblocks -triple 
x86_64-darwin -verify
 


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


RE: r328837 - [analyzer] Fix target triple for autorelease-write-checker test

2018-03-29 Thread via cfe-commits
Hi George,

This test is still failing on a bot 
(http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast/builds/16152):

FAIL: Clang :: Analysis/autoreleasewritechecker_test.m (2908 of 39213)
 TEST 'Clang :: Analysis/autoreleasewritechecker_test.m' 
FAILED 
Script:
--
c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\bin\clang.EXE
 -cc1 -internal-isystem 
c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\lib\clang\7.0.0\include
 -nostdsysteminc -analyze -DARC -fobjc-arc 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 -triple x86_64-darwin -fblocks -verify
c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\bin\clang.EXE
 -cc1 -internal-isystem 
c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\lib\clang\7.0.0\include
 -nostdsysteminc -analyze -DNOARC 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 -fblocks -triple x86_64-darwin -verify
--
Exit Code: 1

Command Output (stdout):
--
$ 
"c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\bin\clang.EXE"
 "-cc1" "-internal-isystem" 
"c:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.obj\lib\clang\7.0.0\include"
 "-nostdsysteminc" "-analyze" "-DARC" "-fobjc-arc" 
"-analyzer-checker=core,osx.cocoa.AutoreleaseWrite" 
"C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m"
 "-triple" "x86_64-darwin" "-fblocks" "-verify"
# command stderr:
error: 'warning' diagnostics expected but not seen: 

  File 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 Line 71: Writing into an auto-releasing out parameter inside autorelease pool 
that may exit before method returns

  File 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 Line 125: Writing into an auto-releasing out

  File 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 Line 131: Writing into an auto-releasing out

  File 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 Line 132: Writing into an auto-releasing out

  File 
C:\ps4-buildslave2\llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast\llvm.src\tools\clang\test\Analysis\autoreleasewritechecker_test.m
 Line 152: Writing into an auto-releasing out

5 errors generated.


error: command failed with exit status: 1



Could you please take a look?

Douglas Yung

> -Original Message-
> From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On Behalf Of
> George Karpenkov via cfe-commits
> Sent: Thursday, March 29, 2018 15:28
> To: cfe-commits@lists.llvm.org
> Subject: r328837 - [analyzer] Fix target triple for autorelease-write-checker
> test
> 
> Author: george.karpenkov
> Date: Thu Mar 29 15:28:04 2018
> New Revision: 328837
> 
> URL: http://llvm.org/viewvc/llvm-project?rev=328837=rev
> Log:
> [analyzer] Fix target triple for autorelease-write-checker test
> 
> Modified:
> cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
> 
> Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
> URL: http://llvm.org/viewvc/llvm-
> project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=328837=3
> 28836=328837=diff
> ==
> --- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
> +++ cfe/trunk/test/Analysis/autoreleasewritechecker_test.m Thu Mar 29
> +++ 15:28:04 2018
> @@ -1,4 +1,5 @@
> -// RUN: %clang_analyze_cc1 -DARC -fobjc-arc -analyzer-
> checker=core,osx.cocoa.AutoreleaseWrite %s -fblocks -verify
> +// RUN: %clang_analyze_cc1 -DARC -fobjc-arc
> +-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -triple
> +x86_64-darwin -fblocks -verify // RUN: %clang_analyze_cc1 -DNOARC
> +-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -fblocks -triple
> +x86_64-darwin -verify
> 
> 
>  typedef signed char BOOL;
> 
> 
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45013: Generate warning when over-aligned new call is required but not supported.

2018-03-29 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Does it make sense to have a warning for `__libcpp_deallocate` and 
`get_temporary_buffer` too? Not sure about deallocate as you have allocated 
memory already and allocation has a warning. So for deallocation a warning can 
be too noisy. But for `get_temporary_buffer` the warning seems reasonable, 
unless I'm missing something.


Repository:
  rCXX libc++

https://reviews.llvm.org/D45013



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


[PATCH] D45071: [analyzer] Track null or undef values through pointer arithmetic.

2018-03-29 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ created this revision.
NoQ added reviewers: dcoughlin, xazax.hun, a.sidorin, george.karpenkov, szepet.
Herald added subscribers: cfe-commits, rnkovacs, eraman.

Pointer arithmetic on null or undefined pointers results in null or undefined 
pointers. This is obvious for undefined pointers; for null pointers it follows 
from our incorrect-but-somehow-working approach that declares that `0 (Loc)` 
doesn't necessarily represent a pointer of numeric address value 0, but instead 
it represents any pointer that will cause a valid "null pointer dereference" 
issue when dereferenced.

For now we've been seeing through pointer arithmetic at the original 
dereference expression, i.e. in `bugreporter::getDerefExpr()`, but not during 
further investigation of the value's origins in 
`bugreporter::trackNullOrUndefValue()`. The patch fixes it.

Reproducers are reduced from WebKit's custom string implementations. 
CStringChecker doesn't call `getDerefExpr()` at all (this is //probably// 
because passing a pointer to `memcpy` is not an immediate null dereference - in 
fact i've no idea how this decision was made or how this code was actually 
supposed to operate). But the second test case demonstrates that simply adding 
`getDerefExpr()` to CStringChecker is insufficient. Also an older FIXME test 
gets fixed this way.


Repository:
  rC Clang

https://reviews.llvm.org/D45071

Files:
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  test/Analysis/inlining/inline-defensive-checks.c
  test/Analysis/null-deref-path-notes.c


Index: test/Analysis/null-deref-path-notes.c
===
--- test/Analysis/null-deref-path-notes.c
+++ test/Analysis/null-deref-path-notes.c
@@ -1,9 +1,25 @@
-// RUN: %clang_analyze_cc1 -w -x c -analyzer-checker=core 
-analyzer-output=text -verify %s
+// RUN: %clang_analyze_cc1 -w -x c -analyzer-checker=core,unix 
-analyzer-output=text -verify %s
 
 // Avoid the crash when finding the expression for tracking the origins
 // of the null pointer for path notes.
 void pr34373() {
   int *a = 0; // expected-note{{'a' initialized to a null pointer value}}
   (a + 0)[0]; // expected-warning{{Array access results in a null pointer 
dereference}}
   // expected-note@-1{{Array access results in a null pointer 
dereference}}
 }
+
+typedef __typeof(sizeof(int)) size_t;
+void *memcpy(void *dest, const void *src, unsigned long count);
+
+void f1(char *source) {
+  char *destination = 0; // expected-note{{'destination' initialized to a null 
pointer value}}
+  memcpy(destination + 0, source, 10); // expected-warning{{Null pointer 
argument in call to memory copy function}}
+   // expected-note@-1{{Null pointer 
argument in call to memory copy function}}
+}
+
+void f2(char *source) {
+  char *destination = 0; // FIXME: There should be a note here as well.
+  destination = destination + 0; // expected-note{{Null pointer value stored 
to 'destination'}}
+  memcpy(destination, source, 10); // expected-warning{{Null pointer argument 
in call to memory copy function}}
+   // expected-note@-1{{Null pointer argument 
in call to memory copy function}}
+}
Index: test/Analysis/inlining/inline-defensive-checks.c
===
--- test/Analysis/inlining/inline-defensive-checks.c
+++ test/Analysis/inlining/inline-defensive-checks.c
@@ -159,8 +159,7 @@
 void idcTrackZeroValueThroughUnaryPointerOperatorsWithOffset2(struct S *s) {
   idc(s);
   int *x = &(s->f2) - 1;
-  // FIXME: Should not warn.
-  *x = 7; // expected-warning{{Dereference of null pointer}}
+  *x = 7; // no-warning
 }
 
 void idcTrackZeroValueThroughUnaryPointerOperatorsWithAssignment(struct S *s) {
Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -75,6 +75,17 @@
   return false;
 }
 
+const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
+  if (B->isAdditiveOp() && B->getType()->isPointerType()) {
+if (B->getLHS()->getType()->isPointerType()) {
+  return B->getLHS();
+} else if (B->getRHS()->getType()->isPointerType()) {
+  return B->getRHS();
+}
+  }
+  return nullptr;
+}
+
 /// Given that expression S represents a pointer that would be dereferenced,
 /// try to find a sub-expression from which the pointer came from.
 /// This is used for tracking down origins of a null or undefined value:
@@ -101,14 +112,8 @@
   E = CE->getSubExpr();
 } else if (const auto *B = dyn_cast(E)) {
   // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
-  if (B->getType()->isPointerType()) {
-if (B->getLHS()->getType()->isPointerType()) {
-  E = B->getLHS();
-} else if (B->getRHS()->getType()->isPointerType()) {
-  E = B->getRHS();
-} else 

[PATCH] D45060: Allow target to handle required features for TARGET_BUILTINs.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra marked an inline comment as done.
tra added inline comments.



Comment at: clang/include/clang/Basic/TargetInfo.h:933
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features.
+  virtual Optional

jlebar wrote:
> It's not totally obvious to me, can we explain why it's a tristate?
We need to distinguish between "target does not need to do anything special 
about the feature" (no value) and "target does have an opinion, which may be 
true or false.". I'll update the comment.


https://reviews.llvm.org/D45060



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


[PATCH] D45060: Allow target to handle required features for TARGET_BUILTINs.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 140371.
tra added a comment.

Updated description of hasRequiredFeature.
Set FirstMissing if target returns 'false' so diags still work.


https://reviews.llvm.org/D45060

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/CodeGen/CodeGenFunction.cpp


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2262,6 +2262,16 @@
 Feature.split(OrFeatures, "|");
 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
[&](StringRef Feature) {
+ // Check if the target wants to handle the 
feature.
+ if (Optional HasFeature =
+ CGM.getTarget().hasRequiredFeature(
+ CallerFeatureMap, Feature)) {
+   if (*HasFeature == false)
+ FirstMissing = Feature.str();
+   return *HasFeature;
+ }
+ // Otherwise just look for the feature
+ // presence/absence in the CallerFeatureMap.
  if (!CallerFeatureMap.lookup(Feature)) {
FirstMissing = Feature.str();
return false;
Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -928,8 +928,20 @@
 return false;
   }
 
-  /// \brief Identify whether this taret supports multiversioning of functions,
-  /// which requires support for cpu_supports and cpu_is functionality.
+  /// \brief Determine if ReqFeature is enabled given the features populated in
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features. Function returns None when the feature does not need
+  /// special handling by the target, or true/false to indicate whether the
+  /// feature is enabled.
+  virtual Optional
+  hasRequiredFeature(const llvm::StringMap FeatureMap,
+ const StringRef ReqFeature) const {
+return None;
+  }
+
+  /// \brief Identify whether this taret supports multiversioning of
+  /// functions, which requires support for cpu_supports and cpu_is
+  /// functionality.
   virtual bool supportsMultiVersioning() const { return false; }
 
   // \brief Validate the contents of the __builtin_cpu_supports(const char*)


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2262,6 +2262,16 @@
 Feature.split(OrFeatures, "|");
 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
[&](StringRef Feature) {
+ // Check if the target wants to handle the feature.
+ if (Optional HasFeature =
+ CGM.getTarget().hasRequiredFeature(
+ CallerFeatureMap, Feature)) {
+   if (*HasFeature == false)
+ FirstMissing = Feature.str();
+   return *HasFeature;
+ }
+ // Otherwise just look for the feature
+ // presence/absence in the CallerFeatureMap.
  if (!CallerFeatureMap.lookup(Feature)) {
FirstMissing = Feature.str();
return false;
Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -928,8 +928,20 @@
 return false;
   }
 
-  /// \brief Identify whether this taret supports multiversioning of functions,
-  /// which requires support for cpu_supports and cpu_is functionality.
+  /// \brief Determine if ReqFeature is enabled given the features populated in
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features. Function returns None when the feature does not need
+  /// special handling by the target, or true/false to indicate whether the
+  /// feature is enabled.
+  virtual Optional
+  hasRequiredFeature(const llvm::StringMap FeatureMap,
+ const StringRef ReqFeature) const {
+return None;
+  }
+
+  /// \brief Identify whether this taret supports multiversioning of
+  /// functions, which requires support for cpu_supports and cpu_is
+  /// functionality.
   virtual bool supportsMultiVersioning() const 

[PATCH] D45068: [NVPTX, CUDA] Added support for m8n32k16 and m32n8k16 variants of wmma instructions.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 140363.
tra added a comment.

Updated comments.


https://reviews.llvm.org/D45068

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/CodeGen/builtins-nvptx-sm_70.cu
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTX.td
  llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
  llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/test/CodeGen/NVPTX/wmma.py

Index: llvm/test/CodeGen/NVPTX/wmma.py
===
--- llvm/test/CodeGen/NVPTX/wmma.py
+++ llvm/test/CodeGen/NVPTX/wmma.py
@@ -2,7 +2,7 @@
 # generates correct instructions for them.
 
 # RUN: python %s > %t.ll
-# RUN: llc < %t.ll -march=nvptx64 -mcpu=sm_70 -mattr=+ptx60 | FileCheck %t.ll
+# RUN: llc < %t.ll -march=nvptx64 -mcpu=sm_70 -mattr=+ptx61 | FileCheck %t.ll
 
 from itertools import product
 from string import Template
@@ -36,33 +36,36 @@
 check_f16_4 = "{{%s}}" % ", *".join(["%hh[0-9]+"] * 4)
 check_f32_8 = "{{%s}}" % ", *".join(["%f[0-9]+"] * 8)
 
+known_geoms = ["m16n16k16", "m8n32k16", "m32n8k16"]
+
 def gen_wmma_load_tests():
   load_template = """
 declare ${ret_ty} @${intrinsic}(i8 ${as}* %src ${extra_args});
 
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define ${ret_ty} @test_${function}(i8 ${as}* %src ${extra_args}) {
-; CHECK ${instruction}
+; CHECK: ${instruction}
 ; CHECK: {${check_result}}
 ; CHECK: [%rd{{[0-9]+}}]${stride_pattern}
   %v0 = call ${ret_ty} @${intrinsic}(i8 ${as}* %src ${extra_args});
   ret ${ret_ty} %v0;
 }
 
 ; CHECK-LABEL: .func{{.*}}test_${function}_o(
 define ${ret_ty} @test_${function}_o(i8 ${as}* %src ${extra_args}) {
-; CHECK ${instruction}
+; CHECK: ${instruction}
 ; CHECK: {${check_result}}
 ; CHECK: [%rd{{[0-9]+}}+128]${stride_pattern}
   %src1 = getelementptr i8, i8 ${as}* %src, i32 128;
   %v0 = call ${ret_ty} @${intrinsic}(i8 ${as}* %src1 ${extra_args});
   ret ${ret_ty} %v0;
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.load.${abc}.${layout}${stride}.${itype}.${pspace}"
-  instruction_template = "wmma.load.${abc}.sync.${geom}.${layout}${space}.${itype}"
+  instruction_template = "wmma.load.${abc}.sync.${layout}.${geom}${space}.${itype}"
 
-  for abc, layout, space, stride, itype in product(
+  for geom, abc, layout, space, stride, itype in product(
+  known_geoms,
   "abc",
   ["row","col"],
   ["",".shared",".global"],
@@ -77,7 +80,7 @@
 "itype" : itype,
 "pspace" : get_pspace(space),
 "as" : "addrspace(%d)" % get_aspace(space),
-"geom"   : "m16n16k16",
+"geom"   : geom,
 }
 
 if itype == "f32" and abc != "c":
@@ -112,27 +115,28 @@
 
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define void @test_${function}(i8 ${as}* %src, ${args}${extra_args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}
+; CHECK: ${instruction} {{.*}}[%rd{{[0-9+]}}
 ; CHECK: {${check_args}}
 ; CHECK: ${stride_pattern}
   call void @${intrinsic}(i8 ${as}* %src, ${args} ${extra_args});
   ret void
 }
 
 ; CHECK-LABEL: .func{{.*}}test_${function}_o(
 define void @test_${function}_o(i8 ${as}* %src, ${args}${extra_args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}+128]
+; CHECK: ${instruction} {{.*}}[%rd{{[0-9+]}}+128]
 ; CHECK: ${check_args}
 ; CHECK: ${stride_pattern}
   %src1 = getelementptr i8, i8 ${as}* %src, i32 128;
   call void @${intrinsic}(i8 ${as}* %src1, ${args}${extra_args});
   ret void
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.store.${abc}.${layout}${stride}.${itype}.${pspace}"
-  instruction_template = "wmma.store.${abc}.sync.${geom}.${layout}${space}.${itype}"
+  instruction_template = "wmma.store.${abc}.sync.${layout}.${geom}${space}.${itype}"
 
-  for abc, layout, space, stride, itype in product(
+  for geom, abc, layout, space, stride, itype in product(
+  known_geoms,
   "d",
   ["row","col"],
   ["",".shared",".global"],
@@ -147,7 +151,7 @@
 "itype" : itype,
 "pspace" : get_pspace(space),
 "as" : "addrspace(%d)" % get_aspace(space),
-"geom"   : "m16n16k16",
+"geom"   : geom,
 }
 
 test_params = params
@@ -174,20 +178,21 @@
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define ${ret_ty} @test_${function}(
 ${args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}
-; CHECK ${check_d}
-; CHECK ${check_ab}
-; CHECK ${check_ab}
-; CHECK ${check_c}
+; CHECK: ${instruction}
+; CHECK-NEXT: ${check_d}
+; CHECK-NEXT: ${check_ab}
+; CHECK-NEXT: ${check_ab}
+; CHECK-NEXT: ${check_c}
   %r = call ${ret_ty} @${intrinsic}(
 ${args});
   ret ${ret_ty} %r;
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.mma.${alayout}.${blayout}.${dtype}.${ctype}${satf}"
   instruction_template = "wmma.mma.sync.${alayout}.${blayout}.${geom}.${dtype}.${ctype}${satf}"
 
-  for alayout, blayout, ctype, dtype, satf in product(
+  for geom, 

[PATCH] D45060: Allow target to handle required features for TARGET_BUILTINs.

2018-03-29 Thread Justin Lebar via Phabricator via cfe-commits
jlebar accepted this revision.
jlebar added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Basic/TargetInfo.h:933
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features.
+  virtual Optional

It's not totally obvious to me, can we explain why it's a tristate?


https://reviews.llvm.org/D45060



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


[PATCH] D45061: [NVPTX, CUDA] Use custom feature detection to handle NVPTX target builtins.

2018-03-29 Thread Justin Lebar via Phabricator via cfe-commits
jlebar accepted this revision.
jlebar added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Basic/Cuda.h:55
 
+static inline const std::vector CudaKnownArchList() {
+  return {CudaArch::SM_20, CudaArch::SM_21, CudaArch::SM_30, CudaArch::SM_32,

Why 'static'?



Comment at: clang/include/clang/Basic/Cuda.h:59
+  CudaArch::SM_53, CudaArch::SM_60, CudaArch::SM_61, CudaArch::SM_62,
+  CudaArch::SM_70, CudaArch::SM_72};
+}

Could we instead rely on the fact that the CudaArch enum is dense and goes from 
UNKNOWN to LAST?  One less bug to make...



Comment at: clang/lib/Basic/Targets/NVPTX.cpp:182
+Optional
+NVPTXTargetInfo::hasRequiredFeature(const llvm::StringMap FeatureMap,
+const StringRef ReqFeature) const {

Nit, if you spell it `/*FeatureMap*/` here, it'll be clearer that you're 
intentionally ignoring that arg.


https://reviews.llvm.org/D45061



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


[PATCH] D45069: [clangd] synthesize fix message when the diagnostic doesn't provide one.

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ilya-biryukov.
Herald added subscribers: cfe-commits, MaskRay, ioeric, jkorous-apple, klimek.

Currently if a fix is attached directly to a diagnostic, we repeat the
diagnostic message as the fix message. From eyeballing the top diagnostics,
it seems describing the textual replacement would be much clearer.

e.g.
error: use of undeclared identifier 'goo'; did you mean 'foo'?
action before: use of undeclared identifier 'goo'; did you mean 'foo'?
action after: change 'goo' to 'foo'


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45069

Files:
  clangd/Diagnostics.cpp
  unittests/clangd/ClangdUnitTests.cpp

Index: unittests/clangd/ClangdUnitTests.cpp
===
--- unittests/clangd/ClangdUnitTests.cpp
+++ unittests/clangd/ClangdUnitTests.cpp
@@ -92,14 +92,6 @@
   return Res;
 }
 
-/// Matches diagnostic that has exactly one fix with the same range and message
-/// as the diagnostic itself.
-testing::Matcher DiagWithEqualFix(clangd::Range Range,
-std::string Replacement,
-std::string Message) {
-  return AllOf(Diag(Range, Message), WithFix(Fix(Range, Replacement, Message)));
-}
-
 TEST(DiagnosticsTest, DiagnosticRanges) {
   // Check we report correct ranges, including various edge-cases.
   Annotations Test(R"cpp(
@@ -111,28 +103,29 @@
   $unk[[unknown]]();
 }
   )cpp");
-  llvm::errs() << Test.code();
   EXPECT_THAT(
   buildDiags(Test.code()),
   ElementsAre(
   // This range spans lines.
-  AllOf(DiagWithEqualFix(
-Test.range("typo"), "foo",
-"use of undeclared identifier 'goo'; did you mean 'foo'?"),
+  AllOf(Diag(Test.range("typo"),
+ "use of undeclared identifier 'goo'; did you mean 'foo'?"),
+WithFix(
+Fix(Test.range("typo"), "foo", "change 'go\\ o' to 'foo'")),
 // This is a pretty normal range.
 WithNote(Diag(Test.range("decl"), "'foo' declared here"))),
   // This range is zero-width, and at the end of a line.
-  DiagWithEqualFix(Test.range("semicolon"), ";",
-   "expected ';' after expression"),
+  AllOf(Diag(Test.range("semicolon"), "expected ';' after expression"),
+WithFix(Fix(Test.range("semicolon"), ";", "insert ';'"))),
   // This range isn't provided by clang, we expand to the token.
   Diag(Test.range("unk"), "use of undeclared identifier 'unknown'")));
 }
 
 TEST(DiagnosticsTest, FlagsMatter) {
   Annotations Test("[[void]] main() {}");
   EXPECT_THAT(buildDiags(Test.code()),
-  ElementsAre(DiagWithEqualFix(Test.range(), "int",
-   "'main' must return 'int'")));
+  ElementsAre(AllOf(Diag(Test.range(), "'main' must return 'int'"),
+WithFix(Fix(Test.range(), "int",
+"change 'void' to 'int'");
   // Same code built as C gets different diagnostics.
   EXPECT_THAT(
   buildDiags(Test.code(), {"-x", "c"}),
Index: clangd/Diagnostics.cpp
===
--- clangd/Diagnostics.cpp
+++ clangd/Diagnostics.cpp
@@ -297,7 +297,7 @@
 return D;
   };
 
-  auto AddFix = [&]() -> bool {
+  auto AddFix = [&](bool SyntheticMessage) -> bool {
 assert(!Info.getFixItHints().empty() &&
"diagnostic does not have attached fix-its");
 if (!InsideMainFile)
@@ -312,7 +312,27 @@
 }
 
 llvm::SmallString<64> Message;
-Info.FormatDiagnostic(Message);
+// If requested and possible, create a message like "change 'foo' to 'bar'".
+if (SyntheticMessage && Info.getNumFixItHints() == 1) {
+  const auto  = Info.getFixItHint(0);
+  bool Invalid = false;
+  StringRef Remove = Lexer::getSourceText(
+  FixIt.RemoveRange, Info.getSourceManager(), *LangOpts, );
+  StringRef Insert = FixIt.CodeToInsert;
+  if (!Invalid && Remove.size() + Insert.size() < 200) {
+llvm::raw_svector_ostream M(Message);
+if (!Remove.empty() && !Insert.empty())
+  M << "change '" << Remove << "' to '" << Insert << "'";
+else if (!Remove.empty())
+  M << "remove '" << Remove << "'";
+else if (!Insert.empty())
+  M << "insert '" << Insert << "'";
+  }
+  // Don't allow source code to inject newlines into diagnostics.
+  std::replace(Message.begin(), Message.end(), '\n', ' ');
+}
+if (Message.empty()) // either !SytheticMessage, or we failed to make one.
+  Info.FormatDiagnostic(Message);
 LastDiag->Fixes.push_back(Fix{Message.str(), std::move(Edits)});
 return true;
   };
@@ -325,7 +345,7 @@
 

[PATCH] D45068: [NVPTX, CUDA] Added support for m8n32k16 and m32n8k16 variants of wmma instructions.

2018-03-29 Thread Justin Lebar via Phabricator via cfe-commits
jlebar accepted this revision.
jlebar added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Driver/ToolChains/Cuda.cpp:578
+  if (CudaInstallation.version() >= CudaVersion::CUDA_91) {
+// CUDA-9 uses new instructions that are only available in PTX6.1
+PtxFeature = "+ptx61";

CUDA-9.1?


https://reviews.llvm.org/D45068



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


[PATCH] D45068: [NVPTX, CUDA] Added support for m8n32k16 and m32n8k16 variants of wmma instructions.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
tra added a reviewer: jlebar.
Herald added subscribers: hiraditya, sanjoy, jholewinski.

The new instructions were added added for sm_70+ GPUs in CUDA-9.1.


https://reviews.llvm.org/D45068

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/CodeGen/builtins-nvptx-sm_70.cu
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTX.td
  llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
  llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/test/CodeGen/NVPTX/wmma.py

Index: llvm/test/CodeGen/NVPTX/wmma.py
===
--- llvm/test/CodeGen/NVPTX/wmma.py
+++ llvm/test/CodeGen/NVPTX/wmma.py
@@ -2,7 +2,7 @@
 # generates correct instructions for them.
 
 # RUN: python %s > %t.ll
-# RUN: llc < %t.ll -march=nvptx64 -mcpu=sm_70 -mattr=+ptx60 | FileCheck %t.ll
+# RUN: llc < %t.ll -march=nvptx64 -mcpu=sm_70 -mattr=+ptx61 | FileCheck %t.ll
 
 from itertools import product
 from string import Template
@@ -36,33 +36,36 @@
 check_f16_4 = "{{%s}}" % ", *".join(["%hh[0-9]+"] * 4)
 check_f32_8 = "{{%s}}" % ", *".join(["%f[0-9]+"] * 8)
 
+known_geoms = ["m16n16k16", "m8n32k16", "m32n8k16"]
+
 def gen_wmma_load_tests():
   load_template = """
 declare ${ret_ty} @${intrinsic}(i8 ${as}* %src ${extra_args});
 
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define ${ret_ty} @test_${function}(i8 ${as}* %src ${extra_args}) {
-; CHECK ${instruction}
+; CHECK: ${instruction}
 ; CHECK: {${check_result}}
 ; CHECK: [%rd{{[0-9]+}}]${stride_pattern}
   %v0 = call ${ret_ty} @${intrinsic}(i8 ${as}* %src ${extra_args});
   ret ${ret_ty} %v0;
 }
 
 ; CHECK-LABEL: .func{{.*}}test_${function}_o(
 define ${ret_ty} @test_${function}_o(i8 ${as}* %src ${extra_args}) {
-; CHECK ${instruction}
+; CHECK: ${instruction}
 ; CHECK: {${check_result}}
 ; CHECK: [%rd{{[0-9]+}}+128]${stride_pattern}
   %src1 = getelementptr i8, i8 ${as}* %src, i32 128;
   %v0 = call ${ret_ty} @${intrinsic}(i8 ${as}* %src1 ${extra_args});
   ret ${ret_ty} %v0;
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.load.${abc}.${layout}${stride}.${itype}.${pspace}"
-  instruction_template = "wmma.load.${abc}.sync.${geom}.${layout}${space}.${itype}"
+  instruction_template = "wmma.load.${abc}.sync.${layout}.${geom}${space}.${itype}"
 
-  for abc, layout, space, stride, itype in product(
+  for geom, abc, layout, space, stride, itype in product(
+  known_geoms,
   "abc",
   ["row","col"],
   ["",".shared",".global"],
@@ -77,7 +80,7 @@
 "itype" : itype,
 "pspace" : get_pspace(space),
 "as" : "addrspace(%d)" % get_aspace(space),
-"geom"   : "m16n16k16",
+"geom"   : geom,
 }
 
 if itype == "f32" and abc != "c":
@@ -112,27 +115,28 @@
 
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define void @test_${function}(i8 ${as}* %src, ${args}${extra_args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}
+; CHECK: ${instruction} {{.*}}[%rd{{[0-9+]}}
 ; CHECK: {${check_args}}
 ; CHECK: ${stride_pattern}
   call void @${intrinsic}(i8 ${as}* %src, ${args} ${extra_args});
   ret void
 }
 
 ; CHECK-LABEL: .func{{.*}}test_${function}_o(
 define void @test_${function}_o(i8 ${as}* %src, ${args}${extra_args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}+128]
+; CHECK: ${instruction} {{.*}}[%rd{{[0-9+]}}+128]
 ; CHECK: ${check_args}
 ; CHECK: ${stride_pattern}
   %src1 = getelementptr i8, i8 ${as}* %src, i32 128;
   call void @${intrinsic}(i8 ${as}* %src1, ${args}${extra_args});
   ret void
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.store.${abc}.${layout}${stride}.${itype}.${pspace}"
-  instruction_template = "wmma.store.${abc}.sync.${geom}.${layout}${space}.${itype}"
+  instruction_template = "wmma.store.${abc}.sync.${layout}.${geom}${space}.${itype}"
 
-  for abc, layout, space, stride, itype in product(
+  for geom, abc, layout, space, stride, itype in product(
+  known_geoms,
   "d",
   ["row","col"],
   ["",".shared",".global"],
@@ -147,7 +151,7 @@
 "itype" : itype,
 "pspace" : get_pspace(space),
 "as" : "addrspace(%d)" % get_aspace(space),
-"geom"   : "m16n16k16",
+"geom"   : geom,
 }
 
 test_params = params
@@ -174,20 +178,21 @@
 ; CHECK-LABEL: .func {{.*}}test_${function}(
 define ${ret_ty} @test_${function}(
 ${args}) {
-; CHECK ${instruction} {{.*}}[%rd{{[0-9+]}}
-; CHECK ${check_d}
-; CHECK ${check_ab}
-; CHECK ${check_ab}
-; CHECK ${check_c}
+; CHECK: ${instruction}
+; CHECK-NEXT: ${check_d}
+; CHECK-NEXT: ${check_ab}
+; CHECK-NEXT: ${check_ab}
+; CHECK-NEXT: ${check_c}
   %r = call ${ret_ty} @${intrinsic}(
 ${args});
   ret ${ret_ty} %r;
 }
 """
   intrinsic_template = "llvm.nvvm.wmma.${geom}.mma.${alayout}.${blayout}.${dtype}.${ctype}${satf}"
   instruction_template = 

r328845 - Hoist MethodVFTableLocation out of MicrosoftVTableContext, NFC

2018-03-29 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Mar 29 15:42:24 2018
New Revision: 328845

URL: http://llvm.org/viewvc/llvm-project?rev=328845=rev
Log:
Hoist MethodVFTableLocation out of MicrosoftVTableContext, NFC

This allows forward declaring it so that we can add it to
MicrosoftMangleContext::mangleVirtualMemPtrThunk without including
VTableBuilder.h. That saves a hashtable lookup when emitting virtual
member pointer functions.

It also shortens a really long type name. This struct has "VFtable" in
the name, so it seems pretty unlikely that someone will assume it is
generally useful for non-MS C++ ABI stuff.

Modified:
cfe/trunk/include/clang/AST/Mangle.h
cfe/trunk/include/clang/AST/VTableBuilder.h
cfe/trunk/lib/AST/MicrosoftMangle.cpp
cfe/trunk/lib/AST/VTableBuilder.cpp
cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp

Modified: cfe/trunk/include/clang/AST/Mangle.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Mangle.h?rev=328845=328844=328845=diff
==
--- cfe/trunk/include/clang/AST/Mangle.h (original)
+++ cfe/trunk/include/clang/AST/Mangle.h Thu Mar 29 15:42:24 2018
@@ -30,6 +30,7 @@ namespace clang {
   class CXXDestructorDecl;
   class CXXMethodDecl;
   class FunctionDecl;
+  struct MethodVFTableLocation;
   class NamedDecl;
   class ObjCMethodDecl;
   class StringLiteral;
@@ -201,7 +202,8 @@ public:
raw_ostream ) = 0;
 
   virtual void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
-raw_ostream &) = 0;
+const MethodVFTableLocation ,
+raw_ostream ) = 0;
 
   virtual void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
const CXXRecordDecl *DstRD,

Modified: cfe/trunk/include/clang/AST/VTableBuilder.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/VTableBuilder.h?rev=328845=328844=328845=diff
==
--- cfe/trunk/include/clang/AST/VTableBuilder.h (original)
+++ cfe/trunk/include/clang/AST/VTableBuilder.h Thu Mar 29 15:42:24 2018
@@ -479,41 +479,42 @@ struct VirtualBaseInfo {
   VPtrInfoVector VBPtrPaths;
 };
 
+struct MethodVFTableLocation {
+  /// If nonzero, holds the vbtable index of the virtual base with the vfptr.
+  uint64_t VBTableIndex;
+
+  /// If nonnull, holds the last vbase which contains the vfptr that the
+  /// method definition is adjusted to.
+  const CXXRecordDecl *VBase;
+
+  /// This is the offset of the vfptr from the start of the last vbase, or the
+  /// complete type if there are no virtual bases.
+  CharUnits VFPtrOffset;
+
+  /// Method's index in the vftable.
+  uint64_t Index;
+
+  MethodVFTableLocation()
+  : VBTableIndex(0), VBase(nullptr), VFPtrOffset(CharUnits::Zero()),
+Index(0) {}
+
+  MethodVFTableLocation(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
+CharUnits VFPtrOffset, uint64_t Index)
+  : VBTableIndex(VBTableIndex), VBase(VBase), VFPtrOffset(VFPtrOffset),
+Index(Index) {}
+
+  bool operator<(const MethodVFTableLocation ) const {
+if (VBTableIndex != other.VBTableIndex) {
+  assert(VBase != other.VBase);
+  return VBTableIndex < other.VBTableIndex;
+}
+return std::tie(VFPtrOffset, Index) <
+   std::tie(other.VFPtrOffset, other.Index);
+  }
+};
+
 class MicrosoftVTableContext : public VTableContextBase {
 public:
-  struct MethodVFTableLocation {
-/// If nonzero, holds the vbtable index of the virtual base with the vfptr.
-uint64_t VBTableIndex;
-
-/// If nonnull, holds the last vbase which contains the vfptr that the
-/// method definition is adjusted to.
-const CXXRecordDecl *VBase;
-
-/// This is the offset of the vfptr from the start of the last vbase, or 
the
-/// complete type if there are no virtual bases.
-CharUnits VFPtrOffset;
-
-/// Method's index in the vftable.
-uint64_t Index;
-
-MethodVFTableLocation()
-: VBTableIndex(0), VBase(nullptr), VFPtrOffset(CharUnits::Zero()),
-  Index(0) {}
-
-MethodVFTableLocation(uint64_t VBTableIndex, const CXXRecordDecl *VBase,
-  CharUnits VFPtrOffset, uint64_t Index)
-: VBTableIndex(VBTableIndex), VBase(VBase),
-  VFPtrOffset(VFPtrOffset), Index(Index) {}
-
-bool operator<(const MethodVFTableLocation ) const {
-  if (VBTableIndex != other.VBTableIndex) {
-assert(VBase != other.VBase);
-return VBTableIndex < other.VBTableIndex;
-  }
-  return std::tie(VFPtrOffset, Index) <
- std::tie(other.VFPtrOffset, other.Index);
-}
-  };
 
 private:
   ASTContext 

Modified: cfe/trunk/lib/AST/MicrosoftMangle.cpp
URL: 

[PATCH] D45007: [clangd] Use compile-command interpolation to provide commands for header files.

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Sending for review in case you have an opinion about whether it's worth 
plumbing a flag through here, or if it's fine to just always do it.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45007



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


[PATCH] D45006: [Tooling] A CompilationDatabase wrapper that infers header commands.

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 140349.
sammccall added a comment.

Add tests, fix minor bugs, add lots of comments and structure.


Repository:
  rC Clang

https://reviews.llvm.org/D45006

Files:
  include/clang/Tooling/CompilationDatabase.h
  lib/Tooling/CMakeLists.txt
  lib/Tooling/InterpolatingCompilationDatabase.cpp
  unittests/Tooling/CompilationDatabaseTest.cpp

Index: unittests/Tooling/CompilationDatabaseTest.cpp
===
--- unittests/Tooling/CompilationDatabaseTest.cpp
+++ unittests/Tooling/CompilationDatabaseTest.cpp
@@ -626,5 +626,99 @@
   EXPECT_EQ(2, Argc);
 }
 
+struct MemCDB : public CompilationDatabase {
+  using EntryMap = llvm::StringMap>;
+  EntryMap Entries;
+  MemCDB(const EntryMap ) : Entries(E) {}
+
+  std::vector getCompileCommands(StringRef F) const override {
+auto Ret = Entries.lookup(F);
+return {Ret.begin(), Ret.end()};
+  }
+
+  std::vector getAllFiles() const override {
+std::vector Result;
+for (const auto  : Entries)
+  Result.push_back(Entry.first());
+return Result;
+  }
+};
+
+class InterpolateTest : public ::testing::Test {
+protected:
+  // Adds an entry to the underlying compilation database.
+  // A flag is injected: -D , so the command used can be identified.
+  void add(llvm::StringRef File, llvm::StringRef Flags = "") {
+llvm::SmallVector Argv = {"clang", File, "-D", File};
+llvm::SplitString(Flags, Argv);
+llvm::SmallString<32> Dir;
+llvm::sys::path::system_temp_directory(false, Dir);
+Entries[path(File)].push_back(
+{Dir, File, {Argv.begin(), Argv.end()}, "foo.o"});
+  }
+
+  // Turn a unix path fragment (foo/bar.h) into a native path (C:\tmp\foo\bar.h)
+  std::string path(llvm::SmallString<32> File) {
+llvm::SmallString<32> Dir;
+llvm::sys::path::system_temp_directory(false, Dir);
+llvm::sys::path::native(File);
+llvm::SmallString<64> Result;
+llvm::sys::path::append(Result, Dir, File);
+return Result.str();
+  }
+
+  // Look up the command from a relative path, and return it in string form.
+  // The input file is not included in the returned command.
+  std::string getCommand(llvm::StringRef F) {
+auto Results =
+inferMissingCompileCommands(llvm::make_unique(Entries))
+->getCompileCommands(path(F));
+if (Results.empty())
+  return "none";
+// drop the input file argument, so tests don't have to deal with path().
+EXPECT_EQ(Results[0].CommandLine.back(), path(F))
+<< "Last arg should be the file";
+Results[0].CommandLine.pop_back();
+return llvm::join(Results[0].CommandLine, " ");
+  }
+
+  MemCDB::EntryMap Entries;
+};
+
+TEST_F(InterpolateTest, Nearby) {
+  add("dir/foo.cpp");
+  add("dir/bar.cpp");
+  add("an/other/foo.cpp");
+
+  // great: dir and name both match (prefix or suffix)
+  EXPECT_EQ(getCommand("dir/f.cpp"), "clang -D dir/foo.cpp");
+  EXPECT_EQ(getCommand("dir/o.cpp"), "clang -D dir/foo.cpp");
+  // no name match. prefer matching dir, break ties by alpha
+  EXPECT_EQ(getCommand("dir/a.cpp"), "clang -D dir/bar.cpp");
+  // an exact name match beats one segment of directory match
+  EXPECT_EQ(getCommand("some/other/bar.h"), "clang -x c++ -D dir/bar.cpp");
+  // two segments of directory match beat a prefix name match
+  EXPECT_EQ(getCommand("an/other/b.cpp"), "clang -D an/other/foo.cpp");
+  // if nothing matches at all, we still get the closest alpha match
+  EXPECT_EQ(getCommand("below/some/obscure/path.cpp"),
+"clang -D an/other/foo.cpp");
+}
+
+TEST_F(InterpolateTest, Language) {
+  add("dir/foo.cpp");
+  add("dir/baz.cee", "-x c");
+
+  // extension changed, so we add explicit language flags
+  EXPECT_EQ(getCommand("foo.h"), "clang -x c++ -D dir/foo.cpp");
+  // but we don't add -x if it's already there
+  EXPECT_EQ(getCommand("baz.h"), "clang -D dir/baz.cee -x c");
+}
+
+TEST_F(InterpolateTest, Strip) {
+  add("dir/foo.cpp", "-o foo.o -Wall");
+  // the -o option and the input file are removed, but -Wall is preserved.
+  EXPECT_EQ(getCommand("dir/bar.cpp"), "clang -D dir/foo.cpp -Wall");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: lib/Tooling/InterpolatingCompilationDatabase.cpp
===
--- /dev/null
+++ lib/Tooling/InterpolatingCompilationDatabase.cpp
@@ -0,0 +1,340 @@
+//===- InterpolatingCompilationDatabase.cpp -*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// InterpolatingCompilationDatabase wraps another CompilationDatabase and
+// attempts to heuristically determine appropriate compile commands for files
+// that are not included, such as 

r328837 - [analyzer] Fix target triple for autorelease-write-checker test

2018-03-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Mar 29 15:28:04 2018
New Revision: 328837

URL: http://llvm.org/viewvc/llvm-project?rev=328837=rev
Log:
[analyzer] Fix target triple for autorelease-write-checker test

Modified:
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m

Modified: cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/autoreleasewritechecker_test.m?rev=328837=328836=328837=diff
==
--- cfe/trunk/test/Analysis/autoreleasewritechecker_test.m (original)
+++ cfe/trunk/test/Analysis/autoreleasewritechecker_test.m Thu Mar 29 15:28:04 
2018
@@ -1,4 +1,5 @@
-// RUN: %clang_analyze_cc1 -DARC -fobjc-arc 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -fblocks -verify
+// RUN: %clang_analyze_cc1 -DARC -fobjc-arc 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -triple x86_64-darwin 
-fblocks -verify
+// RUN: %clang_analyze_cc1 -DNOARC 
-analyzer-checker=core,osx.cocoa.AutoreleaseWrite %s -fblocks -triple 
x86_64-darwin -verify
 
 
 typedef signed char BOOL;


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


r328836 - Set dso_local on cfi_slowpath.

2018-03-29 Thread Rafael Espindola via cfe-commits
Author: rafael
Date: Thu Mar 29 15:08:01 2018
New Revision: 328836

URL: http://llvm.org/viewvc/llvm-project?rev=328836=rev
Log:
Set dso_local on cfi_slowpath.

Modified:
cfe/trunk/lib/CodeGen/CGExpr.cpp
cfe/trunk/test/CodeGen/cfi-icall-cross-dso.c

Modified: cfe/trunk/lib/CodeGen/CGExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGExpr.cpp?rev=328836=328835=328836=diff
==
--- cfe/trunk/lib/CodeGen/CGExpr.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGExpr.cpp Thu Mar 29 15:08:01 2018
@@ -2975,6 +2975,7 @@ void CodeGenFunction::EmitCfiSlowPathChe
   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
 
   llvm::CallInst *CheckCall;
+  llvm::Constant *SlowPathFn;
   if (WithDiag) {
 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
 auto *InfoPtr =
@@ -2983,20 +2984,20 @@ void CodeGenFunction::EmitCfiSlowPathChe
 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
 
-llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath_diag",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
 false));
 CheckCall = Builder.CreateCall(
-SlowPathDiagFn,
-{TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
+SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
   } else {
-llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
   }
 
+  CGM.setDSOLocal(cast(SlowPathFn->stripPointerCasts()));
   CheckCall->setDoesNotThrow();
 
   EmitBlock(Cont);

Modified: cfe/trunk/test/CodeGen/cfi-icall-cross-dso.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/cfi-icall-cross-dso.c?rev=328836=328835=328836=diff
==
--- cfe/trunk/test/CodeGen/cfi-icall-cross-dso.c (original)
+++ cfe/trunk/test/CodeGen/cfi-icall-cross-dso.c Thu Mar 29 15:08:01 2018
@@ -39,6 +39,11 @@
 // MS-DIAG: call void @__cfi_slowpath_diag(i64 4195979634929632483, i8* 
%{{.*}}, {{.*}}@[[DATA]]{{.*}}) {{.*}}, !nosanitize
 // MS-TRAP: call void @__cfi_slowpath(i64 4195979634929632483, i8* %{{.*}}) 
{{.*}}, !nosanitize
 
+// ITANIUM-DIAG: declare void @__cfi_slowpath_diag(
+// ITANIUM-TRAP: declare void @__cfi_slowpath(
+// MS-DIAG: declare dso_local void @__cfi_slowpath_diag(
+// MS-TRAP: declare dso_local void @__cfi_slowpath(
+
 void caller(void (*f)()) {
   f();
 }


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


r328835 - [analyzer] Better pretty-printing of regions in exploded graph

2018-03-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Mar 29 15:07:58 2018
New Revision: 328835

URL: http://llvm.org/viewvc/llvm-project?rev=328835=rev
Log:
[analyzer] Better pretty-printing of regions in exploded graph

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp?rev=328835=328834=328835=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp Thu Mar 29 15:07:58 2018
@@ -2482,7 +2482,7 @@ void ExprEngine::VisitCommonDeclRefExpr(
 assert(Ex->isGLValue() || VD->getType()->isVoidType());
 const LocationContext *LocCtxt = Pred->getLocationContext();
 const Decl *D = LocCtxt->getDecl();
-const auto *MD = D ? dyn_cast(D) : nullptr;
+const auto *MD = dyn_cast_or_null(D);
 const auto *DeclRefEx = dyn_cast(Ex);
 Optional> VInfo;
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp?rev=328835=328834=328835=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/MemRegion.cpp Thu Mar 29 15:07:58 2018
@@ -430,7 +430,7 @@ void BlockDataRegion::dumpToStream(raw_o
   for (BlockDataRegion::referenced_vars_iterator
  I = referenced_vars_begin(),
  E = referenced_vars_end(); I != E; ++I)
-os << "(" << I.getCapturedRegion() << "," <<
+os << "(" << I.getCapturedRegion() << "<-" <<
  I.getOriginalRegion() << ") ";
   os << '}';
 }
@@ -483,7 +483,12 @@ void SymbolicRegion::dumpToStream(raw_os
 }
 
 void VarRegion::dumpToStream(raw_ostream ) const {
-  os << *cast(D);
+  const auto *VD = cast(D);
+  if (const auto *ID = VD->getIdentifier()) {
+os << ID->getName();
+  } else {
+os << "VarRegion{" << static_cast(this) << '}';
+  }
 }
 
 LLVM_DUMP_METHOD void RegionRawOffset::dump() const {


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


[PATCH] D45054: Set dso_local on cfi_slowpath

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola closed this revision.
espindola added a comment.

328836


https://reviews.llvm.org/D45054



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: docs/ReleaseNotes.rst:60
 
+- New module `abseil` for checks related to the `Abseil `_
+  library.

Looks like you copied new version of file over old one. svn update and svn diff 
should be made instead.


https://reviews.llvm.org/D45050



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


[PATCH] D44985: [CUDA] Let device-side shared variables be initialized with undef

2018-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGDecl.cpp:235-240
+  if (Ty.getAddressSpace() != LangAS::opencl_local &&
+  !(getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
+D.hasAttr()))
 Init = EmitNullConstant(Ty);
   else
 Init = llvm::UndefValue::get(LTy);

tra wrote:
> This is too hard to read. Inverting it makes it somewhat easier to understand 
> -- `either opencl_local or device-side CUDA shared are undef`.
> ```
>   if (Ty.getAddressSpace() == LangAS::opencl_local 
>   || (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
>   D.hasAttr()))
> Init = llvm::UndefValue::get(LTy);
>   else
> Init = EmitNullConstant(Ty);
> ```
> 
I assume getLangOpts().CUDAIsDevice implies getLangOpts().CUDA, so you really 
only need to check CUDAIsDevice.  But it might be faster still to just check 
for the attribute.


https://reviews.llvm.org/D44985



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 140337.
Charusso marked 6 inline comments as done.
Charusso added a comment.

Truly fixed everything according to the comments.


https://reviews.llvm.org/D45050

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp

Index: test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
@@ -0,0 +1,153 @@
+// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- -- -std=c++11
+
+typedef unsigned int size_t;
+typedef int errno_t;
+size_t wcslen(const wchar_t *);
+wchar_t *wcschr(const wchar_t *, int);
+errno_t *wcsncpy_s(wchar_t *, const wchar_t *, size_t);
+
+void *alloca(size_t);
+void *calloc(size_t, size_t);
+void *malloc(size_t);
+void *realloc(void *, size_t);
+
+void *wmemcpy(void *, const void *, size_t);
+errno_t wmemcpy_s(void *, size_t, const void *, size_t);
+void *wmemchr(const void *, int, size_t);
+void *wmemmove(void *, const void *, size_t);
+errno_t wmemmove_s(void *, size_t, const void *, size_t);
+void *wmemset(void *, int, size_t);
+
+int wcsncmp(const wchar_t *, const wchar_t *, size_t);
+size_t wcsxfrm(wchar_t *, const wchar_t *, size_t);
+
+namespace std {
+using ::wcsncpy_s;
+using ::wmemcpy;
+using ::wcslen;
+}
+
+void bad_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'alloca' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: alloca(wcslen(src) + 1);
+}
+
+void good_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src) + 1);
+}
+
+void bad_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc(wcslen(src), sizeof(wchar_t));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'calloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void good_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void bad_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc(wcslen(src) * 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'malloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: malloc((wcslen(src) * 2) + 1);
+}
+
+void good_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc((wcslen(src) * 2) + 1);
+}
+
+void bad_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + wcslen(src)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'realloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void good_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void bad_wmemcpy(wchar_t *dest, const wchar_t *src) {
+  std::wmemcpy(dest, src, std::wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void good_wmemcpy_cxx11(wchar_t *dest, const wchar_t *src) {
+  std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void bad_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wmemcpy_s(dest, wcslen(dest), src, wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy_s' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcsncpy_s(dest, src, wcslen(src));
+}
+
+void good_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wcsncpy_s(dest, src, wcslen(src));
+}
+
+void bad_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)wmemchr(src, '\0', wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'wmemchr' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcschr(src, '\0');
+}
+
+void good_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = wcschr(src, '\0');
+}
+
+void bad_wmemmove(wchar_t *dest, const wchar_t *src) {
+  wmemmove(dest, src, 

[PATCH] D45061: [NVPTX, CUDA] Use custom feature detection to handle NVPTX target builtins.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 140334.
tra added a comment.

Run the tests with -target-cpu sm_61 to make sure intrinsics that require sm_60 
are still enabled.


https://reviews.llvm.org/D45061

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/include/clang/Basic/Cuda.h
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/test/CodeGen/builtins-nvptx-ptx50.cu
  clang/test/CodeGen/builtins-nvptx.c
  llvm/lib/Target/NVPTX/NVPTX.td
  llvm/lib/Target/NVPTX/NVPTXSubtarget.h

Index: llvm/lib/Target/NVPTX/NVPTXSubtarget.h
===
--- llvm/lib/Target/NVPTX/NVPTXSubtarget.h
+++ llvm/lib/Target/NVPTX/NVPTXSubtarget.h
@@ -48,10 +48,6 @@
   // FrameLowering class because TargetFrameLowering is abstract.
   NVPTXFrameLowering FrameLowering;
 
-protected:
-  // Processor supports scoped atomic operations.
-  bool HasAtomScope;
-
 public:
   /// This constructor initializes the data members to match that
   /// of the specified module.
@@ -74,7 +70,7 @@
   }
 
   bool hasAtomAddF64() const { return SmVersion >= 60; }
-  bool hasAtomScope() const { return HasAtomScope; }
+  bool hasAtomScope() const { return SmVersion >= 60; }
   bool hasAtomBitwise64() const { return SmVersion >= 32; }
   bool hasAtomMinMax64() const { return SmVersion >= 32; }
   bool hasLDG() const { return SmVersion >= 32; }
Index: llvm/lib/Target/NVPTX/NVPTX.td
===
--- llvm/lib/Target/NVPTX/NVPTX.td
+++ llvm/lib/Target/NVPTX/NVPTX.td
@@ -53,9 +53,6 @@
 def SM70 : SubtargetFeature<"sm_70", "SmVersion", "70",
  "Target SM 7.0">;
 
-def SATOM : SubtargetFeature<"satom", "HasAtomScope", "true",
- "Atomic operations with scope">;
-
 // PTX Versions
 def PTX32 : SubtargetFeature<"ptx32", "PTXVersion", "32",
  "Use PTX version 3.2">;
@@ -88,10 +85,10 @@
 def : Proc<"sm_50", [SM50, PTX40]>;
 def : Proc<"sm_52", [SM52, PTX41]>;
 def : Proc<"sm_53", [SM53, PTX42]>;
-def : Proc<"sm_60", [SM60, PTX50, SATOM]>;
-def : Proc<"sm_61", [SM61, PTX50, SATOM]>;
-def : Proc<"sm_62", [SM62, PTX50, SATOM]>;
-def : Proc<"sm_70", [SM70, PTX60, SATOM]>;
+def : Proc<"sm_60", [SM60, PTX50]>;
+def : Proc<"sm_61", [SM61, PTX50]>;
+def : Proc<"sm_62", [SM62, PTX50]>;
+def : Proc<"sm_70", [SM70, PTX60]>;
 
 def NVPTXInstrInfo : InstrInfo {
 }
Index: clang/test/CodeGen/builtins-nvptx.c
===
--- clang/test/CodeGen/builtins-nvptx.c
+++ clang/test/CodeGen/builtins-nvptx.c
@@ -5,6 +5,9 @@
 // RUN: %clang_cc1 -triple nvptx64-unknown-unknown -target-cpu sm_60 \
 // RUN:-fcuda-is-device -S -emit-llvm -o - -x cuda %s \
 // RUN:   | FileCheck -check-prefix=CHECK -check-prefix=LP64 %s
+// RUN: %clang_cc1 -triple nvptx64-unknown-unknown -target-cpu sm_61 \
+// RUN:-fcuda-is-device -S -emit-llvm -o - -x cuda %s \
+// RUN:   | FileCheck -check-prefix=CHECK -check-prefix=LP64 %s
 // RUN: %clang_cc1 -triple nvptx-unknown-unknown -target-cpu sm_53 \
 // RUN:   -DERROR_CHECK -fcuda-is-device -S -o /dev/null -x cuda -verify %s
 
@@ -292,245 +295,245 @@
 #if ERROR_CHECK || __CUDA_ARCH__ >= 600
 
   // CHECK: call i32 @llvm.nvvm.atomic.add.gen.i.cta.i32.p0i32
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_i' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_i' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_i(ip, i);
   // LP32: call i32 @llvm.nvvm.atomic.add.gen.i.cta.i32.p0i32
   // LP64: call i64 @llvm.nvvm.atomic.add.gen.i.cta.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_l' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_l' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_l(, l);
   // CHECK: call i64 @llvm.nvvm.atomic.add.gen.i.cta.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_ll' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_ll' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_ll(, ll);
   // CHECK: call i32 @llvm.nvvm.atomic.add.gen.i.sys.i32.p0i32
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_i' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_i' needs target feature sm_60}}
   __nvvm_atom_sys_add_gen_i(ip, i);
   // LP32: call i32 @llvm.nvvm.atomic.add.gen.i.sys.i32.p0i32
   // LP64: call i64 @llvm.nvvm.atomic.add.gen.i.sys.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_l' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_l' needs target feature sm_60}}
   __nvvm_atom_sys_add_gen_l(, l);
   // CHECK: call i64 @llvm.nvvm.atomic.add.gen.i.sys.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_ll' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_ll' needs target feature sm_60}}
   

[PATCH] D44985: [CUDA] Let device-side shared variables be initialized with undef

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

Still LGTM.


https://reviews.llvm.org/D44985



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


[PATCH] D44815: [AArch64]: Add support for parsing rN registers.

2018-03-29 Thread Manoj Gupta via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL328829: [AArch64]: Add support for parsing rN registers. 
(authored by manojgupta, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D44815

Files:
  cfe/trunk/lib/Basic/Targets/AArch64.cpp
  cfe/trunk/test/CodeGen/aarch64-inline-asm.c


Index: cfe/trunk/test/CodeGen/aarch64-inline-asm.c
===
--- cfe/trunk/test/CodeGen/aarch64-inline-asm.c
+++ cfe/trunk/test/CodeGen/aarch64-inline-asm.c
@@ -54,3 +54,23 @@
 asm("ldxr %0, %1" : "=r"(val) : "Q"(var));
 // CHECK: call i32 asm "ldxr $0, $1", "=r,*Q"(i64* @var)
 }
+
+void test_gcc_registers(void) {
+register unsigned long reg0 asm("r0") = 0;
+register unsigned long reg1 asm("r1") = 1;
+register unsigned int  reg29 asm("r29") = 2;
+register unsigned int  reg30 asm("r30") = 3;
+
+// Test remapping register names in register ... asm("rN") statments.
+// rN register operands in these two inline assembly lines
+// should get renamed to valid AArch64 registers.
+asm volatile("hvc #0" : : "r" (reg0), "r" (reg1));
+// CHECK: call void asm sideeffect "hvc #0", "{x0},{x1}"
+asm volatile("hvc #0" : : "r" (reg29), "r" (reg30));
+// CHECK: call void asm sideeffect "hvc #0", "{fp},{lr}"
+
+// rN registers when used without register ... asm("rN") syntax
+// should not be remapped.
+asm volatile("mov r0, r1\n");
+// CHECK: call void asm sideeffect "mov r0, r1\0A", ""()
+}
Index: cfe/trunk/lib/Basic/Targets/AArch64.cpp
===
--- cfe/trunk/lib/Basic/Targets/AArch64.cpp
+++ cfe/trunk/lib/Basic/Targets/AArch64.cpp
@@ -308,7 +308,40 @@
 }
 
 const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = {
-{{"w31"}, "wsp"}, {{"x29"}, "fp"}, {{"x30"}, "lr"}, {{"x31"}, "sp"},
+{{"w31"}, "wsp"},
+{{"x31"}, "sp"},
+// GCC rN registers are aliases of xN registers.
+{{"r0"}, "x0"},
+{{"r1"}, "x1"},
+{{"r2"}, "x2"},
+{{"r3"}, "x3"},
+{{"r4"}, "x4"},
+{{"r5"}, "x5"},
+{{"r6"}, "x6"},
+{{"r7"}, "x7"},
+{{"r8"}, "x8"},
+{{"r9"}, "x9"},
+{{"r10"}, "x10"},
+{{"r11"}, "x11"},
+{{"r12"}, "x12"},
+{{"r13"}, "x13"},
+{{"r14"}, "x14"},
+{{"r15"}, "x15"},
+{{"r16"}, "x16"},
+{{"r17"}, "x17"},
+{{"r18"}, "x18"},
+{{"r19"}, "x19"},
+{{"r20"}, "x20"},
+{{"r21"}, "x21"},
+{{"r22"}, "x22"},
+{{"r23"}, "x23"},
+{{"r24"}, "x24"},
+{{"r25"}, "x25"},
+{{"r26"}, "x26"},
+{{"r27"}, "x27"},
+{{"r28"}, "x28"},
+{{"r29", "x29"}, "fp"},
+{{"r30", "x30"}, "lr"},
 // The S/D/Q and W/X registers overlap, but aren't really aliases; we
 // don't want to substitute one of these for a different-sized one.
 };


Index: cfe/trunk/test/CodeGen/aarch64-inline-asm.c
===
--- cfe/trunk/test/CodeGen/aarch64-inline-asm.c
+++ cfe/trunk/test/CodeGen/aarch64-inline-asm.c
@@ -54,3 +54,23 @@
 asm("ldxr %0, %1" : "=r"(val) : "Q"(var));
 // CHECK: call i32 asm "ldxr $0, $1", "=r,*Q"(i64* @var)
 }
+
+void test_gcc_registers(void) {
+register unsigned long reg0 asm("r0") = 0;
+register unsigned long reg1 asm("r1") = 1;
+register unsigned int  reg29 asm("r29") = 2;
+register unsigned int  reg30 asm("r30") = 3;
+
+// Test remapping register names in register ... asm("rN") statments.
+// rN register operands in these two inline assembly lines
+// should get renamed to valid AArch64 registers.
+asm volatile("hvc #0" : : "r" (reg0), "r" (reg1));
+// CHECK: call void asm sideeffect "hvc #0", "{x0},{x1}"
+asm volatile("hvc #0" : : "r" (reg29), "r" (reg30));
+// CHECK: call void asm sideeffect "hvc #0", "{fp},{lr}"
+
+// rN registers when used without register ... asm("rN") syntax
+// should not be remapped.
+asm volatile("mov r0, r1\n");
+// CHECK: call void asm sideeffect "mov r0, r1\0A", ""()
+}
Index: cfe/trunk/lib/Basic/Targets/AArch64.cpp
===
--- cfe/trunk/lib/Basic/Targets/AArch64.cpp
+++ cfe/trunk/lib/Basic/Targets/AArch64.cpp
@@ -308,7 +308,40 @@
 }
 
 const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = {
-{{"w31"}, "wsp"}, {{"x29"}, "fp"}, {{"x30"}, "lr"}, {{"x31"}, "sp"},
+{{"w31"}, "wsp"},
+{{"x31"}, "sp"},
+// GCC rN registers are aliases of xN registers.
+{{"r0"}, "x0"},
+{{"r1"}, "x1"},
+{{"r2"}, "x2"},
+{{"r3"}, "x3"},
+{{"r4"}, "x4"},
+{{"r5"}, "x5"},
+{{"r6"}, "x6"},
+{{"r7"}, "x7"},
+{{"r8"}, "x8"},
+{{"r9"}, "x9"},
+{{"r10"}, "x10"},
+{{"r11"}, "x11"},
+{{"r12"}, "x12"},
+{{"r13"}, "x13"},
+{{"r14"}, "x14"},
+{{"r15"}, "x15"},
+{{"r16"}, "x16"},
+{{"r17"}, 

r328829 - [AArch64]: Add support for parsing rN registers.

2018-03-29 Thread Manoj Gupta via cfe-commits
Author: manojgupta
Date: Thu Mar 29 14:11:15 2018
New Revision: 328829

URL: http://llvm.org/viewvc/llvm-project?rev=328829=rev
Log:
[AArch64]: Add support for parsing rN registers.

Summary:
Allow rN registers to be simply parsed as correspoing xN registers.
The "register ... asm("rN")" is an command to the
compiler's register allocator, not an operand to any individual assembly
instruction. GCC documents this syntax as "...the name of the register
that should be used."

This is needed to support the changes in Linux kernel (see
https://lkml.org/lkml/2018/3/1/268 )

Note: This will add support only for the limited use case of
register ... asm("rN"). Any other uses that make rN leak into assembly
are not supported.

Reviewers: kristof.beyls, rengolin, peter.smith, t.p.northover

Reviewed By: peter.smith

Subscribers: javed.absar, eraman, cfe-commits, srhines

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

Modified:
cfe/trunk/lib/Basic/Targets/AArch64.cpp
cfe/trunk/test/CodeGen/aarch64-inline-asm.c

Modified: cfe/trunk/lib/Basic/Targets/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/AArch64.cpp?rev=328829=328828=328829=diff
==
--- cfe/trunk/lib/Basic/Targets/AArch64.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/AArch64.cpp Thu Mar 29 14:11:15 2018
@@ -308,7 +308,40 @@ ArrayRef AArch64TargetInfo
 }
 
 const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = {
-{{"w31"}, "wsp"}, {{"x29"}, "fp"}, {{"x30"}, "lr"}, {{"x31"}, "sp"},
+{{"w31"}, "wsp"},
+{{"x31"}, "sp"},
+// GCC rN registers are aliases of xN registers.
+{{"r0"}, "x0"},
+{{"r1"}, "x1"},
+{{"r2"}, "x2"},
+{{"r3"}, "x3"},
+{{"r4"}, "x4"},
+{{"r5"}, "x5"},
+{{"r6"}, "x6"},
+{{"r7"}, "x7"},
+{{"r8"}, "x8"},
+{{"r9"}, "x9"},
+{{"r10"}, "x10"},
+{{"r11"}, "x11"},
+{{"r12"}, "x12"},
+{{"r13"}, "x13"},
+{{"r14"}, "x14"},
+{{"r15"}, "x15"},
+{{"r16"}, "x16"},
+{{"r17"}, "x17"},
+{{"r18"}, "x18"},
+{{"r19"}, "x19"},
+{{"r20"}, "x20"},
+{{"r21"}, "x21"},
+{{"r22"}, "x22"},
+{{"r23"}, "x23"},
+{{"r24"}, "x24"},
+{{"r25"}, "x25"},
+{{"r26"}, "x26"},
+{{"r27"}, "x27"},
+{{"r28"}, "x28"},
+{{"r29", "x29"}, "fp"},
+{{"r30", "x30"}, "lr"},
 // The S/D/Q and W/X registers overlap, but aren't really aliases; we
 // don't want to substitute one of these for a different-sized one.
 };

Modified: cfe/trunk/test/CodeGen/aarch64-inline-asm.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/aarch64-inline-asm.c?rev=328829=328828=328829=diff
==
--- cfe/trunk/test/CodeGen/aarch64-inline-asm.c (original)
+++ cfe/trunk/test/CodeGen/aarch64-inline-asm.c Thu Mar 29 14:11:15 2018
@@ -54,3 +54,23 @@ void test_constraint_Q(void) {
 asm("ldxr %0, %1" : "=r"(val) : "Q"(var));
 // CHECK: call i32 asm "ldxr $0, $1", "=r,*Q"(i64* @var)
 }
+
+void test_gcc_registers(void) {
+register unsigned long reg0 asm("r0") = 0;
+register unsigned long reg1 asm("r1") = 1;
+register unsigned int  reg29 asm("r29") = 2;
+register unsigned int  reg30 asm("r30") = 3;
+
+// Test remapping register names in register ... asm("rN") statments.
+// rN register operands in these two inline assembly lines
+// should get renamed to valid AArch64 registers.
+asm volatile("hvc #0" : : "r" (reg0), "r" (reg1));
+// CHECK: call void asm sideeffect "hvc #0", "{x0},{x1}"
+asm volatile("hvc #0" : : "r" (reg29), "r" (reg30));
+// CHECK: call void asm sideeffect "hvc #0", "{fp},{lr}"
+
+// rN registers when used without register ... asm("rN") syntax
+// should not be remapped.
+asm volatile("mov r0, r1\n");
+// CHECK: call void asm sideeffect "mov r0, r1\0A", ""()
+}


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


[clang-tools-extra] r328819 - [clangd] Fix repeated word typo. NFC

2018-03-29 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Thu Mar 29 13:03:16 2018
New Revision: 328819

URL: http://llvm.org/viewvc/llvm-project?rev=328819=rev
Log:
[clangd] Fix repeated word typo. NFC

Modified:
clang-tools-extra/trunk/clangd/JSONExpr.cpp
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp

Modified: clang-tools-extra/trunk/clangd/JSONExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/JSONExpr.cpp?rev=328819=328818=328819=diff
==
--- clang-tools-extra/trunk/clangd/JSONExpr.cpp (original)
+++ clang-tools-extra/trunk/clangd/JSONExpr.cpp Thu Mar 29 13:03:16 2018
@@ -113,7 +113,7 @@ private:
   ++P;
   }
 
-  // On invalid syntax, parseX() functions return false and and set Err.
+  // On invalid syntax, parseX() functions return false and set Err.
   bool parseNumber(char First, double );
   bool parseString(std::string );
   bool parseUnicode(std::string );

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=328819=328818=328819=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Thu Mar 29 
13:03:16 2018
@@ -202,7 +202,7 @@ llvm::Optional getSymbol
 // in a header file, in which case clangd would prefer to use ND as a canonical
 // declaration.
 // FIXME: handle symbol types that are not TagDecl (e.g. functions), if using
-// the the first seen declaration as canonical declaration is not a good enough
+// the first seen declaration as canonical declaration is not a good enough
 // heuristic.
 bool isPreferredDeclaration(const NamedDecl , index::SymbolRoleSet Roles) {
   using namespace clang::ast_matchers;


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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:46
+/// from ' "data_name", "data", ' to just 'data' by "memmoving" it 
char-by-char.
+bool isTrimFunc(const MatchFinder::MatchResult ) {
+  const auto *FuncExpr = Result.Nodes.getNodeAs("expr");

Should be static too.


https://reviews.llvm.org/D45050



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


[PATCH] D45054: Set dso_local on cfi_slowpath

2018-03-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis accepted this revision.
eugenis added a comment.
This revision is now accepted and ready to land.

LGTM then. This naming is confusing.


https://reviews.llvm.org/D45054



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


[PATCH] D44985: [CUDA] Let device-side shared variables be initialized with undef

2018-03-29 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 140329.
yaxunl retitled this revision from "Remove initializer for CUDA shared 
varirable" to "[CUDA] Let device-side shared variables be initialized with 
undef".
yaxunl edited the summary of this revision.
yaxunl added a comment.

Revised by Artem's comment. Improve readability of condition.


https://reviews.llvm.org/D44985

Files:
  lib/CodeGen/CGDecl.cpp
  test/CodeGenCUDA/address-spaces.cu
  test/CodeGenCUDA/device-var-init.cu

Index: test/CodeGenCUDA/device-var-init.cu
===
--- test/CodeGenCUDA/device-var-init.cu
+++ test/CodeGenCUDA/device-var-init.cu
@@ -1,10 +1,14 @@
 // REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
 
 // Make sure we don't allow dynamic initialization for device
 // variables, but accept empty constructors allowed by CUDA.
 
 // RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fcuda-is-device -std=c++11 \
-// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck %s
+// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck -check-prefixes=CHECK,NVPTX %s
+
+// RUN: %clang_cc1 -triple amdgcn -fcuda-is-device -std=c++11 \
+// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck -check-prefixes=CHECK,AMDGCN %s
 
 #ifdef __clang__
 #include "Inputs/cuda.h"
@@ -105,68 +109,120 @@
 __constant__ EC_I_EC c_ec_i_ec;
 // CHECK: @c_ec_i_ec = addrspace(4) externally_initialized global %struct.EC_I_EC zeroinitializer,
 
+// CHECK: @_ZZ2dfvE4s_ec = internal addrspace(3) global %struct.EC undef
+// CHECK: @_ZZ2dfvE5s_etc = internal addrspace(3) global %struct.ETC undef
+
 // We should not emit global initializers for device-side variables.
 // CHECK-NOT: @__cxx_global_var_init
 
 // Make sure that initialization restrictions do not apply to local
 // variables.
 __device__ void df() {
+  // NVPTX:  %[[ec:.*]] = alloca %struct.EC
+  // NVPTX:  %[[ed:.*]] = alloca %struct.ED
+  // NVPTX:  %[[ecd:.*]] = alloca %struct.ECD
+  // NVPTX:  %[[etc:.*]] = alloca %struct.ETC
+  // NVPTX:  %[[uc:.*]] = alloca %struct.UC
+  // NVPTX:  %[[ud:.*]] = alloca %struct.UD
+  // NVPTX:  %[[eci:.*]] = alloca %struct.ECI
+  // NVPTX:  %[[nec:.*]] = alloca %struct.NEC
+  // NVPTX:  %[[ned:.*]] = alloca %struct.NED
+  // NVPTX:  %[[ncv:.*]] = alloca %struct.NCV
+  // NVPTX:  %[[vd:.*]] = alloca %struct.VD
+  // NVPTX:  %[[ncf:.*]] = alloca %struct.NCF
+  // NVPTX:  %[[ncfs:.*]] = alloca %struct.NCFS
+  // NVPTX:  %[[utc:.*]] = alloca %struct.UTC
+  // NVPTX:  %[[netc:.*]] = alloca %struct.NETC
+  // NVPTX:  %[[ec_i_ec:.*]] = alloca %struct.EC_I_EC
+  // NVPTX:  %[[ec_i_ec1:.*]] = alloca %struct.EC_I_EC1
+  // NVPTX:  %[[t_v_t:.*]] = alloca %struct.T_V_T
+  // NVPTX:  %[[t_b_nec:.*]] = alloca %struct.T_B_NEC
+  // NVPTX:  %[[t_f_nec:.*]] = alloca %struct.T_F_NEC
+  // NVPTX:  %[[t_fa_nec:.*]] = alloca %struct.T_FA_NEC
+  // NVPTX:  %[[t_b_ned:.*]] = alloca %struct.T_B_NED
+  // NVPTX:  %[[t_f_ned:.*]] = alloca %struct.T_F_NED
+  // NVPTX:  %[[t_fa_ned:.*]] = alloca %struct.T_FA_NED
+  // AMDGCN:  %[[ec:.*]] = addrspacecast %struct.EC addrspace(5)* %ec to %struct.EC*
+  // AMDGCN:  %[[ed:.*]] = addrspacecast %struct.ED addrspace(5)* %ed to %struct.ED*
+  // AMDGCN:  %[[ecd:.*]] = addrspacecast %struct.ECD addrspace(5)* %ecd to %struct.ECD*
+  // AMDGCN:  %[[etc:.*]] = addrspacecast %struct.ETC addrspace(5)* %etc to %struct.ETC*
+  // AMDGCN:  %[[uc:.*]] = addrspacecast %struct.UC addrspace(5)* %uc to %struct.UC*
+  // AMDGCN:  %[[ud:.*]] = addrspacecast %struct.UD addrspace(5)* %ud to %struct.UD*
+  // AMDGCN:  %[[eci:.*]] = addrspacecast %struct.ECI addrspace(5)* %eci to %struct.ECI*
+  // AMDGCN:  %[[nec:.*]] = addrspacecast %struct.NEC addrspace(5)* %nec to %struct.NEC*
+  // AMDGCN:  %[[ned:.*]] = addrspacecast %struct.NED addrspace(5)* %ned to %struct.NED*
+  // AMDGCN:  %[[ncv:.*]] = addrspacecast %struct.NCV addrspace(5)* %ncv to %struct.NCV*
+  // AMDGCN:  %[[vd:.*]] = addrspacecast %struct.VD addrspace(5)* %vd to %struct.VD*
+  // AMDGCN:  %[[ncf:.*]] = addrspacecast %struct.NCF addrspace(5)* %ncf to %struct.NCF*
+  // AMDGCN:  %[[ncfs:.*]] = addrspacecast %struct.NCFS addrspace(5)* %ncfs to %struct.NCFS*
+  // AMDGCN:  %[[utc:.*]] = addrspacecast %struct.UTC addrspace(5)* %utc to %struct.UTC*
+  // AMDGCN:  %[[netc:.*]] = addrspacecast %struct.NETC addrspace(5)* %netc to %struct.NETC*
+  // AMDGCN:  %[[ec_i_ec:.*]] = addrspacecast %struct.EC_I_EC addrspace(5)* %ec_i_ec to %struct.EC_I_EC*
+  // AMDGCN:  %[[ec_i_ec1:.*]] = addrspacecast %struct.EC_I_EC1 addrspace(5)* %ec_i_ec1 to %struct.EC_I_EC1*
+  // AMDGCN:  %[[t_v_t:.*]] = addrspacecast %struct.T_V_T addrspace(5)* %t_v_t to %struct.T_V_T*
+  // AMDGCN:  %[[t_b_nec:.*]] = addrspacecast %struct.T_B_NEC addrspace(5)* %t_b_nec to %struct.T_B_NEC*
+  // AMDGCN:  %[[t_f_nec:.*]] = addrspacecast %struct.T_F_NEC addrspace(5)* %t_f_nec to %struct.T_F_NEC*
+  // AMDGCN:  %[[t_fa_nec:.*]] = addrspacecast 

[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 140330.
Charusso marked 2 inline comments as done.
Charusso added a comment.

Fixed everything according to the comments.


https://reviews.llvm.org/D45050

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp

Index: test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
@@ -0,0 +1,153 @@
+// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- -- -std=c++11
+
+typedef unsigned int size_t;
+typedef int errno_t;
+size_t wcslen(const wchar_t *);
+wchar_t *wcschr(const wchar_t *, int);
+errno_t *wcsncpy_s(wchar_t *, const wchar_t *, size_t);
+
+void *alloca(size_t);
+void *calloc(size_t, size_t);
+void *malloc(size_t);
+void *realloc(void *, size_t);
+
+void *wmemcpy(void *, const void *, size_t);
+errno_t wmemcpy_s(void *, size_t, const void *, size_t);
+void *wmemchr(const void *, int, size_t);
+void *wmemmove(void *, const void *, size_t);
+errno_t wmemmove_s(void *, size_t, const void *, size_t);
+void *wmemset(void *, int, size_t);
+
+int wcsncmp(const wchar_t *, const wchar_t *, size_t);
+size_t wcsxfrm(wchar_t *, const wchar_t *, size_t);
+
+namespace std {
+using ::wcsncpy_s;
+using ::wmemcpy;
+using ::wcslen;
+}
+
+void bad_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'alloca' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: alloca(wcslen(src) + 1);
+}
+
+void good_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src) + 1);
+}
+
+void bad_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc(wcslen(src), sizeof(wchar_t));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'calloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void good_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void bad_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc(wcslen(src) * 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'malloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: malloc((wcslen(src) * 2) + 1);
+}
+
+void good_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc((wcslen(src) * 2) + 1);
+}
+
+void bad_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + wcslen(src)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'realloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void good_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void bad_wmemcpy(wchar_t *dest, const wchar_t *src) {
+  std::wmemcpy(dest, src, std::wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void good_wmemcpy_cxx11(wchar_t *dest, const wchar_t *src) {
+  std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void bad_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wmemcpy_s(dest, wcslen(dest), src, wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy_s' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcsncpy_s(dest, src, wcslen(src));
+}
+
+void good_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wcsncpy_s(dest, src, wcslen(src));
+}
+
+void bad_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)wmemchr(src, '\0', wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'wmemchr' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcschr(src, '\0');
+}
+
+void good_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = wcschr(src, '\0');
+}
+
+void bad_wmemmove(wchar_t *dest, const wchar_t *src) {
+  wmemmove(dest, src, 

[PATCH] D45054: Set dso_local on cfi_slowpath

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola added a comment.

In https://reviews.llvm.org/D45054#1052118, @eugenis wrote:

> This looks wrong. cfi_slowpath is defined in libclang_rt.cfi, which is linked 
> to the main executable. It is not always dso-local. On Android it is defined 
> in libdl.so and is never dso-local.


And we don't set cfi_local in that case. See the ITANIUM lines is the testcase.

The CodegenModule functions are named setDSOLocal, setDLLImportDLLExport, etc, 
but they only set the corresponding flags when appropriate.


https://reviews.llvm.org/D45054



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


r328827 - [analyzer] Path-insensitive checker for writes into an auto-releasing pointer

2018-03-29 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Mar 29 13:55:34 2018
New Revision: 328827

URL: http://llvm.org/viewvc/llvm-project?rev=328827=rev
Log:
[analyzer] Path-insensitive checker for writes into an auto-releasing pointer

from the wrong auto-releasing pool, as such writes may crash.

rdar://2530

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

Added:
cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
cfe/trunk/test/Analysis/autoreleasewritechecker_test.m
Modified:
cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Modified: cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td?rev=328827=328826=328827=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td (original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Checkers/Checkers.td Thu Mar 29 
13:55:34 2018
@@ -616,6 +616,9 @@ def ObjCSuperDeallocChecker : Checker<"S
   HelpText<"Warn about improper use of '[super dealloc]' in Objective-C">,
   DescFile<"ObjCSuperDeallocChecker.cpp">;
 
+def AutoreleaseWriteChecker : Checker<"AutoreleaseWrite">,
+  HelpText<"Warn about potentially crashing writes to autoreleasing objects 
from different autoreleasing pools in Objective-C">,
+  DescFile<"ObjCAutoreleaseWriteChecker.cpp">;
 } // end "osx.cocoa"
 
 let ParentPackage = Performance in {

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt?rev=328827=328826=328827=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CMakeLists.txt Thu Mar 29 13:55:34 
2018
@@ -63,6 +63,7 @@ add_clang_library(clangStaticAnalyzerChe
   NullabilityChecker.cpp
   NumberObjectConversionChecker.cpp
   ObjCAtSyncChecker.cpp
+  ObjCAutoreleaseWriteChecker.cpp
   ObjCContainersASTChecker.cpp
   ObjCContainersChecker.cpp
   ObjCMissingSuperCallChecker.cpp

Added: cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp?rev=328827=auto
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp 
(added)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ObjCAutoreleaseWriteChecker.cpp Thu 
Mar 29 13:55:34 2018
@@ -0,0 +1,157 @@
+//===- ObjCAutoreleaseWriteChecker.cpp *- C++ 
-*-==//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This file defines ObjCAutoreleaseWriteChecker which warns against writes
+// into autoreleased out parameters which are likely to cause crashes.
+// An example of a problematic write is a write to {@code error} in the example
+// below:
+//
+// - (BOOL) mymethod:(NSError *__autoreleasing *)error list:(NSArray*) list {
+// [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
+//   NSString *myString = obj;
+//   if ([myString isEqualToString:@"error"] && error)
+// *error = [NSError errorWithDomain:@"MyDomain" code:-1];
+// }];
+// return false;
+// }
+//
+// Such code is very likely to crash due to the other queue autorelease pool
+// begin able to free the error object.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
+#include "llvm/ADT/Twine.h"
+
+using namespace clang;
+using namespace ento;
+using namespace ast_matchers;
+
+namespace {
+
+const char *ProblematicWriteBind = "problematicwrite";
+const char *ParamBind = "parambind";
+const char *MethodBind = "methodbind";
+
+class ObjCAutoreleaseWriteChecker : public Checker {
+public:
+  void checkASTCodeBody(const Decl *D,
+AnalysisManager ,
+BugReporter ) const;
+private:
+  std::vector SelectorsWithAutoreleasingPool = {
+  "enumerateObjectsUsingBlock:",
+  "enumerateKeysAndObjectsUsingBlock:",
+  "enumerateKeysAndObjectsWithOptions:usingBlock:",
+  "enumerateObjectsWithOptions:usingBlock:",
+  "enumerateObjectsAtIndexes:options:usingBlock:",
+ 

[PATCH] D45059: [clang-tidy] Add check to catch comparisons in TEMP_FAILURE_RETRY

2018-03-29 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv added a comment.

Thanks!

> Will be good idea to clarify where TEMP_FAILURE_RETRY come from.

Updated the CL summary and added "TEMP_FAILURE_RETRY is a macro provided by 
both glibc and Bionic." to ComparisonInTempFailureRetryCheck.h. Did you have 
anything else in mind?




Comment at: 
docs/clang-tidy/checks/bugprone-comparison-in-temp-failure-retry.rst:6
+
+Checks whether a use of ``TEMP_FAILURE_RETRY`` has a top-level comparison in 
its
+argument. Having such a use is incorrect in the vast majority of cases, and

Eugene.Zelenko wrote:
> Please make first statement same as in Release Notes.
Interpreted "statement" as "sentence". Please let me know if you meant to 
include "Having such a use...", as well


https://reviews.llvm.org/D45059



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


[PATCH] D45052: Mark __cfi_check as dso_local

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola closed this revision.
espindola added a comment.

328825


https://reviews.llvm.org/D45052



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


[PATCH] D45059: [clang-tidy] Add check to catch comparisons in TEMP_FAILURE_RETRY

2018-03-29 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv updated this revision to Diff 140324.
george.burgess.iv marked 3 inline comments as done.
george.burgess.iv edited the summary of this revision.
george.burgess.iv added a comment.

Addressed feedback.


https://reviews.llvm.org/D45059

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/ComparisonInTempFailureRetryCheck.cpp
  clang-tidy/bugprone/ComparisonInTempFailureRetryCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-comparison-in-temp-failure-retry.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c

Index: test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c
===
--- /dev/null
+++ test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c
@@ -0,0 +1,109 @@
+// RUN: %check_clang_tidy %s bugprone-comparison-in-temp-failure-retry %t
+
+#define TEMP_FAILURE_RETRY(x)  \
+  ({   \
+typeof(x) __z; \
+do \
+  __z = (x);   \
+while (__z == -1); \
+__z;   \
+  })
+
+int foo();
+int bar(int a);
+
+void test() {
+  int i;
+  TEMP_FAILURE_RETRY((i = foo()));
+  TEMP_FAILURE_RETRY(foo());
+  TEMP_FAILURE_RETRY((foo()));
+
+  TEMP_FAILURE_RETRY(foo() == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY [bugprone-comparison-in-temp-failure-retry]
+  TEMP_FAILURE_RETRY((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY((int)(foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  TEMP_FAILURE_RETRY(bar(foo() == 1));
+  TEMP_FAILURE_RETRY((bar(foo() == 1)));
+  TEMP_FAILURE_RETRY((bar(foo() == 1)) == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY(((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:41: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:46: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define INDIRECT TEMP_FAILURE_RETRY
+  INDIRECT(foo());
+  INDIRECT((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  INDIRECT(bar(foo() == 1));
+  INDIRECT((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define TFR(x) TEMP_FAILURE_RETRY(x)
+  TFR(foo());
+  TFR((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TFR(bar(foo() == 1));
+  TFR((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define ADD_TFR(x) (1 + TEMP_FAILURE_RETRY(x) + 1)
+  ADD_TFR(foo());
+  ADD_TFR(foo() == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  ADD_TFR(bar(foo() == 1));
+  ADD_TFR((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define ADDP_TFR(x) (1 + TEMP_FAILURE_RETRY((x)) + 1)
+  ADDP_TFR(foo());
+  ADDP_TFR((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  ADDP_TFR(bar(foo() == 1));
+  ADDP_TFR((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define MACRO TEMP_FAILURE_RETRY(foo() == 1)
+  MACRO;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  // Be sure that being a macro arg doesn't mess with this.
+#define ID(x) (x)
+  ID(ADDP_TFR(bar(foo() == 1)));
+  ID(ADDP_TFR(bar(foo() == 1) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  ID(MACRO);
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define CMP(x) x == 1
+  TEMP_FAILURE_RETRY(CMP(foo()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: Top-level 

[PATCH] D45061: [NVPTX, CUDA] Use custom feature detection to handle NVPTX target builtins.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
tra added a reviewer: jlebar.
Herald added subscribers: hiraditya, sanjoy, jholewinski.

When NVPTX TARGET_BUILTIN specifies sm_XX or ptxYY as required feature,
consider those features available if we're compiling for GPU >= sm_XX or have
enabled PTX version >= ptxYY.

This is needed to control availability of target builtins in NVPTX that are
available for large enough set of combinations that would make it very
cumbersome to enumerate individually.


https://reviews.llvm.org/D45061

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/include/clang/Basic/Cuda.h
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/test/CodeGen/builtins-nvptx-ptx50.cu
  clang/test/CodeGen/builtins-nvptx.c
  llvm/lib/Target/NVPTX/NVPTX.td
  llvm/lib/Target/NVPTX/NVPTXSubtarget.h

Index: llvm/lib/Target/NVPTX/NVPTXSubtarget.h
===
--- llvm/lib/Target/NVPTX/NVPTXSubtarget.h
+++ llvm/lib/Target/NVPTX/NVPTXSubtarget.h
@@ -48,10 +48,6 @@
   // FrameLowering class because TargetFrameLowering is abstract.
   NVPTXFrameLowering FrameLowering;
 
-protected:
-  // Processor supports scoped atomic operations.
-  bool HasAtomScope;
-
 public:
   /// This constructor initializes the data members to match that
   /// of the specified module.
@@ -74,7 +70,7 @@
   }
 
   bool hasAtomAddF64() const { return SmVersion >= 60; }
-  bool hasAtomScope() const { return HasAtomScope; }
+  bool hasAtomScope() const { return SmVersion >= 60; }
   bool hasAtomBitwise64() const { return SmVersion >= 32; }
   bool hasAtomMinMax64() const { return SmVersion >= 32; }
   bool hasLDG() const { return SmVersion >= 32; }
Index: llvm/lib/Target/NVPTX/NVPTX.td
===
--- llvm/lib/Target/NVPTX/NVPTX.td
+++ llvm/lib/Target/NVPTX/NVPTX.td
@@ -53,9 +53,6 @@
 def SM70 : SubtargetFeature<"sm_70", "SmVersion", "70",
  "Target SM 7.0">;
 
-def SATOM : SubtargetFeature<"satom", "HasAtomScope", "true",
- "Atomic operations with scope">;
-
 // PTX Versions
 def PTX32 : SubtargetFeature<"ptx32", "PTXVersion", "32",
  "Use PTX version 3.2">;
@@ -88,10 +85,10 @@
 def : Proc<"sm_50", [SM50, PTX40]>;
 def : Proc<"sm_52", [SM52, PTX41]>;
 def : Proc<"sm_53", [SM53, PTX42]>;
-def : Proc<"sm_60", [SM60, PTX50, SATOM]>;
-def : Proc<"sm_61", [SM61, PTX50, SATOM]>;
-def : Proc<"sm_62", [SM62, PTX50, SATOM]>;
-def : Proc<"sm_70", [SM70, PTX60, SATOM]>;
+def : Proc<"sm_60", [SM60, PTX50]>;
+def : Proc<"sm_61", [SM61, PTX50]>;
+def : Proc<"sm_62", [SM62, PTX50]>;
+def : Proc<"sm_70", [SM70, PTX60]>;
 
 def NVPTXInstrInfo : InstrInfo {
 }
Index: clang/test/CodeGen/builtins-nvptx.c
===
--- clang/test/CodeGen/builtins-nvptx.c
+++ clang/test/CodeGen/builtins-nvptx.c
@@ -292,245 +292,245 @@
 #if ERROR_CHECK || __CUDA_ARCH__ >= 600
 
   // CHECK: call i32 @llvm.nvvm.atomic.add.gen.i.cta.i32.p0i32
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_i' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_i' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_i(ip, i);
   // LP32: call i32 @llvm.nvvm.atomic.add.gen.i.cta.i32.p0i32
   // LP64: call i64 @llvm.nvvm.atomic.add.gen.i.cta.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_l' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_l' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_l(, l);
   // CHECK: call i64 @llvm.nvvm.atomic.add.gen.i.cta.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_ll' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_ll' needs target feature sm_60}}
   __nvvm_atom_cta_add_gen_ll(, ll);
   // CHECK: call i32 @llvm.nvvm.atomic.add.gen.i.sys.i32.p0i32
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_i' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_i' needs target feature sm_60}}
   __nvvm_atom_sys_add_gen_i(ip, i);
   // LP32: call i32 @llvm.nvvm.atomic.add.gen.i.sys.i32.p0i32
   // LP64: call i64 @llvm.nvvm.atomic.add.gen.i.sys.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_l' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_l' needs target feature sm_60}}
   __nvvm_atom_sys_add_gen_l(, l);
   // CHECK: call i64 @llvm.nvvm.atomic.add.gen.i.sys.i64.p0i64
-  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_ll' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_sys_add_gen_ll' needs target feature sm_60}}
   __nvvm_atom_sys_add_gen_ll(, ll);
 
   // CHECK: call float @llvm.nvvm.atomic.add.gen.f.cta.f32.p0f32
-  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_f' needs target feature satom}}
+  // expected-error@+1 {{'__nvvm_atom_cta_add_gen_f' needs target feature sm_60}}
   

[PATCH] D45060: Allow target to handle required features for TARGET_BUILTINs.

2018-03-29 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
tra added a reviewer: echristo.
Herald added subscribers: jlebar, sanjoy.

In some cases figuring out whether particular target builtin
should be enabled is a bit more complicated than current
implementation allow. This patch allows the target to override
what it considers for required feature to be enabled/disabled.

This will be used in the upcoming patch which needs to have some
NVPTX builtins enabled for a range of GPUs depending on detected
CUDA version.


https://reviews.llvm.org/D45060

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/CodeGen/CodeGenFunction.cpp


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2262,6 +2262,12 @@
 Feature.split(OrFeatures, "|");
 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
[&](StringRef Feature) {
+ // Check if the target wants to handle the 
feature.
+ if (auto OR = CGM.getTarget().hasRequiredFeature(
+ CallerFeatureMap, Feature))
+   return OR.getValue();
+ // Otherwise just look for the feature
+ // presence/absence in the CallerFeatureMap.
  if (!CallerFeatureMap.lookup(Feature)) {
FirstMissing = Feature.str();
return false;
Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -928,8 +928,18 @@
 return false;
   }
 
-  /// \brief Identify whether this taret supports multiversioning of functions,
-  /// which requires support for cpu_supports and cpu_is functionality.
+  /// \brief Determine if ReqFeature is enabled given the features populated in
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features.
+  virtual Optional
+  hasRequiredFeature(const llvm::StringMap FeatureMap,
+ const StringRef ReqFeature) const {
+return {};
+  }
+
+  /// \brief Identify whether this taret supports multiversioning of
+  /// functions, which requires support for cpu_supports and cpu_is
+  /// functionality.
   virtual bool supportsMultiVersioning() const { return false; }
 
   // \brief Validate the contents of the __builtin_cpu_supports(const char*)


Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2262,6 +2262,12 @@
 Feature.split(OrFeatures, "|");
 return std::any_of(OrFeatures.begin(), OrFeatures.end(),
[&](StringRef Feature) {
+ // Check if the target wants to handle the feature.
+ if (auto OR = CGM.getTarget().hasRequiredFeature(
+ CallerFeatureMap, Feature))
+   return OR.getValue();
+ // Otherwise just look for the feature
+ // presence/absence in the CallerFeatureMap.
  if (!CallerFeatureMap.lookup(Feature)) {
FirstMissing = Feature.str();
return false;
Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -928,8 +928,18 @@
 return false;
   }
 
-  /// \brief Identify whether this taret supports multiversioning of functions,
-  /// which requires support for cpu_supports and cpu_is functionality.
+  /// \brief Determine if ReqFeature is enabled given the features populated in
+  /// FeatureMap. Targets may override this to provide custom handling of
+  /// required features.
+  virtual Optional
+  hasRequiredFeature(const llvm::StringMap FeatureMap,
+ const StringRef ReqFeature) const {
+return {};
+  }
+
+  /// \brief Identify whether this taret supports multiversioning of
+  /// functions, which requires support for cpu_supports and cpu_is
+  /// functionality.
   virtual bool supportsMultiVersioning() const { return false; }
 
   // \brief Validate the contents of the __builtin_cpu_supports(const char*)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D45059: [clang-tidy] Add check to catch comparisons in TEMP_FAILURE_RETRY

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

Will be good idea to clarify where TEMP_FAILURE_RETRY come from.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45059



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


[PATCH] D45059: Add a clang-tidy check to catch comparisons in TEMP_FAILURE_RETRY

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/bugprone/ComparisonInTempFailureRetryCheck.cpp:51
+}
+}
+

Please add // namespace and remove one empty line below.



Comment at: docs/ReleaseNotes.rst:60
 
+- New `bugprone-comparison-in-temp-failure-retry
+  
`_
 check

Please use alphabetical order in new checks list. Also rebase from trunk and 
use //:doc:// and adjust link.



Comment at: 
docs/clang-tidy/checks/bugprone-comparison-in-temp-failure-retry.rst:6
+
+Checks whether a use of ``TEMP_FAILURE_RETRY`` has a top-level comparison in 
its
+argument. Having such a use is incorrect in the vast majority of cases, and

Please make first statement same as in Release Notes.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45059



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


[PATCH] D45059: Add a clang-tidy check to catch comparisons in TEMP_FAILURE_RETRY

2018-03-29 Thread George Burgess IV via Phabricator via cfe-commits
george.burgess.iv created this revision.
george.burgess.iv added reviewers: aaron.ballman, alexfh.
Herald added a subscriber: mgorny.

`TEMP_FAILURE_RETRY(x)` is a macro that executes `x` until `(x) != -1 || errno 
!= EINTR`, and evaluates to the result of the last execution of `x`.

I've been told that a somewhat common mistake people make with this is to 
include a condition in `TEMP_FAILURE_RETRY`'s argument, e.g.

  // Wrote
  TEMP_FAILURE_RETRY(foo() == 1)
  // Meant
  TEMP_FAILURE_RETRY(foo()) == 1

...In the former case, the `TEMP_FAILURE_RETRY` is useless, since `(x == 1) != 
-1` is always true. It will appear to work, though, since `TEMP_FAILURE_RETRY` 
will execute `foo()` at least once, and it'll evaluate to the value of the 
condition.

We do have a warning in clang to catch things like `(x == y) == -1` 
(-Wtautological-constant-out-of-range-compare), and it does complain about this 
in C++. However, we don't see these warnings in C, since `TEMP_FAILURE_RETRY` 
stores the result of executing `x` into a temporary of type `typeof(x)`, and 
comparisons are `int`s in C.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45059

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/ComparisonInTempFailureRetryCheck.cpp
  clang-tidy/bugprone/ComparisonInTempFailureRetryCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-comparison-in-temp-failure-retry.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c

Index: test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c
===
--- /dev/null
+++ test/clang-tidy/bugprone-comparison-in-temp-failure-retry.c
@@ -0,0 +1,109 @@
+// RUN: %check_clang_tidy %s bugprone-comparison-in-temp-failure-retry %t
+
+#define TEMP_FAILURE_RETRY(x)  \
+  ({   \
+typeof(x) __z; \
+do \
+  __z = (x);   \
+while (__z == -1); \
+__z;   \
+  })
+
+int foo();
+int bar(int a);
+
+void test() {
+  int i;
+  TEMP_FAILURE_RETRY((i = foo()));
+  TEMP_FAILURE_RETRY(foo());
+  TEMP_FAILURE_RETRY((foo()));
+
+  TEMP_FAILURE_RETRY(foo() == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY [bugprone-comparison-in-temp-failure-retry]
+  TEMP_FAILURE_RETRY((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY((int)(foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:34: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  TEMP_FAILURE_RETRY(bar(foo() == 1));
+  TEMP_FAILURE_RETRY((bar(foo() == 1)));
+  TEMP_FAILURE_RETRY((bar(foo() == 1)) == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY(((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:41: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TEMP_FAILURE_RETRY((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:46: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define INDIRECT TEMP_FAILURE_RETRY
+  INDIRECT(foo());
+  INDIRECT((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  INDIRECT(bar(foo() == 1));
+  INDIRECT((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:36: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define TFR(x) TEMP_FAILURE_RETRY(x)
+  TFR(foo());
+  TFR((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+  TFR(bar(foo() == 1));
+  TFR((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define ADD_TFR(x) (1 + TEMP_FAILURE_RETRY(x) + 1)
+  ADD_TFR(foo());
+  ADD_TFR(foo() == 1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+  ADD_TFR(bar(foo() == 1));
+  ADD_TFR((int)((bar(foo() == 1)) == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: Top-level comparisons should be moved out of TEMP_FAILURE_RETRY
+
+#define ADDP_TFR(x) (1 + TEMP_FAILURE_RETRY((x)) + 1)
+  ADDP_TFR(foo());
+  ADDP_TFR((foo() == 1));
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: Top-level comparisons 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:209
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;

sammccall wrote:
> similarly this one.
> (ideally we wouldn't do the work above, it's just there to make dumpLast work 
> I think)
This is very cheap and dumpLast has checked the emptiness so there is no need 
to duplicate the work here.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44985: Remove initializer for CUDA shared varirable

2018-03-29 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 140310.
yaxunl added a comment.

Revised by John's comments. Also simplified the test by Artem's comments.


https://reviews.llvm.org/D44985

Files:
  lib/CodeGen/CGDecl.cpp
  test/CodeGenCUDA/address-spaces.cu
  test/CodeGenCUDA/device-var-init.cu

Index: test/CodeGenCUDA/device-var-init.cu
===
--- test/CodeGenCUDA/device-var-init.cu
+++ test/CodeGenCUDA/device-var-init.cu
@@ -1,10 +1,14 @@
 // REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
 
 // Make sure we don't allow dynamic initialization for device
 // variables, but accept empty constructors allowed by CUDA.
 
 // RUN: %clang_cc1 -triple nvptx64-nvidia-cuda -fcuda-is-device -std=c++11 \
-// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck %s
+// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck -check-prefixes=CHECK,NVPTX %s
+
+// RUN: %clang_cc1 -triple amdgcn -fcuda-is-device -std=c++11 \
+// RUN: -fno-threadsafe-statics -emit-llvm -o - %s | FileCheck -check-prefixes=CHECK,AMDGCN %s
 
 #ifdef __clang__
 #include "Inputs/cuda.h"
@@ -105,68 +109,120 @@
 __constant__ EC_I_EC c_ec_i_ec;
 // CHECK: @c_ec_i_ec = addrspace(4) externally_initialized global %struct.EC_I_EC zeroinitializer,
 
+// CHECK: @_ZZ2dfvE4s_ec = internal addrspace(3) global %struct.EC undef
+// CHECK: @_ZZ2dfvE5s_etc = internal addrspace(3) global %struct.ETC undef
+
 // We should not emit global initializers for device-side variables.
 // CHECK-NOT: @__cxx_global_var_init
 
 // Make sure that initialization restrictions do not apply to local
 // variables.
 __device__ void df() {
+  // NVPTX:  %[[ec:.*]] = alloca %struct.EC
+  // NVPTX:  %[[ed:.*]] = alloca %struct.ED
+  // NVPTX:  %[[ecd:.*]] = alloca %struct.ECD
+  // NVPTX:  %[[etc:.*]] = alloca %struct.ETC
+  // NVPTX:  %[[uc:.*]] = alloca %struct.UC
+  // NVPTX:  %[[ud:.*]] = alloca %struct.UD
+  // NVPTX:  %[[eci:.*]] = alloca %struct.ECI
+  // NVPTX:  %[[nec:.*]] = alloca %struct.NEC
+  // NVPTX:  %[[ned:.*]] = alloca %struct.NED
+  // NVPTX:  %[[ncv:.*]] = alloca %struct.NCV
+  // NVPTX:  %[[vd:.*]] = alloca %struct.VD
+  // NVPTX:  %[[ncf:.*]] = alloca %struct.NCF
+  // NVPTX:  %[[ncfs:.*]] = alloca %struct.NCFS
+  // NVPTX:  %[[utc:.*]] = alloca %struct.UTC
+  // NVPTX:  %[[netc:.*]] = alloca %struct.NETC
+  // NVPTX:  %[[ec_i_ec:.*]] = alloca %struct.EC_I_EC
+  // NVPTX:  %[[ec_i_ec1:.*]] = alloca %struct.EC_I_EC1
+  // NVPTX:  %[[t_v_t:.*]] = alloca %struct.T_V_T
+  // NVPTX:  %[[t_b_nec:.*]] = alloca %struct.T_B_NEC
+  // NVPTX:  %[[t_f_nec:.*]] = alloca %struct.T_F_NEC
+  // NVPTX:  %[[t_fa_nec:.*]] = alloca %struct.T_FA_NEC
+  // NVPTX:  %[[t_b_ned:.*]] = alloca %struct.T_B_NED
+  // NVPTX:  %[[t_f_ned:.*]] = alloca %struct.T_F_NED
+  // NVPTX:  %[[t_fa_ned:.*]] = alloca %struct.T_FA_NED
+  // AMDGCN:  %[[ec:.*]] = addrspacecast %struct.EC addrspace(5)* %ec to %struct.EC*
+  // AMDGCN:  %[[ed:.*]] = addrspacecast %struct.ED addrspace(5)* %ed to %struct.ED*
+  // AMDGCN:  %[[ecd:.*]] = addrspacecast %struct.ECD addrspace(5)* %ecd to %struct.ECD*
+  // AMDGCN:  %[[etc:.*]] = addrspacecast %struct.ETC addrspace(5)* %etc to %struct.ETC*
+  // AMDGCN:  %[[uc:.*]] = addrspacecast %struct.UC addrspace(5)* %uc to %struct.UC*
+  // AMDGCN:  %[[ud:.*]] = addrspacecast %struct.UD addrspace(5)* %ud to %struct.UD*
+  // AMDGCN:  %[[eci:.*]] = addrspacecast %struct.ECI addrspace(5)* %eci to %struct.ECI*
+  // AMDGCN:  %[[nec:.*]] = addrspacecast %struct.NEC addrspace(5)* %nec to %struct.NEC*
+  // AMDGCN:  %[[ned:.*]] = addrspacecast %struct.NED addrspace(5)* %ned to %struct.NED*
+  // AMDGCN:  %[[ncv:.*]] = addrspacecast %struct.NCV addrspace(5)* %ncv to %struct.NCV*
+  // AMDGCN:  %[[vd:.*]] = addrspacecast %struct.VD addrspace(5)* %vd to %struct.VD*
+  // AMDGCN:  %[[ncf:.*]] = addrspacecast %struct.NCF addrspace(5)* %ncf to %struct.NCF*
+  // AMDGCN:  %[[ncfs:.*]] = addrspacecast %struct.NCFS addrspace(5)* %ncfs to %struct.NCFS*
+  // AMDGCN:  %[[utc:.*]] = addrspacecast %struct.UTC addrspace(5)* %utc to %struct.UTC*
+  // AMDGCN:  %[[netc:.*]] = addrspacecast %struct.NETC addrspace(5)* %netc to %struct.NETC*
+  // AMDGCN:  %[[ec_i_ec:.*]] = addrspacecast %struct.EC_I_EC addrspace(5)* %ec_i_ec to %struct.EC_I_EC*
+  // AMDGCN:  %[[ec_i_ec1:.*]] = addrspacecast %struct.EC_I_EC1 addrspace(5)* %ec_i_ec1 to %struct.EC_I_EC1*
+  // AMDGCN:  %[[t_v_t:.*]] = addrspacecast %struct.T_V_T addrspace(5)* %t_v_t to %struct.T_V_T*
+  // AMDGCN:  %[[t_b_nec:.*]] = addrspacecast %struct.T_B_NEC addrspace(5)* %t_b_nec to %struct.T_B_NEC*
+  // AMDGCN:  %[[t_f_nec:.*]] = addrspacecast %struct.T_F_NEC addrspace(5)* %t_f_nec to %struct.T_F_NEC*
+  // AMDGCN:  %[[t_fa_nec:.*]] = addrspacecast %struct.T_FA_NEC addrspace(5)* %t_fa_nec to %struct.T_FA_NEC*
+  // AMDGCN:  %[[t_b_ned:.*]] = addrspacecast %struct.T_B_NED addrspace(5)* %t_b_ned to %struct.T_B_NED*
+  // AMDGCN:  %[[t_f_ned:.*]] 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 140311.
MaskRay added a comment.

Don't rename anything. I just want to have this revision reviewed as soon as 
possible


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720

Files:
  clangd/FuzzyMatch.cpp
  clangd/FuzzyMatch.h

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -58,7 +58,7 @@
   void buildGraph();
   void calculateRoles(const char *Text, CharRole *Out, int , int N);
   bool allowMatch(int P, int W) const;
-  int skipPenalty(int W, Action Last) const;
+  int missPenalty(int W, Action Last) const;
   int matchBonus(int P, int W, Action Last) const;
 
   // Pattern data is initialized by the constructor, then constant.
Index: clangd/FuzzyMatch.cpp
===
--- clangd/FuzzyMatch.cpp
+++ clangd/FuzzyMatch.cpp
@@ -58,6 +58,7 @@
 
 #include "FuzzyMatch.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 
 namespace clang {
@@ -67,7 +68,6 @@
 constexpr int FuzzyMatcher::MaxPat;
 constexpr int FuzzyMatcher::MaxWord;
 
-static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; }
 // A "negative infinity" score that won't overflow.
 // We use this to mark unreachable states and forbidden solutions.
 // Score field is 15 bits wide, min value is -2^14, we use half of that.
@@ -80,25 +80,19 @@
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I)
-LowPat[I] = lower(Pat[I]);
-  Scores[0][0][Miss] = {0, Miss};
-  Scores[0][0][Match] = {AwfulScore, Miss};
-  for (int P = 0; P <= PatN; ++P)
-for (int W = 0; W < P; ++W)
-  for (Action A : {Miss, Match})
-Scores[P][W][A] = {AwfulScore, Miss};
-  if (PatN > 0)
-calculateRoles(Pat, PatRole, PatTypeSet, PatN);
+LowPat[I] = toLower(Pat[I]);
+  calculateRoles(Pat, PatRole, PatTypeSet, PatN);
 }
 
 Optional FuzzyMatcher::match(StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
 return None;
-  if (!PatN)
-return 1;
   buildGraph();
-  auto Best = std::max(Scores[PatN][WordN][Miss].Score,
-   Scores[PatN][WordN][Match].Score);
+  // The pattern doesn't have to match the whole word (but the whole pattern
+  // must match). Find the optimal prefix of Word to match Pattern.
+  int Best = AwfulScore;
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
@@ -179,7 +173,8 @@
 }
 void FuzzyMatcher::calculateRoles(const char *Text, CharRole *Out, int ,
   int N) {
-  assert(N > 0);
+  if (!N)
+return;
   CharType Type = packedLookup(CharTypes, Text[0]);
   TypeSet = 1 << Type;
   // Types holds a sliding window of (Prev, Curr, Next) types.
@@ -206,10 +201,8 @@
   if (PatN > WordN)
 return false;
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;
   for (int I = 0; I < WordN; ++I)
-LowWord[I] = lower(Word[I]);
+LowWord[I] = toLower(Word[I]);
 
   // Cheap subsequence check.
   for (int W = 0, P = 0; P != PatN; ++W) {
@@ -236,21 +229,19 @@
 // This range is not strict: we can apply larger bonuses/penalties, or penalize
 // non-matched characters.
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {
-Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - skipPenalty(W, Miss),
+Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - missPenalty(W, Miss),
   Miss};
 Scores[0][W + 1][Match] = {AwfulScore, Miss};
   }
   for (int P = 0; P < PatN; ++P) {
+Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
 for (int W = P; W < WordN; ++W) {
   auto  = Scores[P + 1][W + 1],  = Scores[P + 1][W];
 
-  auto MatchMissScore = PreMiss[Match].Score;
-  auto MissMissScore = PreMiss[Miss].Score;
-  if (P < PatN - 1) { // Skipping trailing characters is always free.
-MatchMissScore -= skipPenalty(W, Match);
-MissMissScore -= skipPenalty(W, Miss);
-  }
+  auto MatchMissScore = PreMiss[Match].Score - missPenalty(W, Match);
+  auto MissMissScore = PreMiss[Miss].Score - missPenalty(W, Miss);
   Score[Miss] = (MatchMissScore > MissMissScore)
 ? ScoreInfo{MatchMissScore, Match}
 : ScoreInfo{MissMissScore, Miss};
@@ -284,10 +275,10 @@
  (Word[W] != LowWord[W] && WordTypeSet & 1 << Lower);
 }
 
-int FuzzyMatcher::skipPenalty(int W, Action Last) const {
+int FuzzyMatcher::missPenalty(int W, Action Last) const {
   int S = 0;
   if (WordRole[W] == Head) // 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In `buildGraph`, the nested loop

  for (int P = 0; P < PatN; ++P) {
  // Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
  for (int W = P; W < WordN; ++W) {

is interpreted as: we are calculating the cell `Scores[P+1][W+1][*]`, using the 
characters `Pattern[P]` and `Word[W]`. This is a position central viewpoint.
If you see `P and W` as numbers of characters, instead of the string indices, 
will it make more sense due to alleviated +1 -1 mental burden?

It can also be rephrased as:

  for (int P = 1; P <= PatN; ++P) {
  for (int W = P + 1; W <= WordN; ++W) { // Since you like this form 
(though I don't)

This is a cell central viewpoint.
(we are calculating the cell `Scores[P][W][*]`, using the characters 
`Pattern[P-1]` and `Word[W-1]`)

The former interpretation is preferred because half closed intervals are 
generally preferred.

In the table dumping stage,

  for (int I = W; i > 0; i--)

is better than

  for (int I = W - 1; I >= 0; --I)

because we are tracing through the optimal path of the dynamic programming 
*cells*. We are also tracing the `W P` positions, but the former interpretation 
gets rid of some +1 -1.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:93
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))

sammccall wrote:
> MaskRay wrote:
> > sammccall wrote:
> > > MaskRay wrote:
> > > > sammccall wrote:
> > > > > this looks like a behavior change - why?
> > > > This is a behavior change. Instead of choosing between `Match/Miss` in 
> > > > the last position, we enumerate the last matching position in `Word`.
> > > > 
> > > > This saves `if (P < PatN - 1) {` check in the main loop at the cost of 
> > > > a for loop here (use sites of ending values)
> > > Ah, I see - the case where we match only part of the word is handled up 
> > > here now.
> > > (I think you mean this is not a behavior change? The result is the same 
> > > AFAICS)
> > > 
> > > That does make more sense, but it's pretty subtle.
> > > Can you add a comment like
> > >  `// The pattern doesn't have to match the whole word (but the whole 
> > > pattern must match).`
> > Added
> > ```
> >   // Find the optimal prefix of Word to match Pattern.
> > ```
> > 
> > I meant this is a behavior change but it makes the first row and the rest 
> > rows of the score table more consistent.
> That comment really doesn't capture what's significant about this line - it's 
> the *policy*, rather than the mechanism, that needs highlighting here.
> 
> (Re: behavior change - I *think* there's no inputs for which we produce a 
> different match result/score because of this patch, right?)
Added your comment.

The behavior change is regarding the values of `Scores` (there is no longer 
different interpretation for the last character of Pattern) how the final value 
is chosen (Scores[P][W][*] -> Scores[P][*][Match]) . There is no noticeable 
change in the user viewpoint.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44984: [HIP] Add hip file type and codegen for kernel launching

2018-03-29 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added a comment.

> 
> 
>> Since the header file and library seem not to affect this patch, is it OK to 
>> defer their changes to be part of the toolchain patch?
> 
> I'm not sure I understand. Could you elaborate?

clang -cc1 does not include `__clang_cuda_runtime_wrapper.h` by default when 
clang -cc1 is called directly to compile CUDA programs. CUDA toolchain adds 
-include `__clang_cuda_runtime_wrapper.h` when compiling CUDA program as kernel 
code. Therefore if clang -cc1 is used to compile HIP program in lit test, there 
is no need to use `-fnocudainc`.

This patch mainly changes kernel launching API function names. The implement 
and testing of this change does not depend on the CUDA/HIP header files. A 
minimum header like test/CodeGenCUDA/Input/cuda.h is sufficient for testing 
this patch.

Basically this patch is only concerns about -cc1 and therefore is independent 
of the toolchain changes about header and library files.


https://reviews.llvm.org/D44984



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 140306.
MaskRay added a comment.

nit picking


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720

Files:
  clangd/FuzzyMatch.cpp
  clangd/FuzzyMatch.h

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -58,8 +58,8 @@
   void buildGraph();
   void calculateRoles(const char *Text, CharRole *Out, int , int N);
   bool allowMatch(int P, int W) const;
-  int skipPenalty(int W, Action Last) const;
-  int matchBonus(int P, int W, Action Last) const;
+  int missPenalty(int W, Action Last) const;
+  int matchScore(int P, int W, Action Last) const;
 
   // Pattern data is initialized by the constructor, then constant.
   char Pat[MaxPat]; // Pattern data
Index: clangd/FuzzyMatch.cpp
===
--- clangd/FuzzyMatch.cpp
+++ clangd/FuzzyMatch.cpp
@@ -58,6 +58,7 @@
 
 #include "FuzzyMatch.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 
 namespace clang {
@@ -67,7 +68,6 @@
 constexpr int FuzzyMatcher::MaxPat;
 constexpr int FuzzyMatcher::MaxWord;
 
-static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; }
 // A "negative infinity" score that won't overflow.
 // We use this to mark unreachable states and forbidden solutions.
 // Score field is 15 bits wide, min value is -2^14, we use half of that.
@@ -80,25 +80,19 @@
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I)
-LowPat[I] = lower(Pat[I]);
-  Scores[0][0][Miss] = {0, Miss};
-  Scores[0][0][Match] = {AwfulScore, Miss};
-  for (int P = 0; P <= PatN; ++P)
-for (int W = 0; W < P; ++W)
-  for (Action A : {Miss, Match})
-Scores[P][W][A] = {AwfulScore, Miss};
-  if (PatN > 0)
-calculateRoles(Pat, PatRole, PatTypeSet, PatN);
+LowPat[I] = toLower(Pat[I]);
+  calculateRoles(Pat, PatRole, PatTypeSet, PatN);
 }
 
 Optional FuzzyMatcher::match(StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
 return None;
-  if (!PatN)
-return 1;
   buildGraph();
-  auto Best = std::max(Scores[PatN][WordN][Miss].Score,
-   Scores[PatN][WordN][Match].Score);
+  // The pattern doesn't have to match the whole word (but the whole pattern
+  // must match). Find the optimal prefix of Word to match Pattern.
+  int Best = AwfulScore;
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
@@ -179,7 +173,8 @@
 }
 void FuzzyMatcher::calculateRoles(const char *Text, CharRole *Out, int ,
   int N) {
-  assert(N > 0);
+  if (!N)
+return;
   CharType Type = packedLookup(CharTypes, Text[0]);
   TypeSet = 1 << Type;
   // Types holds a sliding window of (Prev, Curr, Next) types.
@@ -206,10 +201,8 @@
   if (PatN > WordN)
 return false;
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;
   for (int I = 0; I < WordN; ++I)
-LowWord[I] = lower(Word[I]);
+LowWord[I] = toLower(Word[I]);
 
   // Cheap subsequence check.
   for (int W = 0, P = 0; P != PatN; ++W) {
@@ -236,31 +229,29 @@
 // This range is not strict: we can apply larger bonuses/penalties, or penalize
 // non-matched characters.
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {
-Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - skipPenalty(W, Miss),
+Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - missPenalty(W, Miss),
   Miss};
 Scores[0][W + 1][Match] = {AwfulScore, Miss};
   }
   for (int P = 0; P < PatN; ++P) {
+Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
 for (int W = P; W < WordN; ++W) {
   auto  = Scores[P + 1][W + 1],  = Scores[P + 1][W];
 
-  auto MatchMissScore = PreMiss[Match].Score;
-  auto MissMissScore = PreMiss[Miss].Score;
-  if (P < PatN - 1) { // Skipping trailing characters is always free.
-MatchMissScore -= skipPenalty(W, Match);
-MissMissScore -= skipPenalty(W, Miss);
-  }
+  auto MatchMissScore = PreMiss[Match].Score - missPenalty(W, Match);
+  auto MissMissScore = PreMiss[Miss].Score - missPenalty(W, Miss);
   Score[Miss] = (MatchMissScore > MissMissScore)
 ? ScoreInfo{MatchMissScore, Match}
 : ScoreInfo{MissMissScore, Miss};
 
   if (!allowMatch(P, W)) {
 Score[Match] = {AwfulScore, Miss};
   } else {
 auto  = Scores[P][W];
-auto MatchMatchScore = PreMatch[Match].Score + matchBonus(P, W, Match);
-auto 

[PATCH] D44093: [BUILTINS] structure pretty printer

2018-03-29 Thread Paul Semel via Phabricator via cfe-commits
paulsemel updated this revision to Diff 140304.
paulsemel marked 3 inline comments as done.
paulsemel added a comment.

Added Aaron suggestions.
Fixed a bug when having nested anonymous unions and structures.


Repository:
  rC Clang

https://reviews.llvm.org/D44093

Files:
  include/clang/Basic/Builtins.def
  lib/CodeGen/CGBuiltin.cpp
  lib/Sema/SemaChecking.cpp
  test/CodeGen/dump-struct-builtin.c
  test/Sema/builtin-dump-struct.c

Index: test/Sema/builtin-dump-struct.c
===
--- /dev/null
+++ test/Sema/builtin-dump-struct.c
@@ -0,0 +1,40 @@
+// RUN: %clang_cc1 -triple i386-unknown-unknown -fsyntax-only -fno-spell-checking -verify %s
+
+void invalid_uses() {
+  struct A {
+  };
+  struct A a;
+  void *b;
+  int (*goodfunc)(const char *, ...);
+  int (*badfunc1)(const char *);
+  int (*badfunc2)(int, ...);
+  void (*badfunc3)(const char *, ...);
+  int (*badfunc4)(char *, ...);
+  int (*badfunc5)(void);
+
+  __builtin_dump_struct(); // expected-error {{too few arguments to function call, expected 2, have 0}}
+  __builtin_dump_struct(1);// expected-error {{too few arguments to function call, expected 2, have 1}}
+  __builtin_dump_struct(1, 2); // expected-error {{passing 'int' to parameter of incompatible type structure pointer: type mismatch at 1st parameter ('int' vs structure pointer)}}
+  __builtin_dump_struct(, 2);// expected-error {{passing 'int' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('int' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(b, ); // expected-error {{passing 'void *' to parameter of incompatible type structure pointer: type mismatch at 1st parameter ('void *' vs structure pointer)}}
+  __builtin_dump_struct(, badfunc1); // expected-error {{passing 'int (*)(const char *)' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('int (*)(const char *)' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(, badfunc2); // expected-error {{passing 'int (*)(int, ...)' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('int (*)(int, ...)' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(, badfunc3); // expected-error {{passing 'void (*)(const char *, ...)' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('void (*)(const char *, ...)' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(, badfunc4); // expected-error {{passing 'int (*)(char *, ...)' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('int (*)(char *, ...)' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(, badfunc5); // expected-error {{passing 'int (*)(void)' to parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 2nd parameter ('int (*)(void)' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(a, goodfunc);  // expected-error {{passing 'struct A' to parameter of incompatible type structure pointer: type mismatch at 1st parameter ('struct A' vs structure pointer)}}
+}
+
+void valid_uses() {
+  struct A {
+  };
+  union B {
+  };
+
+  int (*goodfunc)(const char *, ...);
+  struct A a;
+  union B b;
+
+  __builtin_dump_struct(, goodfunc);
+  __builtin_dump_struct(, goodfunc);
+}
Index: test/CodeGen/dump-struct-builtin.c
===
--- /dev/null
+++ test/CodeGen/dump-struct-builtin.c
@@ -0,0 +1,387 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
+
+#include "Inputs/stdio.h"
+
+void unit1() {
+  struct U1A {
+short a;
+  };
+
+  struct U1A a = {
+  .a = 12,
+  };
+
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[RES1:%[0-9]+]] = getelementptr inbounds %struct.U1A, %struct.U1A* %a, i32 0, i32 0
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[LOAD1:%[0-9]+]] = load i16, i16* [[RES1]],
+  // CHECK: call i32 (i8*, ...) @printf({{.*}}, i16 [[LOAD1]])
+  // CHECK: call i32 (i8*, ...) @printf(
+  __builtin_dump_struct(, );
+}
+
+void unit2() {
+  struct U2A {
+unsigned short a;
+  };
+
+  struct U2A a = {
+  .a = 12,
+  };
+
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[RES1:%[0-9]+]] = getelementptr inbounds %struct.U2A, %struct.U2A* %a, i32 0, i32 0
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[LOAD1:%[0-9]+]] = load i16, i16* [[RES1]],
+  // CHECK: call i32 (i8*, ...) @printf({{.*}}, i16 [[LOAD1]])
+  // CHECK: call i32 (i8*, ...) @printf(
+  __builtin_dump_struct(, );
+}
+
+void unit3() {
+  struct U3A {
+int a;
+  };
+
+  struct U3A a = {
+  .a = 12,
+  };
+
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[RES1:%[0-9]+]] = getelementptr inbounds %struct.U3A, %struct.U3A* %a, i32 0, i32 0
+  // CHECK: call i32 (i8*, ...) @printf(
+  // CHECK: [[LOAD1:%[0-9]+]] = load i32, i32* [[RES1]],
+  

[PATCH] D45058: [X86] Disable SGX for Skylake Server

2018-03-29 Thread Gabor Buella via Phabricator via cfe-commits
GBuella created this revision.
GBuella added reviewers: craig.topper, zvi, echristo.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D45058

Files:
  lib/Basic/Targets/X86.cpp


Index: lib/Basic/Targets/X86.cpp
===
--- lib/Basic/Targets/X86.cpp
+++ lib/Basic/Targets/X86.cpp
@@ -182,7 +182,8 @@
 setFeatureEnabledImpl(Features, "xsavec", true);
 setFeatureEnabledImpl(Features, "xsaves", true);
 setFeatureEnabledImpl(Features, "mpx", true);
-setFeatureEnabledImpl(Features, "sgx", true);
+if (Kind != CK_SkylakeServer) // SKX inherits all SKL features, except SGX
+  setFeatureEnabledImpl(Features, "sgx", true);
 setFeatureEnabledImpl(Features, "clflushopt", true);
 setFeatureEnabledImpl(Features, "rtm", true);
 LLVM_FALLTHROUGH;


Index: lib/Basic/Targets/X86.cpp
===
--- lib/Basic/Targets/X86.cpp
+++ lib/Basic/Targets/X86.cpp
@@ -182,7 +182,8 @@
 setFeatureEnabledImpl(Features, "xsavec", true);
 setFeatureEnabledImpl(Features, "xsaves", true);
 setFeatureEnabledImpl(Features, "mpx", true);
-setFeatureEnabledImpl(Features, "sgx", true);
+if (Kind != CK_SkylakeServer) // SKX inherits all SKL features, except SGX
+  setFeatureEnabledImpl(Features, "sgx", true);
 setFeatureEnabledImpl(Features, "clflushopt", true);
 setFeatureEnabledImpl(Features, "rtm", true);
 LLVM_FALLTHROUGH;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44093: [BUILTINS] structure pretty printer

2018-03-29 Thread Paul Semel via Phabricator via cfe-commits
paulsemel marked 6 inline comments as done.
paulsemel added inline comments.



Comment at: test/Sema/builtin-dump-struct.c:8
+  void *b;
+  int (*goodfunc)(const char *, ...);
+  int (*badfunc1)(const char *);

aaron.ballman wrote:
> Can you also add a test for: `int (*badfunc4)(char *, ...);` and `int 
> (*badfunc5)();`
Isn't `int (*func)()` is a valid prototype for a printf like function in C ?
I instead added `int (*func)(void)` to the test cases.



Comment at: test/Sema/builtin-dump-struct.c:15
+  __builtin_dump_struct(1);// expected-error {{too few arguments 
to function call, expected 2, have 1}}
+  __builtin_dump_struct(1, 2); // expected-error {{passing 'int' to 
parameter of incompatible type 'structure pointer type': type mismatch at 1st 
parameter ('int' vs 'structure pointer type')}}
+  __builtin_dump_struct(, 2);// expected-error {{passing 'int' to 
parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 
2nd parameter ('int' vs 'int (*)(const char *, ...)')}}

aaron.ballman wrote:
> Hrm, the `'structure pointer type'` in this diagnostic is unfortunate because 
> it's being quoted as though it were a real type -- you could drop the single 
> quotes. If you think the resulting diagnostic reads too strangely, perhaps we 
> will have to go back to a custom diagnostic after all.
I think it will be better to just put something like `structure pointer`, so 
that we understand the type we are talking about.
But this diagnostic seems great, still, what do you think about sticking with 
it ?



Comment at: test/Sema/builtin-dump-struct.c:17
+  __builtin_dump_struct(, 2);// expected-error {{passing 'int' to 
parameter of incompatible type 'int (*)(const char *, ...)': type mismatch at 
2nd parameter ('int' vs 'int (*)(const char *, ...)')}}
+  __builtin_dump_struct(b, ); // expected-error {{passing 'void *' to 
parameter of incompatible type 'structure pointer type': type mismatch at 1st 
parameter ('void *' vs 'structure pointer type')}}
+  __builtin_dump_struct(, badfunc1); // expected-error {{passing 'int 
(*)(const char *)' to parameter of incompatible type 'int (*)(const char *, 
...)': type mismatch at 2nd parameter ('int (*)(const char *)' vs 'int 
(*)(const char *, ...)')}}

aaron.ballman wrote:
> Why ``?
Yes, we already have a test like this anyway :)


Repository:
  rC Clang

https://reviews.llvm.org/D44093



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


[PATCH] D45056: [X86] Split up -march=icelake to -client & -server

2018-03-29 Thread Gabor Buella via Phabricator via cfe-commits
GBuella created this revision.
GBuella added reviewers: craig.topper, zvi, echristo.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D45056

Files:
  include/clang/Basic/X86Target.def
  lib/Basic/Targets/X86.cpp
  test/Driver/x86-march.c
  test/Frontend/x86-target-cpu.c
  test/Misc/target-invalid-cpu-note.c
  test/Preprocessor/predefined-arch-macros.c

Index: test/Preprocessor/predefined-arch-macros.c
===
--- test/Preprocessor/predefined-arch-macros.c
+++ test/Preprocessor/predefined-arch-macros.c
@@ -1055,7 +1055,7 @@
 // CHECK_CNL_M64: #define __x86_64 1
 // CHECK_CNL_M64: #define __x86_64__ 1
 
-// RUN: %clang -march=icelake -m32 -E -dM %s -o - 2>&1 \
+// RUN: %clang -march=icelake-client -m32 -E -dM %s -o - 2>&1 \
 // RUN: -target i386-unknown-linux \
 // RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_ICL_M32
 // CHECK_ICL_M32: #define __AES__ 1
@@ -1110,8 +1110,64 @@
 // CHECK_ICL_M32: #define __i386__ 1
 // CHECK_ICL_M32: #define __tune_corei7__ 1
 // CHECK_ICL_M32: #define i386 1
-//
-// RUN: %clang -march=icelake -m64 -E -dM %s -o - 2>&1 \
+
+// RUN: %clang -march=icelake-server -m32 -E -dM %s -o - 2>&1 \
+// RUN: -target i386-unknown-linux \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_ICX_M32
+// CHECK_ICX_M32: #define __AES__ 1
+// CHECK_ICX_M32: #define __AVX2__ 1
+// CHECK_ICX_M32: #define __AVX512BITALG__ 1
+// CHECK_ICX_M32: #define __AVX512BW__ 1
+// CHECK_ICX_M32: #define __AVX512CD__ 1
+// CHECK_ICX_M32: #define __AVX512DQ__ 1
+// CHECK_ICX_M32: #define __AVX512F__ 1
+// CHECK_ICX_M32: #define __AVX512IFMA__ 1
+// CHECK_ICX_M32: #define __AVX512VBMI2__ 1
+// CHECK_ICX_M32: #define __AVX512VBMI__ 1
+// CHECK_ICX_M32: #define __AVX512VL__ 1
+// CHECK_ICX_M32: #define __AVX512VNNI__ 1
+// CHECK_ICX_M32: #define __AVX512VPOPCNTDQ__ 1
+// CHECK_ICX_M32: #define __AVX__ 1
+// CHECK_ICX_M32: #define __BMI2__ 1
+// CHECK_ICX_M32: #define __BMI__ 1
+// CHECK_ICX_M32: #define __CLFLUSHOPT__ 1
+// CHECK_ICX_M32: #define __CLWB__ 1
+// CHECK_ICX_M32: #define __F16C__ 1
+// CHECK_ICX_M32: #define __FMA__ 1
+// CHECK_ICX_M32: #define __GFNI__ 1
+// CHECK_ICX_M32: #define __LZCNT__ 1
+// CHECK_ICX_M32: #define __MMX__ 1
+// CHECK_ICX_M32: #define __MPX__ 1
+// CHECK_ICX_M32: #define __PCLMUL__ 1
+// CHECK_ICX_M32: #define __PKU__ 1
+// CHECK_ICX_M32: #define __POPCNT__ 1
+// CHECK_ICX_M32: #define __PRFCHW__ 1
+// CHECK_ICX_M32: #define __RDPID__ 1
+// CHECK_ICX_M32: #define __RDRND__ 1
+// CHECK_ICX_M32: #define __RDSEED__ 1
+// CHECK_ICX_M32: #define __RTM__ 1
+// CHECK_ICX_M32: #define __SGX__ 1
+// CHECK_ICX_M32: #define __SHA__ 1
+// CHECK_ICX_M32: #define __SSE2__ 1
+// CHECK_ICX_M32: #define __SSE3__ 1
+// CHECK_ICX_M32: #define __SSE4_1__ 1
+// CHECK_ICX_M32: #define __SSE4_2__ 1
+// CHECK_ICX_M32: #define __SSE__ 1
+// CHECK_ICX_M32: #define __SSSE3__ 1
+// CHECK_ICX_M32: #define __VAES__ 1
+// CHECK_ICX_M32: #define __VPCLMULQDQ__ 1
+// CHECK_ICX_M32: #define __XSAVEC__ 1
+// CHECK_ICX_M32: #define __XSAVEOPT__ 1
+// CHECK_ICX_M32: #define __XSAVES__ 1
+// CHECK_ICX_M32: #define __XSAVE__ 1
+// CHECK_ICX_M32: #define __corei7 1
+// CHECK_ICX_M32: #define __corei7__ 1
+// CHECK_ICX_M32: #define __i386 1
+// CHECK_ICX_M32: #define __i386__ 1
+// CHECK_ICX_M32: #define __tune_corei7__ 1
+// CHECK_ICX_M32: #define i386 1
+
+// RUN: %clang -march=icelake-client -m64 -E -dM %s -o - 2>&1 \
 // RUN: -target i386-unknown-linux \
 // RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_ICL_M64
 // CHECK_ICL_M64: #define __AES__ 1
@@ -1168,6 +1224,63 @@
 // CHECK_ICL_M64: #define __x86_64 1
 // CHECK_ICL_M64: #define __x86_64__ 1
 
+// RUN: %clang -march=icelake-server -m64 -E -dM %s -o - 2>&1 \
+// RUN: -target i386-unknown-linux \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_ICX_M64
+// CHECK_ICX_M64: #define __AES__ 1
+// CHECK_ICX_M64: #define __AVX2__ 1
+// CHECK_ICX_M64: #define __AVX512BITALG__ 1
+// CHECK_ICX_M64: #define __AVX512BW__ 1
+// CHECK_ICX_M64: #define __AVX512CD__ 1
+// CHECK_ICX_M64: #define __AVX512DQ__ 1
+// CHECK_ICX_M64: #define __AVX512F__ 1
+// CHECK_ICX_M64: #define __AVX512IFMA__ 1
+// CHECK_ICX_M64: #define __AVX512VBMI2__ 1
+// CHECK_ICX_M64: #define __AVX512VBMI__ 1
+// CHECK_ICX_M64: #define __AVX512VL__ 1
+// CHECK_ICX_M64: #define __AVX512VNNI__ 1
+// CHECK_ICX_M64: #define __AVX512VPOPCNTDQ__ 1
+// CHECK_ICX_M64: #define __AVX__ 1
+// CHECK_ICX_M64: #define __BMI2__ 1
+// CHECK_ICX_M64: #define __BMI__ 1
+// CHECK_ICX_M64: #define __CLFLUSHOPT__ 1
+// CHECK_ICX_M64: #define __CLWB__ 1
+// CHECK_ICX_M64: #define __F16C__ 1
+// CHECK_ICX_M64: #define __FMA__ 1
+// CHECK_ICX_M64: #define __GFNI__ 1
+// CHECK_ICX_M64: #define __LZCNT__ 1
+// CHECK_ICX_M64: #define __MMX__ 1
+// CHECK_ICX_M64: #define __MPX__ 1
+// CHECK_ICX_M64: #define __PCLMUL__ 1
+// CHECK_ICX_M64: #define __PKU__ 1
+// 

[PATCH] D44559: [Sema] Wrong width of result of mul operation

2018-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

What would the design for that warning be?  C promotes all arithmetic on 
sub-int types to int, and if that's assigned back to a variable of the original 
type, there's a conversion.  But you seem to only want to warn about truncating 
the result of multiplication and not, say, addition or negation.  Is there a 
principle to this?  Just the likelihood of escaping the range of the original 
type?


https://reviews.llvm.org/D44559



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


[PATCH] D44764: [clangd] Use operator<< to prevent printers issues in Gtest

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(Thanks for sorting this out BTW!)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44764



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


[PATCH] D44764: [clangd] Use operator<< to prevent printers issues in Gtest

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/Protocol.h:673
 json::Expr toJSON(const CompletionItem &);
+std::ostream <<(std::ostream &, const CompletionItem &);
 

I think raw_ostream should work fine here, it's what we've done elsewhere.
Is there a reason to use std::ostream?

(llvm's gtest is specially modified so raw_ostream printers can be used)



Comment at: unittests/clangd/JSONExprTests.cpp:19
-void PrintTo(const Expr , std::ostream *OS) {
-  llvm::raw_os_ostream(*OS) << llvm::formatv("{0:2}", E);
-}

malaperle wrote:
> This one I couldn't change to operator<< because there was already one 
> defined with raw_ostream. But this just means losing indentation so perhaps 
> that's not too bad?
yeah, I think this is fine.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44764



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


[PATCH] D44765: PR36643 Make clang-format support more generic TMarcos

2018-03-29 Thread Teodor Petrov via Phabricator via cfe-commits
obfuscated added inline comments.



Comment at: lib/Format/FormatTokenLexer.cpp:386
   String->HasUnescapedNewline = Macro->HasUnescapedNewline;
+  String->TMacroStringLiteral = true;
 

krasimir wrote:
> In the original code, TMacro detection was done as:
> ```
> (Text.startswith(Prefix = "_T(\"") && Text.endswith(Postfix = "\")"))
> ```
> In the new code the left part is saved in TMacroStringLiteral, and the right 
> part is checked in ContinuationIndenter. Could you keep them together in 
> `FormatTokenLexer`.
> @alexfh, why are we checking for the right check at all? What would be an 
> example where this is needed to disambiguate?
> 
Are you talking about the code in ContinuationIndenter::createBreakableToken?

I don't think I understand how the hole thing works.
Using the debugger I can see that this function is executed first and then 
createBreakableToken.
So we first detect the tmacro in FormatTokenLexer::tryMerge_TMacro and then use 
this information in the createBreakableToken to do something with it.

So when I get a TMacroStringLiteral==true in createBreakableToken I know that 
the token starts with a TMacro and there is no need to use some king of 
startswith calls. Probably the endswith call is redundant and I can do just a 
string search backwards...


https://reviews.llvm.org/D44765



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:340
+  A[WordN] = Miss;
+  for (int I = WordN, P = PatN; I > 0; I--) {
+if (I == W)

sammccall wrote:
> MaskRay wrote:
> > sammccall wrote:
> > > sammccall wrote:
> > > > sammccall wrote:
> > > > > W is the right name in this file for a variable iterating over word 
> > > > > indices, please don't change this.
> > > > > The new variable above could be EndW or so?
> > > > As far as I can see, this loop is setting `A[W+1:...] = Miss` and 
> > > > populating `A[0...W]` with the exsting logic.
> > > > I think this would be clearer as two loops, currently there's a lot of 
> > > > conditionals around Last that obscure what's actually happening.
> > > You've shifted P (and the old W, new I) by 1. This does reduce the number 
> > > of +1 and -1 in this function, but it's inconsistent with how these are 
> > > used elsewhere: P should be the index into Pat of the character that 
> > > we're considering.
> > I don't understand the rationale not to use the shifted indices. The code 
> > actually use `Scores[P][W][*]` to mean the optimal match of the first `P` 
> > characters of the pattern with the first `W` characters of the word, not 
> > the position of the character.
> > 
> > On the other hand, C++ reverse iterators use the shifted one for `for (I = 
> > rend(); I != rbegin(); ++I)`. The shifted one makes ending condition check 
> > easier.
> > I don't understand the rationale not to use the shifted indices
> The rationale is entirely consistency with the surrounding code. The 
> consistency helps avoid off-by-one errors when similar loops have different 
> conventions.
> 
> In this file, when looping over word or pattern dimensions, P and W 
> respectively are used for loop variables, and can be interpreted as indices 
> into Pat/Word.
> Here the interpretation would be "did we match or miss character Word[W]"
`Scores[P][W][*]` is interpreted as how good it is if we align the first `P` 
characters of the pattern with the first `W` characters of the word.

Note the code uses `number of characters` instead of the position.

Here the new interpretation would be "what we should do for the last character 
of the first W characters"


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:230
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {

MaskRay wrote:
> sammccall wrote:
> > MaskRay wrote:
> > > sammccall wrote:
> > > > why this change?
> > > > this has also been moved from the cheaper constructor to the more 
> > > > expensive per-match call. (also the diagonal assignment added in the 
> > > > next loop)
> > > > 
> > > > Also, shouldn't [0][0][Match] be AwfulScore?
> > > > 
> > > "The more expensive per-match call" is just two value assignments.
> > > 
> > > I have removed the expensive table initialization in the constructor.
> > > 
> > > [0][0][*] can be any value.
> > > "The more expensive per-match call" is just two value assignments.
> > Oops, sorry - by "more expensive" I mean "called thousands of times more 
> > often".
> > 
> > > I have removed the expensive table initialization in the constructor.
> > I don't want to be rude, but I asked why you changed this, and you didn't 
> > answer. Unless there's a strong reason, I'd prefer to revert this change, 
> > as I find this harder to reason about.
> > (Roughly: in the old version of the code, any data that didn't need to 
> > change for the life of the object was initialized in the constructor. That 
> > way I didn't need to worry what was performance-critical and what wasn't - 
> > match() only did what was strictly necessary).
> > 
> > > [0][0][*] can be any value.
> > Can you please explain why?
> > Oops, sorry - by "more expensive" I mean "called thousands of times more 
> > often".
> 
> It is true that `Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};` is 
> the cost incurred for each word.
> 
> But **it is not full table initialization**, it is just two variable 
> assignments. And we will assign to other values of the first row 
> `Scores[0][*][*]` in the following loop. The old scatters the table 
> construction to **two places**, the constructor and this dynamic programming 
> site.
> [0][0][*] can be any value.

Can you please explain why?

`Scores[0][0][*]` is the initial value which will be propagated to all other 
values in the table.
The relative difference of pairwise values in the table is a constant whatever 
initial value is chosen.

If you ignore the max clamp you used later, the initial value does not matter.




Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay marked 4 inline comments as done.
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:230
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {

sammccall wrote:
> MaskRay wrote:
> > sammccall wrote:
> > > why this change?
> > > this has also been moved from the cheaper constructor to the more 
> > > expensive per-match call. (also the diagonal assignment added in the next 
> > > loop)
> > > 
> > > Also, shouldn't [0][0][Match] be AwfulScore?
> > > 
> > "The more expensive per-match call" is just two value assignments.
> > 
> > I have removed the expensive table initialization in the constructor.
> > 
> > [0][0][*] can be any value.
> > "The more expensive per-match call" is just two value assignments.
> Oops, sorry - by "more expensive" I mean "called thousands of times more 
> often".
> 
> > I have removed the expensive table initialization in the constructor.
> I don't want to be rude, but I asked why you changed this, and you didn't 
> answer. Unless there's a strong reason, I'd prefer to revert this change, as 
> I find this harder to reason about.
> (Roughly: in the old version of the code, any data that didn't need to change 
> for the life of the object was initialized in the constructor. That way I 
> didn't need to worry what was performance-critical and what wasn't - match() 
> only did what was strictly necessary).
> 
> > [0][0][*] can be any value.
> Can you please explain why?
> Oops, sorry - by "more expensive" I mean "called thousands of times more 
> often".

It is true that `Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};` is the 
cost incurred for each word.

But **it is not full table initialization**, it is just two variable 
assignments. And we will assign to other values of the first row 
`Scores[0][*][*]` in the following loop. The old scatters the table 
construction to **two places**, the constructor and this dynamic programming 
site.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D45054: Set dso_local on cfi_slowpath

2018-03-29 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

This looks wrong. cfi_slowpath is defined in libclang_rt.cfi, which is linked 
to the main executable. It is not always dso-local. On Android it is defined in 
libdl.so and is never dso-local.


https://reviews.llvm.org/D45054



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 140297.
MaskRay added a comment.

missScore -> missPenalty


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720

Files:
  clangd/FuzzyMatch.cpp
  clangd/FuzzyMatch.h

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -58,8 +58,8 @@
   void buildGraph();
   void calculateRoles(const char *Text, CharRole *Out, int , int N);
   bool allowMatch(int P, int W) const;
-  int skipPenalty(int W, Action Last) const;
-  int matchBonus(int P, int W, Action Last) const;
+  int missPenalty(int W, Action Last) const;
+  int matchScore(int P, int W, Action Last) const;
 
   // Pattern data is initialized by the constructor, then constant.
   char Pat[MaxPat]; // Pattern data
Index: clangd/FuzzyMatch.cpp
===
--- clangd/FuzzyMatch.cpp
+++ clangd/FuzzyMatch.cpp
@@ -58,6 +58,7 @@
 
 #include "FuzzyMatch.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 
 namespace clang {
@@ -67,7 +68,6 @@
 constexpr int FuzzyMatcher::MaxPat;
 constexpr int FuzzyMatcher::MaxWord;
 
-static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; }
 // A "negative infinity" score that won't overflow.
 // We use this to mark unreachable states and forbidden solutions.
 // Score field is 15 bits wide, min value is -2^14, we use half of that.
@@ -80,25 +80,18 @@
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I)
-LowPat[I] = lower(Pat[I]);
-  Scores[0][0][Miss] = {0, Miss};
-  Scores[0][0][Match] = {AwfulScore, Miss};
-  for (int P = 0; P <= PatN; ++P)
-for (int W = 0; W < P; ++W)
-  for (Action A : {Miss, Match})
-Scores[P][W][A] = {AwfulScore, Miss};
-  if (PatN > 0)
-calculateRoles(Pat, PatRole, PatTypeSet, PatN);
+LowPat[I] = toLower(Pat[I]);
+  calculateRoles(Pat, PatRole, PatTypeSet, PatN);
 }
 
 Optional FuzzyMatcher::match(StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
 return None;
-  if (!PatN)
-return 1;
   buildGraph();
-  auto Best = std::max(Scores[PatN][WordN][Miss].Score,
-   Scores[PatN][WordN][Match].Score);
+  // Find the optimal prefix of Word to match Pattern.
+  int Best = AwfulScore;
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
@@ -179,7 +172,8 @@
 }
 void FuzzyMatcher::calculateRoles(const char *Text, CharRole *Out, int ,
   int N) {
-  assert(N > 0);
+  if (!N)
+return;
   CharType Type = packedLookup(CharTypes, Text[0]);
   TypeSet = 1 << Type;
   // Types holds a sliding window of (Prev, Curr, Next) types.
@@ -206,10 +200,8 @@
   if (PatN > WordN)
 return false;
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;
   for (int I = 0; I < WordN; ++I)
-LowWord[I] = lower(Word[I]);
+LowWord[I] = toLower(Word[I]);
 
   // Cheap subsequence check.
   for (int W = 0, P = 0; P != PatN; ++W) {
@@ -236,31 +228,29 @@
 // This range is not strict: we can apply larger bonuses/penalties, or penalize
 // non-matched characters.
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {
-Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - skipPenalty(W, Miss),
+Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - missPenalty(W, Miss),
   Miss};
 Scores[0][W + 1][Match] = {AwfulScore, Miss};
   }
   for (int P = 0; P < PatN; ++P) {
+Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
 for (int W = P; W < WordN; ++W) {
   auto  = Scores[P + 1][W + 1],  = Scores[P + 1][W];
 
-  auto MatchMissScore = PreMiss[Match].Score;
-  auto MissMissScore = PreMiss[Miss].Score;
-  if (P < PatN - 1) { // Skipping trailing characters is always free.
-MatchMissScore -= skipPenalty(W, Match);
-MissMissScore -= skipPenalty(W, Miss);
-  }
+  auto MatchMissScore = PreMiss[Match].Score - missPenalty(W, Match);
+  auto MissMissScore = PreMiss[Miss].Score - missPenalty(W, Miss);
   Score[Miss] = (MatchMissScore > MissMissScore)
 ? ScoreInfo{MatchMissScore, Match}
 : ScoreInfo{MissMissScore, Miss};
 
   if (!allowMatch(P, W)) {
 Score[Match] = {AwfulScore, Miss};
   } else {
 auto  = Scores[P][W];
-auto MatchMatchScore = PreMatch[Match].Score + matchBonus(P, W, Match);
-auto MissMatchScore = PreMatch[Miss].Score + matchBonus(P, W, Miss);
+auto 

[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:21
+
+std::string exprToStr(const Expr *Expr,
+  const MatchFinder::MatchResult ) {

Please make it static. Same for other functions.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:56
+  FuncExpr->getArg(ArgPos)->IgnoreParenCasts())) {
+const auto LHSStr = exprToStr(BinOp->getLHS()->IgnoreParens(), Result);
+const auto RHSStr = exprToStr(BinOp->getRHS()->IgnoreParens(), Result);

Please don't use auto when type could not be deduced from statement itself 
(new, cast, iterator). Same for other places.



Comment at: docs/ReleaseNotes.rst:62
 
+- New `bugprone-not-null-terminated-result
+  
`_
 check

Please rebase for trunk, place check in alphabetical order in new checks list, 
use //:doc:// and proper link.



Comment at: docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst:4
+bugprone-not-null-terminated-result
+=
+

Is length same as length of title?



Comment at: docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst:6
+
+This check can be used to find function calls where ``strlen`` or ``wcslen``
+are passed as an argument and cause a not null-terminated result. Depending on

Please synchronize with statement in Release Notes.



Comment at: docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst:29
+
+In addition to issuing warnings, "Fix-it" rewrite all the necessary code
+depending on the version number. The upper code would be the following:

Please use fix-it. Same for other places.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45050



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/FuzzyMatch.cpp:96
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
 }

MaskRay wrote:
> sammccall wrote:
> > MaskRay wrote:
> > > I also don't understand why it clamps the value to zero here. Negative 
> > > values are also meaningful to me. Given that perfectBonus is only 3 it is 
> > > very easy to get a negative value here.
> > An important part of the contract of `match()` is that it returns a value 
> > in `[0,1]`.
> > We rely on this range to combine this with other scoring signals - we 
> > multiply this by a quality signal in code completion.
> > (Currently the quality signal is just derived from Sema, but the global 
> > index will provide the number of uses).
> > 
> > It would be possible to use a different squash function here, but I found 
> > max(kFloor,x) worked well for the examples I looked at - anything <= some 
> > floor value was "not really a useful match at all", and most of the 
> > variance below the floor seemed to be noise to me.
> > (Then I tuned the bonuses/penalties so the floor was at zero)
> We could try other criteria in the future. I believe the current one can be 
> improved because negative scores may be returned but the scoring shouldn't 
> return 0 for all the cases.
Sure, we can try other things, and to gather more data.
(To be clear though - with the data I *did* look at, including the scores <0 
did not add more information, only noise)



Comment at: clangd/FuzzyMatch.cpp:230
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {

MaskRay wrote:
> sammccall wrote:
> > why this change?
> > this has also been moved from the cheaper constructor to the more expensive 
> > per-match call. (also the diagonal assignment added in the next loop)
> > 
> > Also, shouldn't [0][0][Match] be AwfulScore?
> > 
> "The more expensive per-match call" is just two value assignments.
> 
> I have removed the expensive table initialization in the constructor.
> 
> [0][0][*] can be any value.
> "The more expensive per-match call" is just two value assignments.
Oops, sorry - by "more expensive" I mean "called thousands of times more often".

> I have removed the expensive table initialization in the constructor.
I don't want to be rude, but I asked why you changed this, and you didn't 
answer. Unless there's a strong reason, I'd prefer to revert this change, as I 
find this harder to reason about.
(Roughly: in the old version of the code, any data that didn't need to change 
for the life of the object was initialized in the constructor. That way I 
didn't need to worry what was performance-critical and what wasn't - match() 
only did what was strictly necessary).

> [0][0][*] can be any value.
Can you please explain why?



Comment at: clangd/FuzzyMatch.cpp:325
+  int W = PatN;
+  for (int I = PatN; ++I <= WordN; )
+if (Scores[PatN][I][Match].Score > Scores[PatN][W][Match].Score)

MaskRay wrote:
> sammccall wrote:
> > nit: I -> P, move increment to the increment expression of the for loop?
> I -> P.
> 
> > move increment to the increment expression of the for loop?
> 
> Not sure about the coding standard here, but if you insist I'll have to 
> change it as you are the reviewer. If the loop variable was an iterator, `for 
> (It I = std::next(...); I != E; ++I)` would be uglier than `for (It I = ...; 
> ++I != E; )`
Uglier is subjective, but side-effects in the condition of a for-loop is 
sufficiently unusual and surprising that I'd prefer to avoid it in both cases.



Comment at: clangd/FuzzyMatch.cpp:340
+  A[WordN] = Miss;
+  for (int I = WordN, P = PatN; I > 0; I--) {
+if (I == W)

MaskRay wrote:
> sammccall wrote:
> > sammccall wrote:
> > > sammccall wrote:
> > > > W is the right name in this file for a variable iterating over word 
> > > > indices, please don't change this.
> > > > The new variable above could be EndW or so?
> > > As far as I can see, this loop is setting `A[W+1:...] = Miss` and 
> > > populating `A[0...W]` with the exsting logic.
> > > I think this would be clearer as two loops, currently there's a lot of 
> > > conditionals around Last that obscure what's actually happening.
> > You've shifted P (and the old W, new I) by 1. This does reduce the number 
> > of +1 and -1 in this function, but it's inconsistent with how these are 
> > used elsewhere: P should be the index into Pat of the character that we're 
> > considering.
> I don't understand the rationale not to use the shifted indices. The code 
> actually use `Scores[P][W][*]` to mean the optimal match of the first `P` 
> characters of the pattern with the first `W` characters of the word, not the 
> position of the character.
> 
> On the other hand, C++ reverse iterators use the shifted one for `for (I = 
> 

[PATCH] D44882: [clangd] Implementation of workspace/symbol request

2018-03-29 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle added inline comments.



Comment at: clangd/FindSymbols.cpp:31
+
+  if (supportedSymbolKinds &&
+  std::find(supportedSymbolKinds->begin(), supportedSymbolKinds->end(),

MaskRay wrote:
> This std::find loop adds some overhead to each candidate... In my experience 
> the client usually doesn't care about the returned symbol kinds, they are 
> used to give a category name. You can always patch the upstream to add 
> missing categories.
> 
> This is one instance where LSP is over specified. nvm I don't have strong 
> opinion here
I have a client that throws an exception when the symbolkind is not known and 
the whole request fails, so I think it's worth checking. But if it's too slow I 
can look at making it faster. Unfortunately, I cannot patch any upstream 
project :)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44882



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 140294.
Charusso marked 5 inline comments as done.
Charusso added a comment.

Added the whole diff.


https://reviews.llvm.org/D45050

Files:
  clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tidy/bugprone/CMakeLists.txt
  clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/bugprone-not-null-terminated-result.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-strlen-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-before-cxx11.cpp
  test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp

Index: test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
===
--- /dev/null
+++ test/clang-tidy/bugprone-not-null-terminated-result-wcslen-cxx11.cpp
@@ -0,0 +1,153 @@
+// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- -- -std=c++11
+
+typedef unsigned int size_t;
+typedef int errno_t;
+size_t wcslen(const wchar_t *);
+wchar_t *wcschr(const wchar_t *, int);
+errno_t *wcsncpy_s(wchar_t *, const wchar_t *, size_t);
+
+void *alloca(size_t);
+void *calloc(size_t, size_t);
+void *malloc(size_t);
+void *realloc(void *, size_t);
+
+void *wmemcpy(void *, const void *, size_t);
+errno_t wmemcpy_s(void *, size_t, const void *, size_t);
+void *wmemchr(const void *, int, size_t);
+void *wmemmove(void *, const void *, size_t);
+errno_t wmemmove_s(void *, size_t, const void *, size_t);
+void *wmemset(void *, int, size_t);
+
+int wcsncmp(const wchar_t *, const wchar_t *, size_t);
+size_t wcsxfrm(wchar_t *, const wchar_t *, size_t);
+
+namespace std {
+using ::wcsncpy_s;
+using ::wmemcpy;
+using ::wcslen;
+}
+
+void bad_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'alloca' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: alloca(wcslen(src) + 1);
+}
+
+void good_alloca(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)alloca(wcslen(src) + 1);
+}
+
+void bad_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc(wcslen(src), sizeof(wchar_t));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'calloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void good_calloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)calloc((wcslen(src) + 1), sizeof(wchar_t));
+}
+
+void bad_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc(wcslen(src) * 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'malloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: malloc((wcslen(src) * 2) + 1);
+}
+
+void good_malloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)malloc((wcslen(src) * 2) + 1);
+}
+
+void bad_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + wcslen(src)));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'realloc' function's allocated memory cannot hold the null-terminator [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void good_realloc(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)realloc(dest, (wcslen(dest) + (wcslen(src) + 1)));
+}
+
+void bad_wmemcpy(wchar_t *dest, const wchar_t *src) {
+  std::wmemcpy(dest, src, std::wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void good_wmemcpy_cxx11(wchar_t *dest, const wchar_t *src) {
+  std::wcsncpy_s(dest, src, std::wcslen(src));
+}
+
+void bad_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wmemcpy_s(dest, wcslen(dest), src, wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'wmemcpy_s' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcsncpy_s(dest, src, wcslen(src));
+}
+
+void good_wmemcpy_s(wchar_t *dest, const wchar_t *src) {
+  wcsncpy_s(dest, src, wcslen(src));
+}
+
+void bad_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = (wchar_t *)wmemchr(src, '\0', wcslen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 'wmemchr' function's result is not null-terminated [bugprone-not-null-terminated-result]
+  // CHECK-FIXES: wcschr(src, '\0');
+}
+
+void good_wmemchr(wchar_t *dest, const wchar_t *src) {
+  dest = wcschr(src, '\0');
+}
+
+void bad_wmemmove(wchar_t *dest, const wchar_t *src) {
+  wmemmove(dest, src, wcslen(src));
+  // 

[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.h:30
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+private:
   void memAllocFuncFix(StringRef Name,

Please insert empty line above.


https://reviews.llvm.org/D45050



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

you should always upload the whole diff, not just the last changes.


https://reviews.llvm.org/D45050



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 140288.
Charusso added a comment.

Fixed the unseen diff issues, removed redundant parentheses, the class got a 
private part.


https://reviews.llvm.org/D45050

Files:
  clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
  clang-tidy/bugprone/NotNullTerminatedResultCheck.h
  docs/ReleaseNotes.rst


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -65,9 +65,6 @@
   Finds function calls where ``strlen`` or ``wcslen`` passed as argument and
   cause a not null-terminated result.
 
-- The 'misc-incorrect-roundings' check was renamed to 
`bugprone-incorrect-roundings
-  
`_
-
 - New module ``zircon`` for checks related to Fuchsia's Zircon kernel.
 
 - New `bugprone-throw-keyword-missing
Index: clang-tidy/bugprone/NotNullTerminatedResultCheck.h
===
--- clang-tidy/bugprone/NotNullTerminatedResultCheck.h
+++ clang-tidy/bugprone/NotNullTerminatedResultCheck.h
@@ -27,6 +27,7 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+private:
   void memAllocFuncFix(StringRef Name,
const ast_matchers::MatchFinder::MatchResult );
   void memHandlerFuncFix(StringRef Name,
Index: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
===
--- clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -1,3 +1,12 @@
+//===- NotNullTerminatedResultCheck.cpp - clang-tidy-*- C++ 
-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
 #include "NotNullTerminatedResultCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -49,7 +58,7 @@
 const auto StrLenArgStr = exprToStr(
 Result.Nodes.getNodeAs("length-call")->getArg(0), Result);
 
-return (StrLenArgStr == LHSStr || StrLenArgStr == RHSStr);
+return StrLenArgStr == LHSStr || StrLenArgStr == RHSStr;
   }
   return false;
 }


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -65,9 +65,6 @@
   Finds function calls where ``strlen`` or ``wcslen`` passed as argument and
   cause a not null-terminated result.
 
-- The 'misc-incorrect-roundings' check was renamed to `bugprone-incorrect-roundings
-  `_
-
 - New module ``zircon`` for checks related to Fuchsia's Zircon kernel.
 
 - New `bugprone-throw-keyword-missing
Index: clang-tidy/bugprone/NotNullTerminatedResultCheck.h
===
--- clang-tidy/bugprone/NotNullTerminatedResultCheck.h
+++ clang-tidy/bugprone/NotNullTerminatedResultCheck.h
@@ -27,6 +27,7 @@
   : ClangTidyCheck(Name, Context) {}
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+private:
   void memAllocFuncFix(StringRef Name,
const ast_matchers::MatchFinder::MatchResult );
   void memHandlerFuncFix(StringRef Name,
Index: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
===
--- clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -1,3 +1,12 @@
+//===- NotNullTerminatedResultCheck.cpp - clang-tidy-*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
 #include "NotNullTerminatedResultCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
@@ -49,7 +58,7 @@
 const auto StrLenArgStr = exprToStr(
 Result.Nodes.getNodeAs("length-call")->getArg(0), Result);
 
-return (StrLenArgStr == LHSStr || StrLenArgStr == RHSStr);
+return StrLenArgStr == LHSStr || StrLenArgStr == RHSStr;
   }
   return false;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D44882: [clangd] Implementation of workspace/symbol request

2018-03-29 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This is fantastic, really looking forward to using it.
I'm going to need to give up on vim at this rate, or do some serious work on 
ycm.

Most significant comments are around the new functions in SourceLocation, and 
whether we can keep the type-mapping restricted to the LSP layer.




Comment at: clangd/ClangdLSPServer.cpp:99
   
Params.capabilities.textDocument.completion.completionItem.snippetSupport;
+  if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
+  Params.capabilities.workspace->symbol->symbolKind)

malaperle wrote:
> sammccall wrote:
> > This is the analogue to the one on `completion` that we currently ignore, 
> > and one on `symbol` corresponding to the `documentSymbol` call which isn't 
> > implemented yet.
> > 
> > I think the value of the extended types is low and it might be worth 
> > leaving out of the first version to keep complexity down.
> > (If we really want it, the supporting code (mapping tables) should probably 
> > be in a place where it can be reused by `documentSymbol` and can live next 
> > to the equivalent for `completion`...)
> I think having Struct and EnumMember is nice and for sure once Macros is 
> there we will want to use it. So would it be OK to move to FindSymbols.cpp 
> (the new common file for document/symbol and workspace/symbol)?
> I think having Struct and EnumMember is nice and for sure once Macros is 
> there we will want to use it.
OK, fair enough.

I think what bothers me about this option is how deep it goes - this isn't 
really a request option in any useful sense.
I'd suggest the "C++ layer" i.e. ClangdServer should always return 
full-fidelity results, and the "LSP layer" should deal with folding them.

In which case adjustKindToCapability should live somewhere like protocol.h and 
get called from this file - WDYT?



Comment at: clangd/ClangdServer.h:161
 
+  void workspaceSymbols(StringRef Query,
+const clangd::WorkspaceSymbolOptions ,

nit: add a comment for this API, e.g. `/// Retrieve the top symbols from the 
workspace matching a query`



Comment at: clangd/FindSymbols.cpp:28
+  // All clients should support those.
+  if (Kind >= SymbolKind::File && Kind <= SymbolKind::Array)
+return Kind;

Can we rather have this condition checked when the client sets the supported 
symbols, and remove this special knowledge here?



Comment at: clangd/FindSymbols.cpp:32
+  if (supportedSymbolKinds &&
+  std::find(supportedSymbolKinds->begin(), supportedSymbolKinds->end(),
+Kind) != supportedSymbolKinds->end())

this seems gratuituously inefficient - I guess it doesn't matter that much, but 
can't we store the supported kinds as a std::bitset or so?



Comment at: clangd/FindSymbols.cpp:36
+
+  // Provide some fall backs for common kinds that are close enough.
+  if (Kind == SymbolKind::Struct)

nit: if we think this will be extended, a switch might be clearer



Comment at: clangd/FindSymbols.cpp:42
+
+  if (!supportedSymbolKinds) {
+// Provide some sensible default when all fails.

This code shouldn't need to handle this case. The LSP specifies the default set 
of supported types if it's not provided, so ClangdLSPServer should enure we 
always have a valid set



Comment at: clangd/FindSymbols.cpp:114
+  std::vector Result;
+  if (Query.empty() || !Index)
+return Result;

why Query.empty()?
In practice maybe showing results before you type is bad UX, but that seems up 
to the editor to decide.



Comment at: clangd/FindSymbols.cpp:117
+
+  auto Names = splitQualifiedName(Query);
+

nit: move this below the next "paragraph" where it's used?



Comment at: clangd/FindSymbols.cpp:130
+
+  // Global scope is represented by "" in FuzzyFind.
+  if (Names.first.startswith("::"))

nit: this is `Names.first.consume_front("::")`
Might be clearer as "FuzzyFind doesn't want leading :: qualifier" to avoid 
implication, that global namespace is special, particularly because...



Comment at: clangd/FindSymbols.cpp:130
+
+  // Global scope is represented by "" in FuzzyFind.
+  if (Names.first.startswith("::"))

sammccall wrote:
> nit: this is `Names.first.consume_front("::")`
> Might be clearer as "FuzzyFind doesn't want leading :: qualifier" to avoid 
> implication, that global namespace is special, particularly because...
actually the global namespace *is* special :-)

IMO If you type `Foo`, you should get results from any namespace, but if you 
type `::Foo` you should only get results from the global namespace.

So something like:
```
if (Names.first.consume_front("::") || !Names.first.empty())
  Req.Scopes = {Names.first};
```
though 

[PATCH] D44589: [Sema] Make deprecation fix-it replace all multi-parameter ObjC method slots.

2018-03-29 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL328807: [Sema] Make deprecation fix-it replace all 
multi-parameter ObjC method slots. (authored by vsapsai, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D44589?vs=139981=140286#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D44589

Files:
  cfe/trunk/include/clang/Basic/CharInfo.h
  cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/DelayedDiagnostic.cpp
  cfe/trunk/lib/Sema/SemaDeclAttr.cpp
  cfe/trunk/lib/Sema/SemaExpr.cpp
  cfe/trunk/lib/Sema/SemaExprObjC.cpp
  cfe/trunk/test/SemaObjC/attr-deprecated-replacement-fixit.m
  cfe/trunk/unittests/Basic/CharInfoTest.cpp

Index: cfe/trunk/include/clang/Basic/CharInfo.h
===
--- cfe/trunk/include/clang/Basic/CharInfo.h
+++ cfe/trunk/include/clang/Basic/CharInfo.h
@@ -180,14 +180,15 @@
 
 /// Return true if this is a valid ASCII identifier.
 ///
-/// Note that this is a very simple check; it does not accept '$' or UCNs as
-/// valid identifier characters.
-LLVM_READONLY inline bool isValidIdentifier(StringRef S) {
-  if (S.empty() || !isIdentifierHead(S[0]))
+/// Note that this is a very simple check; it does not accept UCNs as valid
+/// identifier characters.
+LLVM_READONLY inline bool isValidIdentifier(StringRef S,
+bool AllowDollar = false) {
+  if (S.empty() || !isIdentifierHead(S[0], AllowDollar))
 return false;
 
   for (StringRef::iterator I = S.begin(), E = S.end(); I != E; ++I)
-if (!isIdentifierBody(*I))
+if (!isIdentifierBody(*I, AllowDollar))
   return false;
 
   return true;
Index: cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
===
--- cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
+++ cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
@@ -31,6 +31,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Sema/Sema.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -138,15 +139,14 @@
   void Destroy();
 
   static DelayedDiagnostic makeAvailability(AvailabilityResult AR,
-SourceLocation Loc,
+ArrayRef Locs,
 const NamedDecl *ReferringDecl,
 const NamedDecl *OffendingDecl,
 const ObjCInterfaceDecl *UnknownObjCClass,
 const ObjCPropertyDecl  *ObjCProperty,
 StringRef Msg,
 bool ObjCPropertyAccess);
 
-
   static DelayedDiagnostic makeAccess(SourceLocation Loc,
   const AccessedEntity ) {
 DelayedDiagnostic DD;
@@ -194,6 +194,12 @@
 return StringRef(AvailabilityData.Message, AvailabilityData.MessageLen);
   }
 
+  ArrayRef getAvailabilitySelectorLocs() const {
+assert(Kind == Availability && "Not an availability diagnostic.");
+return llvm::makeArrayRef(AvailabilityData.SelectorLocs,
+  AvailabilityData.NumSelectorLocs);
+  }
+
   AvailabilityResult getAvailabilityResult() const {
 assert(Kind == Availability && "Not an availability diagnostic.");
 return AvailabilityData.AR;
@@ -238,6 +244,8 @@
 const ObjCPropertyDecl  *ObjCProperty;
 const char *Message;
 size_t MessageLen;
+SourceLocation *SelectorLocs;
+size_t NumSelectorLocs;
 AvailabilityResult AR;
 bool ObjCPropertyAccess;
   };
Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -3947,7 +3947,7 @@
 
   void redelayDiagnostics(sema::DelayedDiagnosticPool );
 
-  void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
+  void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef Locs,
   const ObjCInterfaceDecl *UnknownObjCClass,
   bool ObjCPropertyAccess,
   bool AvoidPartialAvailabilityChecks = false);
@@ -3962,7 +3962,7 @@
   // Expression Parsing Callbacks: SemaExpr.cpp.
 
   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
-  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
+  bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs,
  const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
  bool ObjCPropertyAccess = false,
  bool AvoidPartialAvailabilityChecks = false);

[PATCH] D44589: [Sema] Make deprecation fix-it replace all multi-parameter ObjC method slots.

2018-03-29 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC328807: [Sema] Make deprecation fix-it replace all 
multi-parameter ObjC method slots. (authored by vsapsai, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D44589?vs=139981=140287#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D44589

Files:
  include/clang/Basic/CharInfo.h
  include/clang/Sema/DelayedDiagnostic.h
  include/clang/Sema/Sema.h
  lib/Sema/DelayedDiagnostic.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/SemaExprObjC.cpp
  test/SemaObjC/attr-deprecated-replacement-fixit.m
  unittests/Basic/CharInfoTest.cpp

Index: include/clang/Sema/DelayedDiagnostic.h
===
--- include/clang/Sema/DelayedDiagnostic.h
+++ include/clang/Sema/DelayedDiagnostic.h
@@ -31,6 +31,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Sema/Sema.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -138,15 +139,14 @@
   void Destroy();
 
   static DelayedDiagnostic makeAvailability(AvailabilityResult AR,
-SourceLocation Loc,
+ArrayRef Locs,
 const NamedDecl *ReferringDecl,
 const NamedDecl *OffendingDecl,
 const ObjCInterfaceDecl *UnknownObjCClass,
 const ObjCPropertyDecl  *ObjCProperty,
 StringRef Msg,
 bool ObjCPropertyAccess);
 
-
   static DelayedDiagnostic makeAccess(SourceLocation Loc,
   const AccessedEntity ) {
 DelayedDiagnostic DD;
@@ -194,6 +194,12 @@
 return StringRef(AvailabilityData.Message, AvailabilityData.MessageLen);
   }
 
+  ArrayRef getAvailabilitySelectorLocs() const {
+assert(Kind == Availability && "Not an availability diagnostic.");
+return llvm::makeArrayRef(AvailabilityData.SelectorLocs,
+  AvailabilityData.NumSelectorLocs);
+  }
+
   AvailabilityResult getAvailabilityResult() const {
 assert(Kind == Availability && "Not an availability diagnostic.");
 return AvailabilityData.AR;
@@ -238,6 +244,8 @@
 const ObjCPropertyDecl  *ObjCProperty;
 const char *Message;
 size_t MessageLen;
+SourceLocation *SelectorLocs;
+size_t NumSelectorLocs;
 AvailabilityResult AR;
 bool ObjCPropertyAccess;
   };
Index: include/clang/Sema/Sema.h
===
--- include/clang/Sema/Sema.h
+++ include/clang/Sema/Sema.h
@@ -3947,7 +3947,7 @@
 
   void redelayDiagnostics(sema::DelayedDiagnosticPool );
 
-  void DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc,
+  void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef Locs,
   const ObjCInterfaceDecl *UnknownObjCClass,
   bool ObjCPropertyAccess,
   bool AvoidPartialAvailabilityChecks = false);
@@ -3962,7 +3962,7 @@
   // Expression Parsing Callbacks: SemaExpr.cpp.
 
   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
-  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
+  bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef Locs,
  const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
  bool ObjCPropertyAccess = false,
  bool AvoidPartialAvailabilityChecks = false);
Index: include/clang/Basic/CharInfo.h
===
--- include/clang/Basic/CharInfo.h
+++ include/clang/Basic/CharInfo.h
@@ -180,14 +180,15 @@
 
 /// Return true if this is a valid ASCII identifier.
 ///
-/// Note that this is a very simple check; it does not accept '$' or UCNs as
-/// valid identifier characters.
-LLVM_READONLY inline bool isValidIdentifier(StringRef S) {
-  if (S.empty() || !isIdentifierHead(S[0]))
+/// Note that this is a very simple check; it does not accept UCNs as valid
+/// identifier characters.
+LLVM_READONLY inline bool isValidIdentifier(StringRef S,
+bool AllowDollar = false) {
+  if (S.empty() || !isIdentifierHead(S[0], AllowDollar))
 return false;
 
   for (StringRef::iterator I = S.begin(), E = S.end(); I != E; ++I)
-if (!isIdentifierBody(*I))
+if (!isIdentifierBody(*I, AllowDollar))
   return false;
 
   return true;
Index: test/SemaObjC/attr-deprecated-replacement-fixit.m
===
--- test/SemaObjC/attr-deprecated-replacement-fixit.m
+++ 

r328807 - [Sema] Make deprecation fix-it replace all multi-parameter ObjC method slots.

2018-03-29 Thread Volodymyr Sapsai via cfe-commits
Author: vsapsai
Date: Thu Mar 29 10:34:09 2018
New Revision: 328807

URL: http://llvm.org/viewvc/llvm-project?rev=328807=rev
Log:
[Sema] Make deprecation fix-it replace all multi-parameter ObjC method slots.

Deprecation replacement can be any text but if it looks like a name of
ObjC method and has the same number of arguments as original method,
replace all slot names so after applying a fix-it you have valid code.

rdar://problem/36660853

Reviewers: aaron.ballman, erik.pilkington, rsmith

Reviewed By: erik.pilkington

Subscribers: cfe-commits, jkorous-apple

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


Added:
cfe/trunk/test/SemaObjC/attr-deprecated-replacement-fixit.m
Modified:
cfe/trunk/include/clang/Basic/CharInfo.h
cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/DelayedDiagnostic.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/lib/Sema/SemaExprObjC.cpp
cfe/trunk/unittests/Basic/CharInfoTest.cpp

Modified: cfe/trunk/include/clang/Basic/CharInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/CharInfo.h?rev=328807=328806=328807=diff
==
--- cfe/trunk/include/clang/Basic/CharInfo.h (original)
+++ cfe/trunk/include/clang/Basic/CharInfo.h Thu Mar 29 10:34:09 2018
@@ -180,14 +180,15 @@ LLVM_READONLY inline char toUppercase(ch
 
 /// Return true if this is a valid ASCII identifier.
 ///
-/// Note that this is a very simple check; it does not accept '$' or UCNs as
-/// valid identifier characters.
-LLVM_READONLY inline bool isValidIdentifier(StringRef S) {
-  if (S.empty() || !isIdentifierHead(S[0]))
+/// Note that this is a very simple check; it does not accept UCNs as valid
+/// identifier characters.
+LLVM_READONLY inline bool isValidIdentifier(StringRef S,
+bool AllowDollar = false) {
+  if (S.empty() || !isIdentifierHead(S[0], AllowDollar))
 return false;
 
   for (StringRef::iterator I = S.begin(), E = S.end(); I != E; ++I)
-if (!isIdentifierBody(*I))
+if (!isIdentifierBody(*I, AllowDollar))
   return false;
 
   return true;

Modified: cfe/trunk/include/clang/Sema/DelayedDiagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/DelayedDiagnostic.h?rev=328807=328806=328807=diff
==
--- cfe/trunk/include/clang/Sema/DelayedDiagnostic.h (original)
+++ cfe/trunk/include/clang/Sema/DelayedDiagnostic.h Thu Mar 29 10:34:09 2018
@@ -31,6 +31,7 @@
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Sema/Sema.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
@@ -138,7 +139,7 @@ public:
   void Destroy();
 
   static DelayedDiagnostic makeAvailability(AvailabilityResult AR,
-SourceLocation Loc,
+ArrayRef Locs,
 const NamedDecl *ReferringDecl,
 const NamedDecl *OffendingDecl,
 const ObjCInterfaceDecl 
*UnknownObjCClass,
@@ -146,7 +147,6 @@ public:
 StringRef Msg,
 bool ObjCPropertyAccess);
 
-
   static DelayedDiagnostic makeAccess(SourceLocation Loc,
   const AccessedEntity ) {
 DelayedDiagnostic DD;
@@ -194,6 +194,12 @@ public:
 return StringRef(AvailabilityData.Message, AvailabilityData.MessageLen);
   }
 
+  ArrayRef getAvailabilitySelectorLocs() const {
+assert(Kind == Availability && "Not an availability diagnostic.");
+return llvm::makeArrayRef(AvailabilityData.SelectorLocs,
+  AvailabilityData.NumSelectorLocs);
+  }
+
   AvailabilityResult getAvailabilityResult() const {
 assert(Kind == Availability && "Not an availability diagnostic.");
 return AvailabilityData.AR;
@@ -238,6 +244,8 @@ private:
 const ObjCPropertyDecl  *ObjCProperty;
 const char *Message;
 size_t MessageLen;
+SourceLocation *SelectorLocs;
+size_t NumSelectorLocs;
 AvailabilityResult AR;
 bool ObjCPropertyAccess;
   };

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=328807=328806=328807=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Thu Mar 29 10:34:09 2018
@@ -3947,7 +3947,7 @@ public:
 
   void redelayDiagnostics(sema::DelayedDiagnosticPool );
 
-  void DiagnoseAvailabilityOfDecl(NamedDecl *D, 

[PATCH] D45054: Set dso_local on cfi_slowpath

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola created this revision.
espindola added reviewers: rnk, echristo, eugenis.

https://reviews.llvm.org/D45054

Files:
  lib/CodeGen/CGExpr.cpp
  test/CodeGen/cfi-icall-cross-dso.c


Index: test/CodeGen/cfi-icall-cross-dso.c
===
--- test/CodeGen/cfi-icall-cross-dso.c
+++ test/CodeGen/cfi-icall-cross-dso.c
@@ -39,6 +39,11 @@
 // MS-DIAG: call void @__cfi_slowpath_diag(i64 4195979634929632483, i8* 
%{{.*}}, {{.*}}@[[DATA]]{{.*}}) {{.*}}, !nosanitize
 // MS-TRAP: call void @__cfi_slowpath(i64 4195979634929632483, i8* %{{.*}}) 
{{.*}}, !nosanitize
 
+// ITANIUM-DIAG: declare void @__cfi_slowpath_diag(
+// ITANIUM-TRAP: declare void @__cfi_slowpath(
+// MS-DIAG: declare dso_local void @__cfi_slowpath_diag(
+// MS-TRAP: declare dso_local void @__cfi_slowpath(
+
 void caller(void (*f)()) {
   f();
 }
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -2975,28 +2975,29 @@
   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
 
   llvm::CallInst *CheckCall;
+  llvm::Constant *SlowPathFn;
   if (WithDiag) {
 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
 auto *InfoPtr =
 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  llvm::GlobalVariable::PrivateLinkage, Info);
 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
 
-llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath_diag",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
 false));
 CheckCall = Builder.CreateCall(
-SlowPathDiagFn,
-{TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
+SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
   } else {
-llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
   }
 
+  CGM.setDSOLocal(cast(SlowPathFn->stripPointerCasts()));
   CheckCall->setDoesNotThrow();
 
   EmitBlock(Cont);


Index: test/CodeGen/cfi-icall-cross-dso.c
===
--- test/CodeGen/cfi-icall-cross-dso.c
+++ test/CodeGen/cfi-icall-cross-dso.c
@@ -39,6 +39,11 @@
 // MS-DIAG: call void @__cfi_slowpath_diag(i64 4195979634929632483, i8* %{{.*}}, {{.*}}@[[DATA]]{{.*}}) {{.*}}, !nosanitize
 // MS-TRAP: call void @__cfi_slowpath(i64 4195979634929632483, i8* %{{.*}}) {{.*}}, !nosanitize
 
+// ITANIUM-DIAG: declare void @__cfi_slowpath_diag(
+// ITANIUM-TRAP: declare void @__cfi_slowpath(
+// MS-DIAG: declare dso_local void @__cfi_slowpath_diag(
+// MS-TRAP: declare dso_local void @__cfi_slowpath(
+
 void caller(void (*f)()) {
   f();
 }
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -2975,28 +2975,29 @@
   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
 
   llvm::CallInst *CheckCall;
+  llvm::Constant *SlowPathFn;
   if (WithDiag) {
 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
 auto *InfoPtr =
 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  llvm::GlobalVariable::PrivateLinkage, Info);
 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
 
-llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath_diag",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
 false));
 CheckCall = Builder.CreateCall(
-SlowPathDiagFn,
-{TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
+SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
   } else {
-llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
+SlowPathFn = CGM.getModule().getOrInsertFunction(
 "__cfi_slowpath",
 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
   }
 
+  CGM.setDSOLocal(cast(SlowPathFn->stripPointerCasts()));
   CheckCall->setDoesNotThrow();
 
   EmitBlock(Cont);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2018-03-29 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: docs/ReleaseNotes.rst:137
+  
+- New `readability-unnecessary-intermediate-var
+  
`_
 check

Please use alphabetic order and //:doc:// as well as proper link. See other 
checks as example.


https://reviews.llvm.org/D37014



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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2018-03-29 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon marked an inline comment as done.
tbourvon added inline comments.



Comment at: docs/ReleaseNotes.rst:62
 
 - New `bugprone-throw-keyword-missing
   
`_
 check

Eugene.Zelenko wrote:
> Please rebase from trunk and use //:doc:// for link.
I'm sorry, what do you mean by "use :doc: for link"?


https://reviews.llvm.org/D37014



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


[PATCH] D37014: [clang-tidy] Add a checker to remove useless intermediate variables before return statements with comparisons

2018-03-29 Thread Tristan Bourvon via Phabricator via cfe-commits
tbourvon updated this revision to Diff 140278.
tbourvon marked 10 inline comments as done.
tbourvon added a comment.

Fixed review comments


https://reviews.llvm.org/D37014

Files:
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/ReadabilityTidyModule.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.cpp
  clang-tidy/readability/UnnecessaryIntermediateVarCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-unnecessary-intermediate-var.rst
  test/clang-tidy/readability-unnecessary-intermediate-var.cpp
  unittests/clang-tidy/ReadabilityModuleTest.cpp

Index: unittests/clang-tidy/ReadabilityModuleTest.cpp
===
--- unittests/clang-tidy/ReadabilityModuleTest.cpp
+++ unittests/clang-tidy/ReadabilityModuleTest.cpp
@@ -1,6 +1,8 @@
 #include "ClangTidyTest.h"
 #include "readability/BracesAroundStatementsCheck.h"
 #include "readability/NamespaceCommentCheck.h"
+#include "readability/UnnecessaryIntermediateVarCheck.h"
+#include "../../../unittests/ASTMatchers/ASTMatchersTest.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -500,6 +502,19 @@
 runCheckOnCode(Input));
 }
 
+TEST(StatementMatcher, HasSuccessor) {
+  using namespace ast_matchers;
+  using namespace matchers;
+
+  StatementMatcher DeclHasSuccessorReturnStmt =
+  declStmt(hasSuccessor(returnStmt()));
+
+  EXPECT_TRUE(
+  matches("void foo() { int bar; return; }", DeclHasSuccessorReturnStmt));
+  EXPECT_TRUE(notMatches("void foo() { int bar; bar++; return; }",
+ DeclHasSuccessorReturnStmt));
+}
+
 } // namespace test
 } // namespace tidy
 } // namespace clang
Index: test/clang-tidy/readability-unnecessary-intermediate-var.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-unnecessary-intermediate-var.cpp
@@ -0,0 +1,245 @@
+// RUN: %check_clang_tidy %s readability-unnecessary-intermediate-var %t
+
+bool f() {
+  auto test = 1; // Test
+  // CHECK-FIXES: {{^}}  // Test{{$}}
+  return (test == 1);
+  // CHECK-FIXES: {{^}}  return (1 == 1);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f2() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test1 == test2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: and so is 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-4]]:11: note: because they are only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-9]]:8: note: consider removing both this variable declaration
+  // CHECK-MESSAGES: :[[@LINE-8]]:8: note: and this one
+  // CHECK-MESSAGES: :[[@LINE-7]]:11: note: and directly using the variable initialization expressions here
+}
+
+bool f3() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (test1 == 2);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-7]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f4() {
+  auto test1 = 1; // Test1
+  auto test2 = 2; // Test2
+  // CHECK-FIXES: {{^}}  // Test2{{$}}
+  return (test2 == 3);
+  // CHECK-FIXES: {{^}}  return (2 == 3);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-4]]:8: warning: unnecessary intermediate variable 'test2' [readability-unnecessary-intermediate-var]
+  // CHECK-MESSAGES: :[[@LINE-3]]:11: note: because it is only used when returning the result of this comparison
+  // CHECK-MESSAGES: :[[@LINE-6]]:8: note: consider removing the variable declaration
+  // CHECK-MESSAGES: :[[@LINE-5]]:11: note: and directly using the variable initialization expression here
+}
+
+bool f5() {
+  auto test1 = 1; // Test1
+  // CHECK-FIXES: {{^}}  // Test1{{$}}
+  auto test2 = 2; // Test2
+  return (2 == test1);
+  // CHECK-FIXES: {{^}}  return (1 == 2);{{$}}
+  // CHECK-MESSAGES: :[[@LINE-5]]:8: warning: unnecessary intermediate variable 'test1' 

[PATCH] D45052: Mark __cfi_check as dso_local

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola created this revision.
espindola added reviewers: rnk, echristo.

https://reviews.llvm.org/D45052

Files:
  lib/CodeGen/CGExpr.cpp
  test/CodeGen/cfi-icall-cross-dso.c


Index: test/CodeGen/cfi-icall-cross-dso.c
===
--- test/CodeGen/cfi-icall-cross-dso.c
+++ test/CodeGen/cfi-icall-cross-dso.c
@@ -66,6 +66,9 @@
 inline void foo() {}
 void bar() { foo(); }
 
+// ITANIUM: define weak void @__cfi_check
+// MS: define weak dso_local void @__cfi_check
+
 // CHECK: !{i32 4, !"Cross-DSO CFI", i32 1}
 
 // Check that the type entries are correct.
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -3010,6 +3010,7 @@
   llvm::Function *F = llvm::Function::Create(
   llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
   llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
+  CGM.setDSOLocal(F);
   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
   // FIXME: consider emitting an intrinsic call like
   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)


Index: test/CodeGen/cfi-icall-cross-dso.c
===
--- test/CodeGen/cfi-icall-cross-dso.c
+++ test/CodeGen/cfi-icall-cross-dso.c
@@ -66,6 +66,9 @@
 inline void foo() {}
 void bar() { foo(); }
 
+// ITANIUM: define weak void @__cfi_check
+// MS: define weak dso_local void @__cfi_check
+
 // CHECK: !{i32 4, !"Cross-DSO CFI", i32 1}
 
 // Check that the type entries are correct.
Index: lib/CodeGen/CGExpr.cpp
===
--- lib/CodeGen/CGExpr.cpp
+++ lib/CodeGen/CGExpr.cpp
@@ -3010,6 +3010,7 @@
   llvm::Function *F = llvm::Function::Create(
   llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
   llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
+  CGM.setDSOLocal(F);
   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
   // FIXME: consider emitting an intrinsic call like
   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42034: [clang-format] In tests, expected code should be format-stable

2018-03-29 Thread Mark Zeren via Phabricator via cfe-commits
mzeren-vmw updated this revision to Diff 140276.
mzeren-vmw added a comment.

Update other verifyFormat implementations.


Repository:
  rC Clang

https://reviews.llvm.org/D42034

Files:
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestComments.cpp
  unittests/Format/FormatTestJS.cpp
  unittests/Format/FormatTestJava.cpp
  unittests/Format/FormatTestObjC.cpp
  unittests/Format/FormatTestProto.cpp
  unittests/Format/FormatTestTextProto.cpp


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -36,6 +36,7 @@
   }
 
   static void verifyFormat(llvm::StringRef Code, const FormatStyle ) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not 
stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
   }
 
Index: unittests/Format/FormatTestProto.cpp
===
--- unittests/Format/FormatTestProto.cpp
+++ unittests/Format/FormatTestProto.cpp
@@ -38,6 +38,7 @@
   }
 
   static void verifyFormat(llvm::StringRef Code) {
+EXPECT_EQ(Code.str(), format(Code)) << "Expected code is not stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code)));
   }
 };
Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -58,6 +58,7 @@
   }
 
   void verifyFormat(StringRef Code) {
+EXPECT_EQ(Code.str(), format(Code)) << "Expected code is not stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code)));
   }
 
Index: unittests/Format/FormatTestJava.cpp
===
--- unittests/Format/FormatTestJava.cpp
+++ unittests/Format/FormatTestJava.cpp
@@ -46,6 +46,7 @@
   static void verifyFormat(
   llvm::StringRef Code,
   const FormatStyle  = getGoogleStyle(FormatStyle::LK_Java)) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not 
stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
   }
 };
Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -49,14 +49,18 @@
   static void verifyFormat(
   llvm::StringRef Code,
   const FormatStyle  = getGoogleStyle(FormatStyle::LK_JavaScript)) {
+EXPECT_EQ(Code.str(), format(Code, Style))
+<< "Expected code is not stable";
 std::string Result = format(test::messUp(Code), Style);
 EXPECT_EQ(Code.str(), Result) << "Formatted:\n" << Result;
   }
 
   static void verifyFormat(
   llvm::StringRef Expected,
   llvm::StringRef Code,
   const FormatStyle  = getGoogleStyle(FormatStyle::LK_JavaScript)) {
+EXPECT_EQ(Expected.str(), format(Expected, Style))
+<< "Expected code is not stable";
 std::string Result = format(Code, Style);
 EXPECT_EQ(Expected.str(), Result) << "Formatted:\n" << Result;
   }
Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -70,6 +70,7 @@
 
   void verifyFormat(llvm::StringRef Code,
 const FormatStyle  = getLLVMStyle()) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not 
stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
   }
 
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -72,6 +72,8 @@
 
   void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
 const FormatStyle  = getLLVMStyle()) {
+EXPECT_EQ(Expected.str(), format(Expected, Style))
+<< "Expected code is not stable";
 EXPECT_EQ(Expected.str(), format(Code, Style));
 if (Style.Language == FormatStyle::LK_Cpp) {
   // Objective-C++ is a superset of C++, so everything checked for C++


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -36,6 +36,7 @@
   }
 
   static void verifyFormat(llvm::StringRef Code, const FormatStyle ) {
+EXPECT_EQ(Code.str(), format(Code, Style)) << "Expected code is not stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
   }
 
Index: unittests/Format/FormatTestProto.cpp
===
--- unittests/Format/FormatTestProto.cpp
+++ unittests/Format/FormatTestProto.cpp
@@ -38,6 +38,7 @@
   }
 
   static void verifyFormat(llvm::StringRef Code) {
+EXPECT_EQ(Code.str(), 

[PATCH] D44723: Set dso_local when clearing dllimport

2018-03-29 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola closed this revision.
espindola added a comment.

328801


https://reviews.llvm.org/D44723



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


r328801 - Set dso_local when clearing dllimport.

2018-03-29 Thread Rafael Espindola via cfe-commits
Author: rafael
Date: Thu Mar 29 09:45:18 2018
New Revision: 328801

URL: http://llvm.org/viewvc/llvm-project?rev=328801=rev
Log:
Set dso_local when clearing dllimport.

Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/test/CodeGenCXX/dllimport.cpp

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=328801=328800=328801=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Thu Mar 29 09:45:18 2018
@@ -2398,8 +2398,10 @@ llvm::Constant *CodeGenModule::GetOrCrea
 }
 
 // Handle dropped DLL attributes.
-if (D && !D->hasAttr() && !D->hasAttr())
+if (D && !D->hasAttr() && !D->hasAttr()) {
   Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
+  setDSOLocal(Entry);
+}
 
 // If there are two attempts to define the same mangled name, issue an
 // error.

Modified: cfe/trunk/test/CodeGenCXX/dllimport.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/dllimport.cpp?rev=328801=328800=328801=diff
==
--- cfe/trunk/test/CodeGenCXX/dllimport.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/dllimport.cpp Thu Mar 29 09:45:18 2018
@@ -203,6 +203,8 @@ USEVAR(VarTmpl)
 // Functions
 
//===--===//
 
+// GNU-DAG: declare dso_local void @_ZdlPv(i8*)
+
 // Import function declaration.
 // MSC-DAG: declare dllimport void @"?decl@@YAXXZ"()
 // GNU-DAG: declare dllimport void @_Z4declv()


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


[PATCH] D43341: [clang-doc] Implement reducer portion of the frontend framework

2018-03-29 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett updated this revision to Diff 140275.
juliehockett added a comment.

Fixing assert on vector size.


https://reviews.llvm.org/D43341

Files:
  clang-doc/BitcodeReader.cpp
  clang-doc/BitcodeReader.h
  clang-doc/BitcodeWriter.cpp
  clang-doc/BitcodeWriter.h
  clang-doc/CMakeLists.txt
  clang-doc/Reducer.cpp
  clang-doc/Reducer.h
  clang-doc/Representation.cpp
  clang-doc/Representation.h
  clang-doc/tool/ClangDocMain.cpp
  docs/ReleaseNotes.rst
  test/clang-doc/bc-comment.cpp
  test/clang-doc/bc-namespace.cpp
  test/clang-doc/bc-record.cpp

Index: test/clang-doc/bc-record.cpp
===
--- /dev/null
+++ test/clang-doc/bc-record.cpp
@@ -0,0 +1,178 @@
+// This test requires Linux due to the system-dependent USR for the
+// inner class in function H.
+// REQUIRES: system-linux
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --dump -doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: llvm-bcanalyzer %t/docs/bc/docs.bc --dump | FileCheck %s
+
+union A { int X; int Y; };
+
+enum B { X, Y };
+
+enum class Bc { A, B };
+
+struct C { int i; };
+
+class D {};
+
+class E {
+public:
+  E() {}
+  ~E() {}
+
+protected:
+  void ProtectedMethod();
+};
+
+void E::ProtectedMethod() {}
+
+class F : virtual private D, public E {};
+
+class X {
+  class Y {};
+};
+
+void H() {
+  class I {};
+}
+
+// CHECK: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'E'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'void'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = '~E'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'void'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'ProtectedMethod'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'void'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'H'
+  // CHECK-NEXT:  blob data = '3433664532ABFCC39301646A10E768C1882BF194'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'void'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'A'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'A::X'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'A::Y'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'C'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+// CHECK-NEXT:  blob data = 'int'
+// CHECK-NEXT:  blob data = 'C::i'
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'D'
+  // CHECK-NEXT:  blob data = 'E3B54702FABFF4037025BA194FC27C47006330B5'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'E'
+  // CHECK-NEXT:  blob data = 'E3B54702FABFF4037025BA194FC27C47006330B5'
+  // CHECK-NEXT:  blob data = 'DEB4AC1CD9253CD9EF7FBE6BCAC506D77984ABD4'
+  // CHECK-NEXT:  blob data = 'DEB4AC1CD9253CD9EF7FBE6BCAC506D77984ABD4'
+  // CHECK-NEXT:  blob data = 'BD2BDEBD423F80BACCEA75DE6D6622D355FC2D17'
+  // CHECK-NEXT:  blob data = 'BD2BDEBD423F80BACCEA75DE6D6622D355FC2D17'
+  // CHECK-NEXT:  blob data = '5093D428CDC62096A67547BA52566E4FB9404EEE'
+  // CHECK-NEXT:  blob data = '5093D428CDC62096A67547BA52566E4FB9404EEE'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'F'
+  // CHECK-NEXT:  blob data = '{{.*}}'
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = '289584A8E0FF4178A794622A547AA622503967A1'
+  // CHECK-NEXT:  blob data = '0921737541208B8FA9BB42B60F78AC1D779AA054'
+// CHECK-NEXT: 
+// CHECK-NEXT: 
+  // CHECK-NEXT: 
+  // CHECK-NEXT:  blob data = 'X'
+  // CHECK-NEXT:  blob data = '641AB4A3D36399954ACDE29C7A8833032BF40472'
+  // CHECK-NEXT:  

r328800 - Add a dllimport test.

2018-03-29 Thread Rafael Espindola via cfe-commits
Author: rafael
Date: Thu Mar 29 09:35:52 2018
New Revision: 328800

URL: http://llvm.org/viewvc/llvm-project?rev=328800=rev
Log:
Add a dllimport test.

Thanks to rnk for the suggestion.

Added:
cfe/trunk/test/CodeGen/flip-dllimport.c

Added: cfe/trunk/test/CodeGen/flip-dllimport.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/flip-dllimport.c?rev=328800=auto
==
--- cfe/trunk/test/CodeGen/flip-dllimport.c (added)
+++ cfe/trunk/test/CodeGen/flip-dllimport.c Thu Mar 29 09:35:52 2018
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -fms-extensions -emit-llvm -o - 
%s | FileCheck %s
+
+__declspec(dllimport) void f();
+void g() { f(); } // use it
+
+// CHECK: define dso_local dllexport void @f
+void f() { }


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


[PATCH] D44882: [clangd] Implementation of workspace/symbol request

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FindSymbols.cpp:31
+
+  if (supportedSymbolKinds &&
+  std::find(supportedSymbolKinds->begin(), supportedSymbolKinds->end(),

This std::find loop adds some overhead to each candidate... In my experience 
the client usually doesn't care about the returned symbol kinds, they are used 
to give a category name. You can always patch the upstream to add missing 
categories.

This is one instance where LSP is over specified. nvm I don't have strong 
opinion here



Comment at: clangd/Protocol.cpp:206
+
+bool fromJSON(const json::Expr , WorkspaceClientCapabilities ) {
+  json::ObjectMapper O(Params);

This copy-pasting exposes another problem that the current  `fromJSON` `toJSON` 
approach is too verbose and you may find other space-efficient serialization 
format convenient  Anyway, they can always be improved in the future.



Comment at: clangd/tool/ClangdMain.cpp:235
 
+  clangd::WorkspaceSymbolOptions WorkspaceSymOpts;
+  WorkspaceSymOpts.Limit = LimitResults;

I know command line options are easy for testing purpose but they are clumsy 
for users. You need a "initialization option" <-> "command line option" bridge.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44882



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


[PATCH] D44985: Remove initializer for CUDA shared varirable

2018-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D44985#1051840, @yaxunl wrote:

> In https://reviews.llvm.org/D44985#1050876, @rjmccall wrote:
>
> > In https://reviews.llvm.org/D44985#1050674, @yaxunl wrote:
> >
> > > In https://reviews.llvm.org/D44985#1050670, @rjmccall wrote:
> > >
> > > > What exactly are you trying to express here?  Are you just trying to 
> > > > make these external declarations when compiling for the device because 
> > > > `__shared__` variables are actually defined on the host?  That should 
> > > > be handled by the frontend by setting up the AST so that these 
> > > > declarations are not definitions.
> > >
> > >
> > > No. These variables are not like external symbols defined on the host. 
> > > They behave like global variables in the kernel code but never 
> > > initialized. Currently no targets are able to initialize them and it is 
> > > users' responsibility to initialize them explicitly.
> > >
> > > Giving them an initial value will cause error in some backends since they 
> > > cannot handle them, therefore put undef as initializer.
> >
> >
> > So undef is being used as a special marker to the backends that it's okay 
> > not to try to initialize these variables?
>
>
> I think undef as the initializer tells the llvm passes and backend that this 
> global variable contains undefined value. I am not sure if this is better 
> than without an initializer. I saw code in 
> CodeGenModule::getOrCreateStaticVarDecl
>
>   // Local address space cannot have an initializer.
>   llvm::Constant *Init = nullptr;
>   if (Ty.getAddressSpace() != LangAS::opencl_local)
> Init = EmitNullConstant(Ty);
>   else
> Init = llvm::UndefValue::get(LTy);
>   
>   
>
> which means OpenCL static variable in local address space (equivalent to CUDA 
> shared address space) gets an undef initializer.
>
> For CUDA shared variable, in CodeGenFunction::EmitStaticVarDecl, it first 
> goes through call of CodeGenModule::getOrCreateStaticVarDecl and gets a 
> zeroinitializer, then it reaches line 400
>
>   // Whatever initializer such variable may have when it gets here is
> // a no-op and should not be emitted.
> bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
>D.hasAttr();
> // If this value has an initializer, emit it.
> if (D.getInit() && !isCudaSharedVar)
>   var = AddInitializerToStaticVarDecl(D, var);
>  
>
>
> Although this disables adding initializer from D, var already has a 
> zeroinitializer from CodeGenModule::getOrCreateStaticVarDecl, therefore its 
> initializer needs to be overwritten by undef.
>
> Probably a better solution would be do it in  
> CodeGenModule::getOrCreateStaticVarDecl, side by side by the OpenCL code.


Yes, I agree, just updating the condition to trigger if either language mode is 
set is the right fix.


https://reviews.llvm.org/D44985



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


[PATCH] D44883: [Sema] Extend -Wself-assign and -Wself-assign-field to warn on overloaded self-assignment (classes)

2018-03-29 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In https://reviews.llvm.org/D44883#1051878, @lebedev.ri wrote:

> Ok, tried llvm stage2 build, and it failed as expected, in code that 
> intentionally does self-assignment:


Actually, this is not the sort of failure that I think should worry you.  Any 
new warning has the ability to break -Werror builds; if I saw this failure in a 
build, I would totally consider it a project bug, not a false-positive.

In this case, you should just make sure there's a reasonable way to suppress 
the warning and then fix the code in LLVM by doing that.  Explicitly casting 
the RHS to the right reference type should shut the compiler up.


Repository:
  rC Clang

https://reviews.llvm.org/D44883



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


[PATCH] D44882: [clangd] Implementation of workspace/symbol request

2018-03-29 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle added a comment.

I realized that using the draft store has limited improvement for now because 
not many symbol locations come from main files (.cpp, etc) and when headers are 
modified, the main files are not reindexed right now. So the draft store will 
give better location for example when navigating to a function definition which 
moved in the unsaved main file. But it will be more general once header updates 
are handled better.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44882



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


[PATCH] D44882: [clangd] Implementation of workspace/symbol request

2018-03-29 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle updated this revision to Diff 140272.
malaperle added a comment.

Use the DraftStore for offset -> line/col when there is a draft available.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44882

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/FindSymbols.cpp
  clangd/FindSymbols.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  clangd/SourceCode.cpp
  clangd/SourceCode.h
  clangd/XRefs.cpp
  clangd/index/SymbolCollector.cpp
  clangd/tool/ClangdMain.cpp
  test/clangd/initialize-params-invalid.test
  test/clangd/initialize-params.test
  unittests/clangd/CMakeLists.txt
  unittests/clangd/FindSymbolsTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -41,6 +41,10 @@
 
 std::string runDumpAST(ClangdServer , PathRef File);
 
+llvm::Expected
+runWorkspaceSymbols(ClangdServer , StringRef Query,
+const WorkspaceSymbolOptions , const DraftStore );
+
 } // namespace clangd
 } // namespace clang
 
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -110,5 +110,13 @@
   return std::move(*Result);
 }
 
+llvm::Expected
+runWorkspaceSymbols(ClangdServer , StringRef Query,
+const WorkspaceSymbolOptions , const DraftStore ) {
+  llvm::Optional> Result;
+  Server.workspaceSymbols(Query, Opts, DS, capture(Result));
+  return std::move(*Result);
+}
+
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/FindSymbolsTests.cpp
===
--- /dev/null
+++ unittests/clangd/FindSymbolsTests.cpp
@@ -0,0 +1,383 @@
+//===-- FindSymbolsTests.cpp -*- C++ -*===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+#include "Annotations.h"
+#include "ClangdServer.h"
+#include "DraftStore.h"
+#include "FindSymbols.h"
+#include "SyncAPI.h"
+#include "TestFS.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+
+void PrintTo(const SymbolInformation , std::ostream *O) {
+  llvm::raw_os_ostream OS(*O);
+  OS << I.containerName << I.name << " - " << toJSON(I);
+}
+
+namespace {
+
+using ::testing::AllOf;
+using ::testing::AnyOf;
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+using ::testing::UnorderedElementsAre;
+
+class IgnoreDiagnostics : public DiagnosticsConsumer {
+  void onDiagnosticsReady(PathRef File,
+  std::vector Diagnostics) override {}
+};
+
+// GMock helpers for matching SymbolInfos items.
+MATCHER_P(Named, Name, "") { return arg.name == Name; }
+MATCHER_P(InContainer, ContainerName, "") {
+  return arg.containerName == ContainerName;
+}
+MATCHER_P(WithKind, Kind, "") { return arg.kind == Kind; }
+
+class WorkspaceSymbolsTest : public ::testing::Test {
+protected:
+  std::unique_ptr FSProvider;
+  std::unique_ptr CDB;
+  std::unique_ptr DiagConsumer;
+  std::unique_ptr Server;
+  std::unique_ptr Opts;
+  std::unique_ptr DS;
+
+  virtual void SetUp() override {
+FSProvider = llvm::make_unique();
+CDB = llvm::make_unique();
+DiagConsumer = llvm::make_unique();
+auto ServerOpts = ClangdServer::optsForTest();
+ServerOpts.BuildDynamicSymbolIndex = true;
+Server = llvm::make_unique(*CDB, *FSProvider, *DiagConsumer,
+ ServerOpts);
+Opts = llvm::make_unique();
+DS = llvm::make_unique();
+  }
+
+  std::vector getSymbols(StringRef Query) {
+EXPECT_TRUE(Server->blockUntilIdleForTest()) << "Waiting for preamble";
+auto SymbolInfos = runWorkspaceSymbols(*Server, Query, *Opts, *DS);
+EXPECT_TRUE(bool(SymbolInfos)) << "workspaceSymbols returned an error";
+return *SymbolInfos;
+  }
+
+  void addFile(StringRef FileName, StringRef Contents) {
+auto Path = testPath(FileName);
+FSProvider->Files[Path] = Contents;
+Server->addDocument(Path, Contents);
+  }
+};
+
+} // namespace
+
+TEST_F(WorkspaceSymbolsTest, NoMacro) {
+  addFile("foo.cpp", R"cpp(
+  #define MACRO X
+  )cpp");
+
+  // Macros are not in the index.
+  EXPECT_THAT(getSymbols("macro"), IsEmpty());
+}
+
+TEST_F(WorkspaceSymbolsTest, NoLocals) {
+  addFile("foo.cpp", R"cpp(
+  void test() {
+struct LocalClass {};
+int local_var;
+  })cpp");
+  EXPECT_THAT(getSymbols("local_var"), 

[PATCH] D44994: [clang-format] Ensure wrapped ObjC selectors with 1 arg obey IndentWrappedFunctionNames

2018-03-29 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton marked an inline comment as done.
benhamilton added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:904
+   : State.Stack.back().Indent);
   if (NextNonComment->LongestObjCSelectorName == 0)
+return MinIndent;

djasper wrote:
> benhamilton wrote:
> > djasper wrote:
> > > Does this if actually change the behavior in any way? With 
> > > LongestObjCSelectorName being 0, isn't that:
> > > 
> > >   return MinIndent +
> > >  std::max(0, ColumnWidth) - ColumnWidth;
> > > 
> > > (and with ColumnWidth being >= 0, this should be just MinIndent)
> > The `- ColumnWidth` part is only for the case where 
> > `LongestObjCSelectorName` is *not* 0. If it's 0, we return `MinIndent` 
> > which ensures we obey `Style.IndentWrappedFunctionNames`.
> > 
> > The problem with the code before this diff is when 
> > `LongestObjCSelectorName` was 0, we ignored 
> > `Style.IndentWrappedFunctionNames` and always returned 
> > `State.Stack.back().Indent` regardless of that setting.
> > 
> > After this diff, when `LongestObjCSelectorName` is 0 (i.e., this is either 
> > the first part of the selector or a selector which is not colon-aligned due 
> > to block formatting), we change the behavior to indent to at least 
> > `State.FirstIndent + Style.ContinuationIndentWidth`, like all other 
> > indentation logic in this file.
> > 
> > I've added some comments explaining what's going on, since this code is 
> > quite complex.
> I am not saying your change is wrong.  And I might be getting out of practice 
> with coding. My question is, what changes if you remove lines 906 and 907 
> (the "if (...) return MinIndent")?
Oh, I see what you're saying now! Thanks for clarifying.

Yes, we can remove these lines now. Done.


Repository:
  rC Clang

https://reviews.llvm.org/D44994



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


[PATCH] D44994: [clang-format] Ensure wrapped ObjC selectors with 1 arg obey IndentWrappedFunctionNames

2018-03-29 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 140271.
benhamilton added a comment.

Remove if (...) return MinIndent.


Repository:
  rC Clang

https://reviews.llvm.org/D44994

Files:
  lib/Format/ContinuationIndenter.cpp
  unittests/Format/FormatTestObjC.cpp


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -537,6 +537,22 @@
"   aShortf:(NSRect)theRect {\n"
"}");
 
+  // Make sure selectors with 0, 1, or more arguments are indented
+  // when IndentWrappedFunctionNames is true.
+  verifyFormat("- (a)\n"
+   ";\n");
+  verifyFormat("- (a)\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   " aaa:(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   " aaa:(int)a;\n");
+
   // Format pairs correctly.
   Style.ColumnLimit = 80;
   verifyFormat("- (void)drawRectOn:(id)surface\n"
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -896,12 +896,20 @@
 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
   if (NextNonComment->is(TT_SelectorName)) {
 if (!State.Stack.back().ObjCSelectorNameFound) {
-  if (NextNonComment->LongestObjCSelectorName == 0)
-return State.Stack.back().Indent;
-  return (Style.IndentWrappedFunctionNames
-  ? std::max(State.Stack.back().Indent,
- State.FirstIndent + Style.ContinuationIndentWidth)
-  : State.Stack.back().Indent) +
+  unsigned MinIndent = State.Stack.back().Indent;
+  if (Style.IndentWrappedFunctionNames)
+MinIndent = std::max(MinIndent,
+ State.FirstIndent + 
Style.ContinuationIndentWidth);
+  // If LongestObjCSelectorName is 0, we are indenting the first
+  // part of an ObjC selector (or a selector component which is
+  // not colon-aligned due to block formatting).
+  //
+  // Otherwise, we are indenting a subsequent part of an ObjC
+  // selector which should be colon-aligned to the longest
+  // component of the ObjC selector.
+  //
+  // In either case, we want to respect Style.IndentWrappedFunctionNames.
+  return MinIndent +
  std::max(NextNonComment->LongestObjCSelectorName,
   NextNonComment->ColumnWidth) -
  NextNonComment->ColumnWidth;


Index: unittests/Format/FormatTestObjC.cpp
===
--- unittests/Format/FormatTestObjC.cpp
+++ unittests/Format/FormatTestObjC.cpp
@@ -537,6 +537,22 @@
"   aShortf:(NSRect)theRect {\n"
"}");
 
+  // Make sure selectors with 0, 1, or more arguments are indented
+  // when IndentWrappedFunctionNames is true.
+  verifyFormat("- (a)\n"
+   ";\n");
+  verifyFormat("- (a)\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   " aaa:(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   " aaa:(int)a;\n");
+
   // Format pairs correctly.
   Style.ColumnLimit = 80;
   verifyFormat("- (void)drawRectOn:(id)surface\n"
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -896,12 +896,20 @@
 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
   if (NextNonComment->is(TT_SelectorName)) {
 if (!State.Stack.back().ObjCSelectorNameFound) {
-  if (NextNonComment->LongestObjCSelectorName == 0)
-return State.Stack.back().Indent;
-  return (Style.IndentWrappedFunctionNames
-  ? 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:96
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
 }

sammccall wrote:
> MaskRay wrote:
> > I also don't understand why it clamps the value to zero here. Negative 
> > values are also meaningful to me. Given that perfectBonus is only 3 it is 
> > very easy to get a negative value here.
> An important part of the contract of `match()` is that it returns a value in 
> `[0,1]`.
> We rely on this range to combine this with other scoring signals - we 
> multiply this by a quality signal in code completion.
> (Currently the quality signal is just derived from Sema, but the global index 
> will provide the number of uses).
> 
> It would be possible to use a different squash function here, but I found 
> max(kFloor,x) worked well for the examples I looked at - anything <= some 
> floor value was "not really a useful match at all", and most of the variance 
> below the floor seemed to be noise to me.
> (Then I tuned the bonuses/penalties so the floor was at zero)
We could try other criteria in the future. I believe the current one can be 
improved because negative scores may be returned but the scoring shouldn't 
return 0 for all the cases.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen or wcslen

2018-03-29 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:1
+#include "NotNullTerminatedResultCheck.h"
+#include "clang/AST/ASTContext.h"

Missing header blurb



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:14
+  const MatchFinder::MatchResult ) {
+  return Lexer::getSourceText(
+  CharSourceRange::getTokenRange(Expr->getSourceRange()),

Doesn't `Lexer::getSourceText()` return `StringRef`?



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:264
+const auto FirstArg = FuncExpr->getArg(0);
+std::string NewSecondArg = " strlen(" + exprToStr(FirstArg, Result) + "),";
+

This should probably be `SmallString<32>`



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.h:40
+   DiagnosticBuilder );
+  void memchrFix(StringRef Name,
+ const ast_matchers::MatchFinder::MatchResult ,

Why are all these internal functions `public`?
They should be either in anonymous namespace (best), or at least have `private` 
visibility.



Comment at: docs/ReleaseNotes.rst:68
+
+- The 'misc-incorrect-roundings' check was renamed to 
`bugprone-incorrect-roundings
+  
`_

This seems out-of-place. Why is this in the diff?



Comment at: 
test/clang-tidy/bugprone-not-null-terminated-result-strlen-before-cxx11.cpp:11
+void bad_memcpy(char *dest, const char *src) {
+  memcpy(dest, src, strlen(src));
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'memcpy' function's result is 
not null-terminated [bugprone-not-null-terminated-result]

What about these functions, but in `std::` namespace?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D45050



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:93
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))

sammccall wrote:
> MaskRay wrote:
> > sammccall wrote:
> > > this looks like a behavior change - why?
> > This is a behavior change. Instead of choosing between `Match/Miss` in the 
> > last position, we enumerate the last matching position in `Word`.
> > 
> > This saves `if (P < PatN - 1) {` check in the main loop at the cost of a 
> > for loop here (use sites of ending values)
> Ah, I see - the case where we match only part of the word is handled up here 
> now.
> (I think you mean this is not a behavior change? The result is the same 
> AFAICS)
> 
> That does make more sense, but it's pretty subtle.
> Can you add a comment like
>  `// The pattern doesn't have to match the whole word (but the whole pattern 
> must match).`
Added
```
  // Find the optimal prefix of Word to match Pattern.
```

I meant this is a behavior change but it makes the first row and the rest rows 
of the score table more consistent.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 140268.
MaskRay added a comment.

Add comment

  // Find the optimal prefix of Word to match Pattern.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720

Files:
  clangd/FuzzyMatch.cpp
  clangd/FuzzyMatch.h

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -58,8 +58,8 @@
   void buildGraph();
   void calculateRoles(const char *Text, CharRole *Out, int , int N);
   bool allowMatch(int P, int W) const;
-  int skipPenalty(int W, Action Last) const;
-  int matchBonus(int P, int W, Action Last) const;
+  int missScore(int W, Action Last) const;
+  int matchScore(int P, int W, Action Last) const;
 
   // Pattern data is initialized by the constructor, then constant.
   char Pat[MaxPat]; // Pattern data
Index: clangd/FuzzyMatch.cpp
===
--- clangd/FuzzyMatch.cpp
+++ clangd/FuzzyMatch.cpp
@@ -58,6 +58,7 @@
 
 #include "FuzzyMatch.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 
 namespace clang {
@@ -67,7 +68,6 @@
 constexpr int FuzzyMatcher::MaxPat;
 constexpr int FuzzyMatcher::MaxWord;
 
-static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; }
 // A "negative infinity" score that won't overflow.
 // We use this to mark unreachable states and forbidden solutions.
 // Score field is 15 bits wide, min value is -2^14, we use half of that.
@@ -80,25 +80,18 @@
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I)
-LowPat[I] = lower(Pat[I]);
-  Scores[0][0][Miss] = {0, Miss};
-  Scores[0][0][Match] = {AwfulScore, Miss};
-  for (int P = 0; P <= PatN; ++P)
-for (int W = 0; W < P; ++W)
-  for (Action A : {Miss, Match})
-Scores[P][W][A] = {AwfulScore, Miss};
-  if (PatN > 0)
-calculateRoles(Pat, PatRole, PatTypeSet, PatN);
+LowPat[I] = toLower(Pat[I]);
+  calculateRoles(Pat, PatRole, PatTypeSet, PatN);
 }
 
 Optional FuzzyMatcher::match(StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
 return None;
-  if (!PatN)
-return 1;
   buildGraph();
-  auto Best = std::max(Scores[PatN][WordN][Miss].Score,
-   Scores[PatN][WordN][Match].Score);
+  // Find the optimal prefix of Word to match Pattern.
+  int Best = AwfulScore;
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
@@ -179,7 +172,8 @@
 }
 void FuzzyMatcher::calculateRoles(const char *Text, CharRole *Out, int ,
   int N) {
-  assert(N > 0);
+  if (!N)
+return;
   CharType Type = packedLookup(CharTypes, Text[0]);
   TypeSet = 1 << Type;
   // Types holds a sliding window of (Prev, Curr, Next) types.
@@ -206,10 +200,8 @@
   if (PatN > WordN)
 return false;
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;
   for (int I = 0; I < WordN; ++I)
-LowWord[I] = lower(Word[I]);
+LowWord[I] = toLower(Word[I]);
 
   // Cheap subsequence check.
   for (int W = 0, P = 0; P != PatN; ++W) {
@@ -236,31 +228,29 @@
 // This range is not strict: we can apply larger bonuses/penalties, or penalize
 // non-matched characters.
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {
-Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - skipPenalty(W, Miss),
+Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score + missScore(W, Miss),
   Miss};
 Scores[0][W + 1][Match] = {AwfulScore, Miss};
   }
   for (int P = 0; P < PatN; ++P) {
+Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
 for (int W = P; W < WordN; ++W) {
   auto  = Scores[P + 1][W + 1],  = Scores[P + 1][W];
 
-  auto MatchMissScore = PreMiss[Match].Score;
-  auto MissMissScore = PreMiss[Miss].Score;
-  if (P < PatN - 1) { // Skipping trailing characters is always free.
-MatchMissScore -= skipPenalty(W, Match);
-MissMissScore -= skipPenalty(W, Miss);
-  }
+  auto MatchMissScore = PreMiss[Match].Score + missScore(W, Match);
+  auto MissMissScore = PreMiss[Miss].Score + missScore(W, Miss);
   Score[Miss] = (MatchMissScore > MissMissScore)
 ? ScoreInfo{MatchMissScore, Match}
 : ScoreInfo{MissMissScore, Miss};
 
   if (!allowMatch(P, W)) {
 Score[Match] = {AwfulScore, Miss};
   } else {
 auto  = Scores[P][W];
-auto MatchMatchScore = PreMatch[Match].Score + matchBonus(P, W, Match);
-auto MissMatchScore = PreMatch[Miss].Score + matchBonus(P, 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 140265.
MaskRay edited the summary of this revision.
MaskRay added a comment.

Address comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720

Files:
  clangd/FuzzyMatch.cpp
  clangd/FuzzyMatch.h

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -58,8 +58,8 @@
   void buildGraph();
   void calculateRoles(const char *Text, CharRole *Out, int , int N);
   bool allowMatch(int P, int W) const;
-  int skipPenalty(int W, Action Last) const;
-  int matchBonus(int P, int W, Action Last) const;
+  int missScore(int W, Action Last) const;
+  int matchScore(int P, int W, Action Last) const;
 
   // Pattern data is initialized by the constructor, then constant.
   char Pat[MaxPat]; // Pattern data
Index: clangd/FuzzyMatch.cpp
===
--- clangd/FuzzyMatch.cpp
+++ clangd/FuzzyMatch.cpp
@@ -58,6 +58,7 @@
 
 #include "FuzzyMatch.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Format.h"
 
 namespace clang {
@@ -67,7 +68,6 @@
 constexpr int FuzzyMatcher::MaxPat;
 constexpr int FuzzyMatcher::MaxWord;
 
-static char lower(char C) { return C >= 'A' && C <= 'Z' ? C + ('a' - 'A') : C; }
 // A "negative infinity" score that won't overflow.
 // We use this to mark unreachable states and forbidden solutions.
 // Score field is 15 bits wide, min value is -2^14, we use half of that.
@@ -80,25 +80,17 @@
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
   std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I)
-LowPat[I] = lower(Pat[I]);
-  Scores[0][0][Miss] = {0, Miss};
-  Scores[0][0][Match] = {AwfulScore, Miss};
-  for (int P = 0; P <= PatN; ++P)
-for (int W = 0; W < P; ++W)
-  for (Action A : {Miss, Match})
-Scores[P][W][A] = {AwfulScore, Miss};
-  if (PatN > 0)
-calculateRoles(Pat, PatRole, PatTypeSet, PatN);
+LowPat[I] = toLower(Pat[I]);
+  calculateRoles(Pat, PatRole, PatTypeSet, PatN);
 }
 
 Optional FuzzyMatcher::match(StringRef Word) {
   if (!(WordContainsPattern = init(Word)))
 return None;
-  if (!PatN)
-return 1;
   buildGraph();
-  auto Best = std::max(Scores[PatN][WordN][Miss].Score,
-   Scores[PatN][WordN][Match].Score);
+  int Best = AwfulScore;
+  for (int I = PatN; I <= WordN; I++)
+Best = std::max(Best, Scores[PatN][I][Match].Score);
   if (isAwful(Best))
 return None;
   return ScoreScale * std::min(PerfectBonus * PatN, std::max(0, Best));
@@ -179,7 +171,8 @@
 }
 void FuzzyMatcher::calculateRoles(const char *Text, CharRole *Out, int ,
   int N) {
-  assert(N > 0);
+  if (!N)
+return;
   CharType Type = packedLookup(CharTypes, Text[0]);
   TypeSet = 1 << Type;
   // Types holds a sliding window of (Prev, Curr, Next) types.
@@ -206,10 +199,8 @@
   if (PatN > WordN)
 return false;
   std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
-  if (PatN == 0)
-return true;
   for (int I = 0; I < WordN; ++I)
-LowWord[I] = lower(Word[I]);
+LowWord[I] = toLower(Word[I]);
 
   // Cheap subsequence check.
   for (int W = 0, P = 0; P != PatN; ++W) {
@@ -236,31 +227,29 @@
 // This range is not strict: we can apply larger bonuses/penalties, or penalize
 // non-matched characters.
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {
-Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score - skipPenalty(W, Miss),
+Scores[0][W + 1][Miss] = {Scores[0][W][Miss].Score + missScore(W, Miss),
   Miss};
 Scores[0][W + 1][Match] = {AwfulScore, Miss};
   }
   for (int P = 0; P < PatN; ++P) {
+Scores[P + 1][P][Miss] = Scores[P + 1][P][Match] = {AwfulScore, Miss};
 for (int W = P; W < WordN; ++W) {
   auto  = Scores[P + 1][W + 1],  = Scores[P + 1][W];
 
-  auto MatchMissScore = PreMiss[Match].Score;
-  auto MissMissScore = PreMiss[Miss].Score;
-  if (P < PatN - 1) { // Skipping trailing characters is always free.
-MatchMissScore -= skipPenalty(W, Match);
-MissMissScore -= skipPenalty(W, Miss);
-  }
+  auto MatchMissScore = PreMiss[Match].Score + missScore(W, Match);
+  auto MissMissScore = PreMiss[Miss].Score + missScore(W, Miss);
   Score[Miss] = (MatchMissScore > MissMissScore)
 ? ScoreInfo{MatchMissScore, Match}
 : ScoreInfo{MissMissScore, Miss};
 
   if (!allowMatch(P, W)) {
 Score[Match] = {AwfulScore, Miss};
   } else {
 auto  = Scores[P][W];
-auto MatchMatchScore = PreMatch[Match].Score + matchBonus(P, W, Match);
-auto MissMatchScore = PreMatch[Miss].Score + matchBonus(P, W, Miss);
+auto MatchMatchScore = PreMatch[Match].Score 

[PATCH] D44720: [clangd] Simplify fuzzy matcher (sequence alignment) by removing some condition checks.

2018-03-29 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clangd/FuzzyMatch.cpp:230
 void FuzzyMatcher::buildGraph() {
+  Scores[0][0][Miss] = Scores[0][0][Match] = {0, Miss};
   for (int W = 0; W < WordN; ++W) {

sammccall wrote:
> why this change?
> this has also been moved from the cheaper constructor to the more expensive 
> per-match call. (also the diagonal assignment added in the next loop)
> 
> Also, shouldn't [0][0][Match] be AwfulScore?
> 
"The more expensive per-match call" is just two value assignments.

I have removed the expensive table initialization in the constructor.

[0][0][*] can be any value.



Comment at: clangd/FuzzyMatch.cpp:325
+  int W = PatN;
+  for (int I = PatN; ++I <= WordN; )
+if (Scores[PatN][I][Match].Score > Scores[PatN][W][Match].Score)

sammccall wrote:
> nit: I -> P, move increment to the increment expression of the for loop?
I -> P.

> move increment to the increment expression of the for loop?

Not sure about the coding standard here, but if you insist I'll have to change 
it as you are the reviewer. If the loop variable was an iterator, `for (It I = 
std::next(...); I != E; ++I)` would be uglier than `for (It I = ...; ++I != E; 
)`



Comment at: clangd/FuzzyMatch.cpp:340
+  A[WordN] = Miss;
+  for (int I = WordN, P = PatN; I > 0; I--) {
+if (I == W)

sammccall wrote:
> sammccall wrote:
> > sammccall wrote:
> > > W is the right name in this file for a variable iterating over word 
> > > indices, please don't change this.
> > > The new variable above could be EndW or so?
> > As far as I can see, this loop is setting `A[W+1:...] = Miss` and 
> > populating `A[0...W]` with the exsting logic.
> > I think this would be clearer as two loops, currently there's a lot of 
> > conditionals around Last that obscure what's actually happening.
> You've shifted P (and the old W, new I) by 1. This does reduce the number of 
> +1 and -1 in this function, but it's inconsistent with how these are used 
> elsewhere: P should be the index into Pat of the character that we're 
> considering.
I don't understand the rationale not to use the shifted indices. The code 
actually use `Scores[P][W][*]` to mean the optimal match of the first `P` 
characters of the pattern with the first `W` characters of the word, not the 
position of the character.

On the other hand, C++ reverse iterators use the shifted one for `for (I = 
rend(); I != rbegin(); ++I)`. The shifted one makes ending condition check 
easier.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44720



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


  1   2   >