[PATCH] D47616: [CFG] [analyzer] Explain copy elision through construction contexts.

2018-06-12 Thread Henry Wong via Phabricator via cfe-commits
MTC added inline comments.
Herald added a subscriber: mikhail.ramalho.



Comment at: include/clang/Analysis/ConstructionContext.h:351
+
+  explicit SimpleTemporaryObjectConstructionContext(
+  const CXXBindTemporaryExpr *BTE, const MaterializeTemporaryExpr *MTE)

MTC wrote:
> `explicit` useless?
I'm wrong here, maybe there is some use of 
`SimpleTemporaryObjectConstructionContext({ , })`, sorry to bother!



Comment at: include/clang/Analysis/ConstructionContext.h:377
+
+  explicit ElidedTemporaryObjectConstructionContext(
+  const CXXBindTemporaryExpr *BTE, const MaterializeTemporaryExpr *MTE,

MTC wrote:
> Same useless here?
Also I'm wrong here!


https://reviews.llvm.org/D47616



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


[libcxx] r334477 - [CMake] Use common variable for all header targets NFC

2018-06-12 Thread Petr Hosek via cfe-commits
Author: phosek
Date: Mon Jun 11 23:58:06 2018
New Revision: 334477

URL: http://llvm.org/viewvc/llvm-project?rev=334477&view=rev
Log:
[CMake] Use common variable for all header targets NFC

This simplifies the handling of header targets.

Modified:
libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake
libcxx/trunk/include/CMakeLists.txt
libcxx/trunk/lib/CMakeLists.txt

Modified: libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake?rev=334477&r1=334476&r2=334477&view=diff
==
--- libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake (original)
+++ libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake Mon Jun 11 23:58:06 2018
@@ -78,8 +78,8 @@ macro(setup_abi_lib abidefines abilib ab
   endforeach()
 
   include_directories("${LIBCXX_BINARY_INCLUDE_DIR}")
-  add_custom_target(cxx-abi-headers ALL DEPENDS ${abilib_headers})
-  set(LIBCXX_ABI_HEADERS_TARGET cxx-abi-headers)
+  add_custom_target(cxx_abi_headers ALL DEPENDS ${abilib_headers})
+  set(LIBCXX_CXX_ABI_HEADER_TARGET "cxx_abi_headers")
 endmacro()
 
 

Modified: libcxx/trunk/include/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/CMakeLists.txt?rev=334477&r1=334476&r2=334477&view=diff
==
--- libcxx/trunk/include/CMakeLists.txt (original)
+++ libcxx/trunk/include/CMakeLists.txt Mon Jun 11 23:58:06 2018
@@ -228,11 +228,11 @@ if(NOT LIBCXX_USING_INSTALLED_LLVM AND L
 list(APPEND out_files ${dst})
   endif()
 
-  add_custom_target(cxx-headers ALL DEPENDS ${out_files} 
${LIBCXX_CXX_ABI_LIBRARY_HEADERS})
+  add_custom_target(cxx_headers ALL DEPENDS ${out_files} 
${LIBCXX_CXX_ABI_HEADER_TARGET})
 else()
-  add_custom_target(cxx-headers)
+  add_custom_target(cxx_headers)
 endif()
-set_target_properties(cxx-headers PROPERTIES FOLDER "Misc")
+set_target_properties(cxx_headers PROPERTIES FOLDER "Misc")
 
 if (LIBCXX_INSTALL_HEADERS)
   foreach(file ${files})

Modified: libcxx/trunk/lib/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/lib/CMakeLists.txt?rev=334477&r1=334476&r2=334477&view=diff
==
--- libcxx/trunk/lib/CMakeLists.txt (original)
+++ libcxx/trunk/lib/CMakeLists.txt Mon Jun 11 23:58:06 2018
@@ -189,8 +189,8 @@ split_list(LIBCXX_LINK_FLAGS)
 
 # Add an object library that contains the compiled source files.
 add_library(cxx_objects OBJECT ${exclude_from_all} ${LIBCXX_SOURCES} 
${LIBCXX_HEADERS})
-if(LIBCXX_CXX_ABI_LIBRARY_HEADERS)
-  add_dependencies(cxx_objects ${LIBCXX_CXX_ABI_LIBRARY_HEADERS})
+if(LIBCXX_CXX_ABI_HEADER_TARGET)
+  add_dependencies(cxx_objects ${LIBCXX_CXX_ABI_HEADER_TARGET})
 endif()
 if(WIN32 AND NOT MINGW)
   target_compile_definitions(cxx_objects
@@ -286,8 +286,7 @@ if (LIBCXX_ENABLE_STATIC)
 endif()
 
 # Add a meta-target for both libraries.
-add_custom_target(cxx DEPENDS ${LIBCXX_TARGETS})
-add_dependencies(cxx cxx-headers ${LIBCXX_ABI_HEADERS_TARGET})
+add_custom_target(cxx DEPENDS cxx_headers ${LIBCXX_TARGETS})
 
 if (LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY)
   file(GLOB LIBCXX_EXPERIMENTAL_SOURCES ../src/experimental/*.cpp)


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


[PATCH] D45532: [StaticAnalyzer] Checker to find uninitialized fields after a constructor call

2018-06-12 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 150899.
Szelethus added a comment.

Polite ping :)

This diff fixed a minor issue in FieldChainInfo's constructor.


https://reviews.llvm.org/D45532

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
  test/Analysis/Inputs/system-header-simulator-for-cxx-uninitialized-object.h
  test/Analysis/cxx-uninitialized-object-inheritance.cpp
  test/Analysis/cxx-uninitialized-object-ptr-ref.cpp
  test/Analysis/cxx-uninitialized-object.cpp

Index: test/Analysis/cxx-uninitialized-object.cpp
===
--- /dev/null
+++ test/Analysis/cxx-uninitialized-object.cpp
@@ -0,0 +1,1058 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.cplusplus.UninitializedObject -analyzer-config alpha.cplusplus.UninitializedObject:Pedantic=true -std=c++11 -DPEDANTIC -verify %s
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.cplusplus.UninitializedObject -std=c++11 -verify %s
+
+//===--===//
+// Default constructor test.
+//===--===//
+
+class CompilerGeneratedConstructorTest {
+  int a, b, c, d, e, f, g, h, i, j;
+
+public:
+  CompilerGeneratedConstructorTest() = default;
+};
+
+void fCompilerGeneratedConstructorTest() {
+  CompilerGeneratedConstructorTest();
+}
+
+#ifdef PEDANTIC
+class DefaultConstructorTest {
+  int a; // expected-note{{uninitialized field 'this->a'}}
+
+public:
+  DefaultConstructorTest();
+};
+
+DefaultConstructorTest::DefaultConstructorTest() = default;
+
+void fDefaultConstructorTest() {
+  DefaultConstructorTest(); // expected-warning{{1 uninitialized field}}
+}
+#else
+class DefaultConstructorTest {
+  int a;
+
+public:
+  DefaultConstructorTest();
+};
+
+DefaultConstructorTest::DefaultConstructorTest() = default;
+
+void fDefaultConstructorTest() {
+  DefaultConstructorTest();
+}
+#endif // PEDANTIC
+
+//===--===//
+// Initializer list test.
+//===--===//
+
+class InitListTest1 {
+  int a;
+  int b;
+
+public:
+  InitListTest1()
+  : a(1),
+b(2) {
+// All good!
+  }
+};
+
+void fInitListTest1() {
+  InitListTest1();
+}
+
+class InitListTest2 {
+  int a;
+  int b; // expected-note{{uninitialized field 'this->b'}}
+
+public:
+  InitListTest2()
+  : a(3) {} // expected-warning{{1 uninitialized field}}
+};
+
+void fInitListTest2() {
+  InitListTest2();
+}
+
+class InitListTest3 {
+  int a; // expected-note{{uninitialized field 'this->a'}}
+  int b;
+
+public:
+  InitListTest3()
+  : b(4) {} // expected-warning{{1 uninitialized field}}
+};
+
+void fInitListTest3() {
+  InitListTest3();
+}
+
+//===--===//
+// Constructor body test.
+//===--===//
+
+class CtorBodyTest1 {
+  int a, b;
+
+public:
+  CtorBodyTest1() {
+a = 5;
+b = 6;
+// All good!
+  }
+};
+
+void fCtorBodyTest1() {
+  CtorBodyTest1();
+}
+
+class CtorBodyTest2 {
+  int a;
+  int b; // expected-note{{uninitialized field 'this->b'}}
+
+public:
+  CtorBodyTest2() {
+a = 7; // expected-warning{{1 uninitialized field}}
+  }
+};
+
+void fCtorBodyTest2() {
+  CtorBodyTest2();
+}
+
+class CtorBodyTest3 {
+  int a; // expected-note{{uninitialized field 'this->a'}}
+  int b;
+
+public:
+  CtorBodyTest3() {
+b = 8; // expected-warning{{1 uninitialized field}}
+  }
+};
+
+void fCtorBodyTest3() {
+  CtorBodyTest3();
+}
+
+#ifdef PEDANTIC
+class CtorBodyTest4 {
+  int a; // expected-note{{uninitialized field 'this->a'}}
+  int b; // expected-note{{uninitialized field 'this->b'}}
+
+public:
+  CtorBodyTest4() {}
+};
+
+void fCtorBodyTest4() {
+  CtorBodyTest4(); // expected-warning{{2 uninitialized fields}}
+}
+#else
+class CtorBodyTest4 {
+  int a;
+  int b;
+
+public:
+  CtorBodyTest4() {}
+};
+
+void fCtorBodyTest4() {
+  CtorBodyTest4();
+}
+#endif
+
+//===--===//
+// Constructor delegation test.
+//===--===//
+
+class CtorDelegationTest1 {
+  int a;
+  int b;
+
+public:
+  CtorDelegationTest1(int)
+  : a(9) {
+// leaves 'b' unintialized, but we'll never check this function
+  }
+
+  CtorDelegationTest1()
+  : CtorDelegationTest1(int{}) { // Initializing 'a'
+b = 10;
+// All good!
+  }
+};
+
+void fCtorDelegationTest1() {
+  CtorDelegationTest1();
+}
+
+class CtorDelegationTest2 {
+  int a; // expected-note{{uninitialized field 'this->a'}}
+  int b;
+
+public:
+  CtorDelegationTest2(int)
+  : b(11) {
+// leaves 'a' unintialized, but we

[PATCH] D48063: [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
Herald added a subscriber: cfe-commits.

This is an alternative to https://reviews.llvm.org/D48034.


Repository:
  rC Clang

https://reviews.llvm.org/D48063

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestTextProto.cpp


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -485,8 +485,15 @@
   verifyFormat("keys: []");
   verifyFormat("keys: [ 1 ]");
   verifyFormat("keys: [ 'ala', 'bala' ]");
-  verifyFormat("keys:\n"
-   "[ 'ala', 'bala', 'porto', 'kala', 'too', 'long', 'ng' ]");
+  verifyFormat("keys: [\n"
+   "  'ala',\n"
+   "  'bala',\n"
+   "  'porto',\n"
+   "  'kala',\n"
+   "  'too',\n"
+   "  'long',\n"
+   "  'ng'\n"
+   "]");
   verifyFormat("key: item\n"
"keys: [\n"
"  'ala',\n"
@@ -670,5 +677,23 @@
"}");
 }
 
+TEST_F(FormatTestTextProto, TODO) {
+  verifyFormat("submessage: {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage: <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage: [\n"
+   "  'ey'\n"
+   "]");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -3101,10 +3101,16 @@
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
-  return false;
+if (Style.Language == FormatStyle::LK_Proto ||
+ Style.Language == FormatStyle::LK_TextProto) {
+  if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+return false;
+  if ((Right.is(tok::l_brace) || Right.is(tok::less)) &&
+  Right.is(TT_DictLiteral))
+return false;
+  if (Right.is(TT_ArrayInitializerLSquare))
+return false;
+}
 return true;
   }
   if (Right.is(tok::r_square) && Right.MatchingParen &&


Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -485,8 +485,15 @@
   verifyFormat("keys: []");
   verifyFormat("keys: [ 1 ]");
   verifyFormat("keys: [ 'ala', 'bala' ]");
-  verifyFormat("keys:\n"
-   "[ 'ala', 'bala', 'porto', 'kala', 'too', 'long', 'ng' ]");
+  verifyFormat("keys: [\n"
+   "  'ala',\n"
+   "  'bala',\n"
+   "  'porto',\n"
+   "  'kala',\n"
+   "  'too',\n"
+   "  'long',\n"
+   "  'ng'\n"
+   "]");
   verifyFormat("key: item\n"
"keys: [\n"
"  'ala',\n"
@@ -670,5 +677,23 @@
"}");
 }
 
+TEST_F(FormatTestTextProto, TODO) {
+  verifyFormat("submessage: {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage: <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage: [\n"
+   "  'ey'\n"
+   "]");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -3101,10 +3101,16 @@
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBr

[clang-tools-extra] r334485 - [clangd] Support proximity paths in index fuzzy find.

2018-06-12 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Tue Jun 12 01:48:20 2018
New Revision: 334485

URL: http://llvm.org/viewvc/llvm-project?rev=334485&view=rev
Log:
[clangd] Support proximity paths in index fuzzy find.

Reviewers: sammccall

Subscribers: ilya-biryukov, MaskRay, jkorous, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/index/Index.h

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=334485&r1=334484&r2=334485&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Tue Jun 12 01:48:20 2018
@@ -928,6 +928,7 @@ private:
 Req.RestrictForCodeCompletion = true;
 Req.Scopes = getQueryScopes(Recorder->CCContext,
 Recorder->CCSema->getSourceManager());
+Req.ProximityPaths.push_back(FileName);
 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
   Req.Query,
   llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=334485&r1=334484&r2=334485&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Tue Jun 12 01:48:20 2018
@@ -271,6 +271,9 @@ struct FuzzyFindRequest {
   size_t MaxCandidateCount = UINT_MAX;
   /// If set to true, only symbols for completion support will be considered.
   bool RestrictForCodeCompletion = false;
+  /// Contextually relevant files (e.g. the file we're code-completing in).
+  /// Paths should be absolute.
+  std::vector ProximityPaths;
 };
 
 struct LookupRequest {


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


[PATCH] D47937: [clangd] Support proximity paths in index fuzzy find.

2018-06-12 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL334485: [clangd] Support proximity paths in index fuzzy 
find. (authored by ioeric, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D47937

Files:
  clang-tools-extra/trunk/clangd/CodeComplete.cpp
  clang-tools-extra/trunk/clangd/index/Index.h


Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp
===
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp
@@ -928,6 +928,7 @@
 Req.RestrictForCodeCompletion = true;
 Req.Scopes = getQueryScopes(Recorder->CCContext,
 Recorder->CCSema->getSourceManager());
+Req.ProximityPaths.push_back(FileName);
 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
   Req.Query,
   llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Index: clang-tools-extra/trunk/clangd/index/Index.h
===
--- clang-tools-extra/trunk/clangd/index/Index.h
+++ clang-tools-extra/trunk/clangd/index/Index.h
@@ -271,6 +271,9 @@
   size_t MaxCandidateCount = UINT_MAX;
   /// If set to true, only symbols for completion support will be considered.
   bool RestrictForCodeCompletion = false;
+  /// Contextually relevant files (e.g. the file we're code-completing in).
+  /// Paths should be absolute.
+  std::vector ProximityPaths;
 };
 
 struct LookupRequest {


Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp
===
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp
@@ -928,6 +928,7 @@
 Req.RestrictForCodeCompletion = true;
 Req.Scopes = getQueryScopes(Recorder->CCContext,
 Recorder->CCSema->getSourceManager());
+Req.ProximityPaths.push_back(FileName);
 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
   Req.Query,
   llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Index: clang-tools-extra/trunk/clangd/index/Index.h
===
--- clang-tools-extra/trunk/clangd/index/Index.h
+++ clang-tools-extra/trunk/clangd/index/Index.h
@@ -271,6 +271,9 @@
   size_t MaxCandidateCount = UINT_MAX;
   /// If set to true, only symbols for completion support will be considered.
   bool RestrictForCodeCompletion = false;
+  /// Contextually relevant files (e.g. the file we're code-completing in).
+  /// Paths should be absolute.
+  std::vector ProximityPaths;
 };
 
 struct LookupRequest {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46024: [clang-format] Add SpaceBeforeCpp11BracedList option.

2018-06-12 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In https://reviews.llvm.org/D46024#1121242, @rkirsling wrote:

> FWIW, please note that this space-before-brace style is not specific to 
> WebKit; CppCoreGuidelines exhibits it as well:
>  
> http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es23-prefer-the--initializer-syntax


This and WebKit's style seem like compelling arguments to support this option.

klimek, djasper: Do you have any objections against landing this?


Repository:
  rC Clang

https://reviews.llvm.org/D46024



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


[PATCH] D47829: [Driver] Accept the -fno-shrink-wrap option for GCC compatibility

2018-06-12 Thread Simon Dardis via Phabricator via cfe-commits
sdardis updated this revision to Diff 150904.
sdardis added a comment.

Modify implementation to produce a function attribute.


Repository:
  rC Clang

https://reviews.llvm.org/D47829

Files:
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  lib/CodeGen/CodeGenFunction.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGen/noshrinkwrapping.c


Index: test/CodeGen/noshrinkwrapping.c
===
--- /dev/null
+++ test/CodeGen/noshrinkwrapping.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -S -fno-shrink-wrapping %s -emit-llvm -o - | FileCheck %s
+
+// CHECK-LABEL: main
+// CHECK: attributes #0 = {{.*}}"no-shrink-wrapping"="true"{{.*}}
+
+int main() {
+  return 0;
+}
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -743,6 +743,8 @@
 
   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
 
+  Opts.NoShrinkWrap = Args.hasArg(OPT_fno_shrink_wrap);
+
   Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
 
   Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -4054,6 +4054,9 @@
 
   Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
 
+  if (Args.hasArg(options::OPT_fno_shrink_wrap))
+CmdArgs.push_back("-fno-shrink-wrap");
+
   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
   if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
Index: lib/CodeGen/CodeGenFunction.cpp
===
--- lib/CodeGen/CodeGenFunction.cpp
+++ lib/CodeGen/CodeGenFunction.cpp
@@ -935,6 +935,11 @@
 }
   }
 
+  // Add no-shrink-wrap value.
+  if (CGM.getCodeGenOpts().NoShrinkWrap)
+Fn->addFnAttr("no-shrink-wrap",
+  llvm::toStringRef(CGM.getCodeGenOpts().NoShrinkWrap));
+
   // Add no-jump-tables value.
   Fn->addFnAttr("no-jump-tables",
 llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
Index: include/clang/Frontend/CodeGenOptions.def
===
--- include/clang/Frontend/CodeGenOptions.def
+++ include/clang/Frontend/CodeGenOptions.def
@@ -216,6 +216,7 @@
 CODEGENOPT(TimePasses, 1, 0) ///< Set when -ftime-report is enabled.
 CODEGENOPT(UnrollLoops   , 1, 0) ///< Control whether loops are unrolled.
 CODEGENOPT(RerollLoops   , 1, 0) ///< Control whether loops are rerolled.
+CODEGENOPT(NoShrinkWrap  , 1, 0) ///< Set when -fno-shrink-wrap is enabled.
 CODEGENOPT(NoUseJumpTables   , 1, 0) ///< Set when -fno-jump-tables is enabled.
 CODEGENOPT(UnsafeFPMath  , 1, 0) ///< Allow unsafe floating point optzns.
 CODEGENOPT(UnwindTables  , 1, 0) ///< Emit unwind tables.
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -1393,6 +1393,8 @@
   HelpText<"Do not include column number on diagnostics">;
 def fno_show_source_location : Flag<["-"], "fno-show-source-location">, 
Group,
   Flags<[CC1Option]>, HelpText<"Do not include source location information 
with diagnostics">;
+def fno_shrink_wrap : Flag<["-"], "fno-shrink-wrap">, Group,
+  Flags<[CC1Option]>, HelpText<"Disable shrink wrapping">;
 def fdiagnostics_absolute_paths : Flag<["-"], "fdiagnostics-absolute-paths">, 
Group,
   Flags<[CC1Option, CoreOption]>, HelpText<"Print absolute paths in 
diagnostics">;
 def fno_spell_checking : Flag<["-"], "fno-spell-checking">, Group,


Index: test/CodeGen/noshrinkwrapping.c
===
--- /dev/null
+++ test/CodeGen/noshrinkwrapping.c
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -S -fno-shrink-wrapping %s -emit-llvm -o - | FileCheck %s
+
+// CHECK-LABEL: main
+// CHECK: attributes #0 = {{.*}}"no-shrink-wrapping"="true"{{.*}}
+
+int main() {
+  return 0;
+}
Index: lib/Frontend/CompilerInvocation.cpp
===
--- lib/Frontend/CompilerInvocation.cpp
+++ lib/Frontend/CompilerInvocation.cpp
@@ -743,6 +743,8 @@
 
   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
 
+  Opts.NoShrinkWrap = Args.hasArg(OPT_fno_shrink_wrap);
+
   Opts.NoUseJumpTables = Args.hasArg(OPT_fno_jump_tables);
 
   Opts.ProfileSampleAccurate = Args.hasArg(OPT_fprofile_sample_accurate);
Index: lib/Driver/ToolChains/Clang.cpp
===
--- lib/Driver/ToolChains/Clang.cpp
+++ lib/Driver/ToolChains/Clang.cpp
@@ -4054,6 +4054,9 @@

[PATCH] D47946: [ASTmporter] Fix infinite recursion on function import with struct definition in parameters

2018-06-12 Thread Zoltán Gera via Phabricator via cfe-commits
gerazo added a comment.

In https://reviews.llvm.org/D47946#1127679, @balazske wrote:

> Problem: This change interferes with https://reviews.llvm.org/D47445. 
> Probably that should be committed, it is approved already.


Ok. I'll wait for the other thing to be committed and I will rework this 
immediately. Thanks for telling.


Repository:
  rC Clang

https://reviews.llvm.org/D47946



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


r334489 - [AArch64] Corrected FP16 Intrinsic range checks in Clang + added Sema tests

2018-06-12 Thread Luke Geeson via cfe-commits
Author: lukegeeson
Date: Tue Jun 12 02:54:27 2018
New Revision: 334489

URL: http://llvm.org/viewvc/llvm-project?rev=334489&view=rev
Log:
[AArch64] Corrected FP16 Intrinsic range checks in Clang + added Sema tests

Summary:
This fixes the ranges for the vcvth family of FP16 intrinsics in the clang 
front end. Previously it was accepting incorrect ranges
-Changed builtin range checking in SemaChecking
-added tests SemaCheck changes - included in  their own file since no similar 
one exists
-modified existing tests to reflect new ranges

Reviewers: SjoerdMeijer, javed.absar

Reviewed By: SjoerdMeijer

Subscribers: kristof.beyls, cfe-commits

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

Added:
cfe/trunk/test/Sema/aarch64-neon-fp16-ranges.c
Modified:
cfe/trunk/include/clang/Basic/arm_fp16.td
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c
cfe/trunk/utils/TableGen/NeonEmitter.cpp

Modified: cfe/trunk/include/clang/Basic/arm_fp16.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/arm_fp16.td?rev=334489&r1=334488&r2=334489&view=diff
==
--- cfe/trunk/include/clang/Basic/arm_fp16.td (original)
+++ cfe/trunk/include/clang/Basic/arm_fp16.td Tue Jun 12 02:54:27 2018
@@ -75,15 +75,15 @@ let ArchGuard = "defined(__ARM_FEATURE_F
   def SCALAR_FCVTPUH  : SInst<"vcvtp_u16", "bs", "Sh">;
   def SCALAR_FCVTPUH1 : SInst<"vcvtp_u32", "Us", "Sh">;
   def SCALAR_FCVTPUH2 : SInst<"vcvtp_u64", "Os", "Sh">;
-
-  def SCALAR_SCVTFSHO : SInst<"vcvth_n_f16", "Ysi", "silUsUiUl">;
-  def SCALAR_FCVTZSHO : SInst<"vcvt_n_s16", "$si", "Sh">;
-  def SCALAR_FCVTZSH1O: SInst<"vcvt_n_s32", "Isi", "Sh">;
-  def SCALAR_FCVTZSH2O: SInst<"vcvt_n_s64", "Lsi", "Sh">;
-  def SCALAR_FCVTZUHO : SInst<"vcvt_n_u16", "bsi", "Sh">;
-  def SCALAR_FCVTZUH1O: SInst<"vcvt_n_u32", "Usi", "Sh">;
-  def SCALAR_FCVTZUH2O: SInst<"vcvt_n_u64", "Osi", "Sh">;
-
+  let isVCVT_N = 1 in {
+def SCALAR_SCVTFSHO : SInst<"vcvth_n_f16", "Ysi", "silUsUiUl">;
+def SCALAR_FCVTZSHO : SInst<"vcvt_n_s16", "$si", "Sh">;
+def SCALAR_FCVTZSH1O: SInst<"vcvt_n_s32", "Isi", "Sh">;
+def SCALAR_FCVTZSH2O: SInst<"vcvt_n_s64", "Lsi", "Sh">;
+def SCALAR_FCVTZUHO : SInst<"vcvt_n_u16", "bsi", "Sh">;
+def SCALAR_FCVTZUH1O: SInst<"vcvt_n_u32", "Usi", "Sh">;
+def SCALAR_FCVTZUH2O: SInst<"vcvt_n_u64", "Osi", "Sh">;
+  }
   // Comparison
   def SCALAR_CMEQRH   : SInst<"vceq", "bss", "Sh">;
   def SCALAR_CMEQZH   : SInst<"vceqz", "bs", "Sh">;

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=334489&r1=334488&r2=334489&view=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Tue Jun 12 02:54:27 2018
@@ -1499,10 +1499,10 @@ bool Sema::CheckNeonBuiltinFunctionCall(
   switch (BuiltinID) {
   default:
 return false;
-#define GET_NEON_IMMEDIATE_CHECK
-#include "clang/Basic/arm_neon.inc"
-#include "clang/Basic/arm_fp16.inc"
-#undef GET_NEON_IMMEDIATE_CHECK
+  #define GET_NEON_IMMEDIATE_CHECK
+  #include "clang/Basic/arm_neon.inc"
+  #include "clang/Basic/arm_fp16.inc"
+  #undef GET_NEON_IMMEDIATE_CHECK
   }
 
   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);

Modified: cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c?rev=334489&r1=334488&r2=334489&view=diff
==
--- cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c (original)
+++ cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c Tue Jun 12 02:54:27 
2018
@@ -486,90 +486,90 @@ uint16_t test_vclth_f16(float16_t a, flo
 
 // CHECK-LABEL: test_vcvth_n_f16_s16
 // CHECK: [[SEXT:%.*]] = sext i16 %a to i32
-// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i32(i32 
[[SEXT]], i32 0)
+// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i32(i32 
[[SEXT]], i32 1)
 // CHECK:  ret half [[CVT]]
 float16_t test_vcvth_n_f16_s16(int16_t a) {
-  return vcvth_n_f16_s16(a, 0);
+  return vcvth_n_f16_s16(a, 1);
 }
 
 // CHECK-LABEL: test_vcvth_n_f16_s32
-// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i32(i32 
%a, i32 0)
+// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i32(i32 
%a, i32 1)
 // CHECK:  ret half [[CVT]]
 float16_t test_vcvth_n_f16_s32(int32_t a) {
-  return vcvth_n_f16_s32(a, 0);
+  return vcvth_n_f16_s32(a, 1);
 }
 
 // CHECK-LABEL: test_vcvth_n_f16_s64
-// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i64(i64 
%a, i32 0)
+// CHECK:  [[CVT:%.*]] = call half @llvm.aarch64.neon.vcvtfxs2fp.f16.i64(i64 
%a, i32 1)
 // CHECK:  ret half [[CVT]]
 float16_t test_vcvth_n_f16_s64(int

[PATCH] D47592: [AArch64] Corrected FP16 Intrinsic range checks in Clang + added Sema tests

2018-06-12 Thread Luke Geeson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
LukeGeeson marked an inline comment as done.
Closed by commit rL334489: [AArch64] Corrected FP16 Intrinsic range checks in 
Clang + added Sema tests (authored by LukeGeeson, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D47592?vs=149737&id=150912#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D47592

Files:
  cfe/trunk/include/clang/Basic/arm_fp16.td
  cfe/trunk/lib/Sema/SemaChecking.cpp
  cfe/trunk/test/CodeGen/aarch64-v8.2a-fp16-intrinsics.c
  cfe/trunk/test/Sema/aarch64-neon-fp16-ranges.c
  cfe/trunk/utils/TableGen/NeonEmitter.cpp

Index: cfe/trunk/utils/TableGen/NeonEmitter.cpp
===
--- cfe/trunk/utils/TableGen/NeonEmitter.cpp
+++ cfe/trunk/utils/TableGen/NeonEmitter.cpp
@@ -2162,8 +2162,7 @@
   OS << "#endif\n\n";
 }
 
-void
-NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
+void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
 SmallVectorImpl &Defs) {
   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
 
@@ -2188,11 +2187,15 @@
 Record *R = Def->getRecord();
 if (R->getValueAsBit("isVCVT_N")) {
   // VCVT between floating- and fixed-point values takes an immediate
-  // in the range [1, 32) for f32 or [1, 64) for f64.
+  // in the range [1, 32) for f32 or [1, 64) for f64 or [1, 16) for f16.
   LowerBound = "1";
-  if (Def->getBaseType().getElementSizeInBits() == 32)
+	  if (Def->getBaseType().getElementSizeInBits() == 16 ||
+		  Def->getName().find('h') != std::string::npos)
+		// VCVTh operating on FP16 intrinsics in range [1, 16)
+		UpperBound = "15";
+	  else if (Def->getBaseType().getElementSizeInBits() == 32)
 UpperBound = "31";
-  else
+	  else
 UpperBound = "63";
 } else if (R->getValueAsBit("isScalarShift")) {
   // Right shifts have an 'r' in the name, left shifts do not. Convert
Index: cfe/trunk/include/clang/Basic/arm_fp16.td
===
--- cfe/trunk/include/clang/Basic/arm_fp16.td
+++ cfe/trunk/include/clang/Basic/arm_fp16.td
@@ -75,15 +75,15 @@
   def SCALAR_FCVTPUH  : SInst<"vcvtp_u16", "bs", "Sh">;
   def SCALAR_FCVTPUH1 : SInst<"vcvtp_u32", "Us", "Sh">;
   def SCALAR_FCVTPUH2 : SInst<"vcvtp_u64", "Os", "Sh">;
-
-  def SCALAR_SCVTFSHO : SInst<"vcvth_n_f16", "Ysi", "silUsUiUl">;
-  def SCALAR_FCVTZSHO : SInst<"vcvt_n_s16", "$si", "Sh">;
-  def SCALAR_FCVTZSH1O: SInst<"vcvt_n_s32", "Isi", "Sh">;
-  def SCALAR_FCVTZSH2O: SInst<"vcvt_n_s64", "Lsi", "Sh">;
-  def SCALAR_FCVTZUHO : SInst<"vcvt_n_u16", "bsi", "Sh">;
-  def SCALAR_FCVTZUH1O: SInst<"vcvt_n_u32", "Usi", "Sh">;
-  def SCALAR_FCVTZUH2O: SInst<"vcvt_n_u64", "Osi", "Sh">;
-
+  let isVCVT_N = 1 in {
+def SCALAR_SCVTFSHO : SInst<"vcvth_n_f16", "Ysi", "silUsUiUl">;
+def SCALAR_FCVTZSHO : SInst<"vcvt_n_s16", "$si", "Sh">;
+def SCALAR_FCVTZSH1O: SInst<"vcvt_n_s32", "Isi", "Sh">;
+def SCALAR_FCVTZSH2O: SInst<"vcvt_n_s64", "Lsi", "Sh">;
+def SCALAR_FCVTZUHO : SInst<"vcvt_n_u16", "bsi", "Sh">;
+def SCALAR_FCVTZUH1O: SInst<"vcvt_n_u32", "Usi", "Sh">;
+def SCALAR_FCVTZUH2O: SInst<"vcvt_n_u64", "Osi", "Sh">;
+  }
   // Comparison
   def SCALAR_CMEQRH   : SInst<"vceq", "bss", "Sh">;
   def SCALAR_CMEQZH   : SInst<"vceqz", "bs", "Sh">;
Index: cfe/trunk/test/Sema/aarch64-neon-fp16-ranges.c
===
--- cfe/trunk/test/Sema/aarch64-neon-fp16-ranges.c
+++ cfe/trunk/test/Sema/aarch64-neon-fp16-ranges.c
@@ -0,0 +1,64 @@
+// RUN: %clang_cc1 -triple arm64-linux-gnu -fallow-half-arguments-and-returns -target-feature +neon -target-feature +fullfp16 -ffreestanding -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -fallow-half-arguments-and-returns -target-feature +fullfp16 -target-feature +neon -ffreestanding -fsyntax-only -verify %s
+
+#include 
+#include 
+
+void test_vcvt_f16_16(int16_t a){
+  vcvth_n_f16_s16(a, 1);
+  vcvth_n_f16_s16(a, 16);
+  vcvth_n_f16_s16(a, 0);  // expected-error {{argument should be a value from 1 to 16}}
+  vcvth_n_f16_s16(a, 17); // expected-error {{argument should be a value from 1 to 16}}
+
+  vcvth_n_f16_u16(a, 1);
+  vcvth_n_f16_u16(a, 16);
+  vcvth_n_f16_u16(a, 0);  // expected-error {{argument should be a value from 1 to 16}}
+  vcvth_n_f16_u16(a, 17); // expected-error {{argument should be a value from 1 to 16}}
+}
+
+void test_vcvt_f16_32(int32_t a){
+  vcvth_n_f16_u32(a, 1);
+  vcvth_n_f16_u32(a, 16);
+  vcvth_n_f16_u32(a, 0);  // expected-error {{argument should be a value from 1 to 16}}
+  vcvth_n_f16_u32(a, 17); // expected-error {{argument should be a value from 1 to 16}}
+
+  vcvth_n_f16_s32(a, 1);
+  vcvth_n_f16_s32(a, 16);
+  vcvth_n_f16_s32(a, 0);  // expected-error {{argument should be a value from 1 to 16}}
+  vcvth_n_f16_s32(a, 17); 

[PATCH] D48068: [clangd] Move caching of compile args out of ClangdServer.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: jkorous, MaskRay, ioeric, mgorny.

Caching is now handled by ClangdLSPServer and hidden behind the
GlobalCompilationDatabase interface. This simplifies ClangdServer.

No behavioral changes are intended, the clangd binary still caches the
compile commands on the first read.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48068

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/CompileArgsCache.cpp
  clangd/CompileArgsCache.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -20,8 +20,7 @@
 
 // Calls addDocument and then blockUntilIdleForTest.
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags = WantDiagnostics::Auto,
-bool SkipCache = false);
+WantDiagnostics WantDiags = WantDiagnostics::Auto);
 
 llvm::Expected
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -12,8 +12,8 @@
 namespace clangd {
 
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags, bool SkipCache) {
-  Server.addDocument(File, Contents, WantDiags, SkipCache);
+WantDiagnostics WantDiags) {
+  Server.addDocument(File, Contents, WantDiags);
   if (!Server.blockUntilIdleForTest())
 llvm_unreachable("not idle after addDocument");
 }
Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -390,16 +390,7 @@
 
   // Now switch to C++ mode.
   CDB.ExtraClangFlags = {"-xc++"};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents1);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  runAddDocument(Server, FooCpp, SourceContents2);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto);
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument calls should finish without errors too.
   runAddDocument(Server, FooCpp, SourceContents1);
@@ -431,14 +422,7 @@
 
   // Parse without the define, no errors should be produced.
   CDB.ExtraClangFlags = {};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument call should finish without errors too.
@@ -500,10 +484,8 @@
   CDB.ExtraClangFlags.clear();
   DiagConsumer.clear();
   Server.removeDocument(BazCpp);
-  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
-  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto);
+  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
 
   EXPECT_THAT(DiagConsumer.filesWithDiags(),
@@ -708,7 +690,7 @@
   Server.addDocument(FilePaths[FileIndex],
  ShouldHaveErrors ? SourceContentsWithErrors
   : SourceContentsWithoutErrors,
- WantDiagnostics::Auto, SkipCache);
+ WantDiagnostics::Auto);
   UpdateStatsOnAddDocument(FileIndex, ShouldHaveErrors);
 };
 
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalComp

[PATCH] D48068: [clangd] Move caching of compile args out of ClangdServer.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

After looking at it more closely, it seems caching happens in the underlying 
compilation databases anyway. So I guess we don't even need the 
`CachingCompilationDatabase`.
I'll remove it.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48068



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


[PATCH] D48068: [clangd] Move caching of compile args out of ClangdServer.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 150917.
ilya-biryukov added a comment.

- Remove CachingCompilationDb


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48068

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/CompileArgsCache.cpp
  clangd/CompileArgsCache.h
  clangd/GlobalCompilationDatabase.h
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -20,8 +20,7 @@
 
 // Calls addDocument and then blockUntilIdleForTest.
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags = WantDiagnostics::Auto,
-bool SkipCache = false);
+WantDiagnostics WantDiags = WantDiagnostics::Auto);
 
 llvm::Expected
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -12,8 +12,8 @@
 namespace clangd {
 
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags, bool SkipCache) {
-  Server.addDocument(File, Contents, WantDiags, SkipCache);
+WantDiagnostics WantDiags) {
+  Server.addDocument(File, Contents, WantDiags);
   if (!Server.blockUntilIdleForTest())
 llvm_unreachable("not idle after addDocument");
 }
Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -390,16 +390,7 @@
 
   // Now switch to C++ mode.
   CDB.ExtraClangFlags = {"-xc++"};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents1);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  runAddDocument(Server, FooCpp, SourceContents2);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto);
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument calls should finish without errors too.
   runAddDocument(Server, FooCpp, SourceContents1);
@@ -431,14 +422,7 @@
 
   // Parse without the define, no errors should be produced.
   CDB.ExtraClangFlags = {};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument call should finish without errors too.
@@ -500,10 +484,8 @@
   CDB.ExtraClangFlags.clear();
   DiagConsumer.clear();
   Server.removeDocument(BazCpp);
-  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
-  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto);
+  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
 
   EXPECT_THAT(DiagConsumer.filesWithDiags(),
@@ -708,7 +690,7 @@
   Server.addDocument(FilePaths[FileIndex],
  ShouldHaveErrors ? SourceContentsWithErrors
   : SourceContentsWithoutErrors,
- WantDiagnostics::Auto, SkipCache);
+ WantDiagnostics::Auto);
   UpdateStatsOnAddDocument(FileIndex, ShouldHaveErrors);
 };
 
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -85,6 +85,7 @@
   /// is located.
   llvm::Optional CompileCommandsDir;
 };
+
 } // namespace clangd
 } // namespace clang
 
Index: clangd/CompileArgsCache.h
===
--- clangd/CompileArgsCache.h
+++ /dev/null
@@ -1,43 +0,0 

[PATCH] D48068: [clangd] Move caching of compile args out of ClangdServer.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 150920.
ilya-biryukov added a comment.

- Revert "Remove CachingCompilationDb". Turns out we do need it internally 
(Thanks, Sam!) :-)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48068

Files:
  clangd/CMakeLists.txt
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/CompileArgsCache.cpp
  clangd/CompileArgsCache.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  unittests/clangd/ClangdTests.cpp
  unittests/clangd/SyncAPI.cpp
  unittests/clangd/SyncAPI.h

Index: unittests/clangd/SyncAPI.h
===
--- unittests/clangd/SyncAPI.h
+++ unittests/clangd/SyncAPI.h
@@ -20,8 +20,7 @@
 
 // Calls addDocument and then blockUntilIdleForTest.
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags = WantDiagnostics::Auto,
-bool SkipCache = false);
+WantDiagnostics WantDiags = WantDiagnostics::Auto);
 
 llvm::Expected
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
Index: unittests/clangd/SyncAPI.cpp
===
--- unittests/clangd/SyncAPI.cpp
+++ unittests/clangd/SyncAPI.cpp
@@ -12,8 +12,8 @@
 namespace clangd {
 
 void runAddDocument(ClangdServer &Server, PathRef File, StringRef Contents,
-WantDiagnostics WantDiags, bool SkipCache) {
-  Server.addDocument(File, Contents, WantDiags, SkipCache);
+WantDiagnostics WantDiags) {
+  Server.addDocument(File, Contents, WantDiags);
   if (!Server.blockUntilIdleForTest())
 llvm_unreachable("not idle after addDocument");
 }
Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -390,16 +390,7 @@
 
   // Now switch to C++ mode.
   CDB.ExtraClangFlags = {"-xc++"};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents1);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  runAddDocument(Server, FooCpp, SourceContents2);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto);
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument calls should finish without errors too.
   runAddDocument(Server, FooCpp, SourceContents1);
@@ -431,14 +422,7 @@
 
   // Parse without the define, no errors should be produced.
   CDB.ExtraClangFlags = {};
-  // By default addDocument does not check if CompileCommand has changed, so we
-  // expect to see the errors.
-  runAddDocument(Server, FooCpp, SourceContents);
-  EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags());
-  // Passing SkipCache=true will force addDocument to reparse the file with
-  // proper flags.
-  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
   EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags());
   // Subsequent addDocument call should finish without errors too.
@@ -500,10 +484,8 @@
   CDB.ExtraClangFlags.clear();
   DiagConsumer.clear();
   Server.removeDocument(BazCpp);
-  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
-  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto,
- /*SkipCache=*/true);
+  Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto);
+  Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto);
   ASSERT_TRUE(Server.blockUntilIdleForTest());
 
   EXPECT_THAT(DiagConsumer.filesWithDiags(),
@@ -708,7 +690,7 @@
   Server.addDocument(FilePaths[FileIndex],
  ShouldHaveErrors ? SourceContentsWithErrors
   : SourceContentsWithoutErrors,
- WantDiagnostics::Auto, SkipCache);
+ WantDiagnostics::Auto);
   UpdateStatsOnAddDocument(FileIndex, ShouldHaveErrors);
 };
 
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -85,6 +85,34 @@
   /// is located.
   llvm::Optional CompileCommandsDir;
 };
+
+/// A wrapper around GlobalCompilationDatabase that caches the compile commands.
+/// Note that only

[PATCH] D47829: [Driver] Accept the -fno-shrink-wrap option for GCC compatibility

2018-06-12 Thread Simon Dardis via Phabricator via cfe-commits
sdardis added a comment.

In https://reviews.llvm.org/D47829#1124040, @efriedma wrote:

> Is this something which is actually useful to control?  From your 
> description, you want to add the flag to clang not because you actually want 
> to use it, but just because you can't figure out how to pass the right flags 
> to your clang build.
>
> If it is useful, it should be implemented as a function attribute, not a 
> global flag.


This is useful to control in the sense of being able to opt-in or opt-out of 
the shrink wrapping pass for clang, especially in the cases of where we might 
discover a triggerable bug in a released version of clang.

Currently, the compiler-rt sanitizer tests make use of the CMAKE_C_FLAGS and 
CMAKE_CXX_FLAGS when generating the test objects. Working around this would 
require stripping the incompatible arguments from those variables when building 
the test objects. This seems to me to worse choice, as I'm also posting a patch 
to automatically add -fno-shrink-wrap when building LLVM with GCC for MIPS 
(https://reviews.llvm.org/D48069).


Repository:
  rC Clang

https://reviews.llvm.org/D47829



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


[PATCH] D47935: [clangd] Boost completion score according to file proximity.

2018-06-12 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 150923.
ioeric added a comment.

- Merge branch 'uri' into proximity
- Addressed review comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D47935

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  unittests/clangd/QualityTests.cpp
  unittests/clangd/TestFS.cpp
  unittests/clangd/URITests.cpp

Index: unittests/clangd/URITests.cpp
===
--- unittests/clangd/URITests.cpp
+++ unittests/clangd/URITests.cpp
@@ -14,46 +14,20 @@
 
 namespace clang {
 namespace clangd {
+
+// Force the unittest URI scheme to be linked,
+extern volatile int UnittestSchemeAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED UnittestSchemeAnchorDest =
+UnittestSchemeAnchorSource;
+
 namespace {
 
 using ::testing::AllOf;
 
 MATCHER_P(Scheme, S, "") { return arg.scheme() == S; }
 MATCHER_P(Authority, A, "") { return arg.authority() == A; }
 MATCHER_P(Body, B, "") { return arg.body() == B; }
 
-// Assume all files in the schema have a "test-root/" root directory, and the
-// schema path is the relative path to the root directory.
-// So the schema of "/some-dir/test-root/x/y/z" is "test:x/y/z".
-class TestScheme : public URIScheme {
-public:
-  static const char *Scheme;
-
-  static const char *TestRoot;
-
-  llvm::Expected
-  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
-  llvm::StringRef HintPath) const override {
-auto Pos = HintPath.find(TestRoot);
-assert(Pos != llvm::StringRef::npos);
-return (HintPath.substr(0, Pos + llvm::StringRef(TestRoot).size()) + Body)
-.str();
-  }
-
-  llvm::Expected
-  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
-auto Pos = AbsolutePath.find(TestRoot);
-assert(Pos != llvm::StringRef::npos);
-return URI(Scheme, /*Authority=*/"",
-   AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
-  }
-};
-
-const char *TestScheme::Scheme = "unittest";
-const char *TestScheme::TestRoot = "/test-root/";
-
-static URISchemeRegistry::Add X(TestScheme::Scheme, "Test schema");
-
 std::string createOrDie(llvm::StringRef AbsolutePath,
 llvm::StringRef Scheme = "file") {
   auto Uri = URI::create(AbsolutePath, Scheme);
Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 #include "TestFS.h"
+#include "URI.h"
 #include "llvm/Support/Errc.h"
 #include "gtest/gtest.h"
 
@@ -62,5 +63,50 @@
   return Path.str();
 }
 
+// Assume all files in the schema have a "test-root/" root directory, and the
+// schema path is the relative path to the root directory.
+// So the schema of "/some-dir/test-root/x/y/z" is "test:x/y/z".
+class TestScheme : public URIScheme {
+public:
+  static const char *Scheme;
+
+  static const char *TestRoot;
+
+  llvm::Expected
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+  llvm::StringRef HintPath) const override {
+auto Pos = HintPath.find(TestRoot);
+assert(Pos != llvm::StringRef::npos);
+return (HintPath.substr(0, Pos + llvm::StringRef(TestRoot).size()) + Body)
+.str();
+  }
+
+  llvm::Expected
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+auto Pos = AbsolutePath.find(TestRoot);
+if (Pos == llvm::StringRef::npos)
+  return llvm::make_error(
+  llvm::Twine("Directory ") + TestRoot + " not found in path " +
+  AbsolutePath,
+  llvm::inconvertibleErrorCode());
+
+return URI(Scheme, /*Authority=*/"",
+   AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
+  }
+};
+
+const char *TestScheme::Scheme = "unittest";
+#ifdef _WIN32
+const char *TestScheme::TestRoot = "\\test-root\\";
+#else
+const char *TestScheme::TestRoot = "/test-root/";
+#endif
+
+static URISchemeRegistry::Add X(TestScheme::Scheme, "Test schema");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the plugin.
+volatile int UnittestSchemeAnchorSource = 0;
+
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/QualityTests.cpp
===
--- unittests/clangd/QualityTests.cpp
+++ unittests/clangd/QualityTests.cpp
@@ -18,12 +18,19 @@
 //===--===//
 
 #include "Quality.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace clangd {
+
+// Force the unittest URI scheme to be linked,
+extern volatile int UnittestSchemeAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED UnittestSchemeAnchorDest =
+UnittestSchemeAnchorSource;
+
 namespace {
 
 T

[PATCH] D47935: [clangd] Boost completion score according to file proximity.

2018-06-12 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 150924.
ioeric added a comment.

- Cleanup comment a bit.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D47935

Files:
  clangd/CodeComplete.cpp
  clangd/Quality.cpp
  clangd/Quality.h
  unittests/clangd/QualityTests.cpp
  unittests/clangd/TestFS.cpp
  unittests/clangd/URITests.cpp

Index: unittests/clangd/URITests.cpp
===
--- unittests/clangd/URITests.cpp
+++ unittests/clangd/URITests.cpp
@@ -14,46 +14,20 @@
 
 namespace clang {
 namespace clangd {
+
+// Force the unittest URI scheme to be linked,
+extern volatile int UnittestSchemeAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED UnittestSchemeAnchorDest =
+UnittestSchemeAnchorSource;
+
 namespace {
 
 using ::testing::AllOf;
 
 MATCHER_P(Scheme, S, "") { return arg.scheme() == S; }
 MATCHER_P(Authority, A, "") { return arg.authority() == A; }
 MATCHER_P(Body, B, "") { return arg.body() == B; }
 
-// Assume all files in the schema have a "test-root/" root directory, and the
-// schema path is the relative path to the root directory.
-// So the schema of "/some-dir/test-root/x/y/z" is "test:x/y/z".
-class TestScheme : public URIScheme {
-public:
-  static const char *Scheme;
-
-  static const char *TestRoot;
-
-  llvm::Expected
-  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
-  llvm::StringRef HintPath) const override {
-auto Pos = HintPath.find(TestRoot);
-assert(Pos != llvm::StringRef::npos);
-return (HintPath.substr(0, Pos + llvm::StringRef(TestRoot).size()) + Body)
-.str();
-  }
-
-  llvm::Expected
-  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
-auto Pos = AbsolutePath.find(TestRoot);
-assert(Pos != llvm::StringRef::npos);
-return URI(Scheme, /*Authority=*/"",
-   AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
-  }
-};
-
-const char *TestScheme::Scheme = "unittest";
-const char *TestScheme::TestRoot = "/test-root/";
-
-static URISchemeRegistry::Add X(TestScheme::Scheme, "Test schema");
-
 std::string createOrDie(llvm::StringRef AbsolutePath,
 llvm::StringRef Scheme = "file") {
   auto Uri = URI::create(AbsolutePath, Scheme);
Index: unittests/clangd/TestFS.cpp
===
--- unittests/clangd/TestFS.cpp
+++ unittests/clangd/TestFS.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 #include "TestFS.h"
+#include "URI.h"
 #include "llvm/Support/Errc.h"
 #include "gtest/gtest.h"
 
@@ -62,5 +63,50 @@
   return Path.str();
 }
 
+// Assume all files in the schema have a "test-root/" root directory, and the
+// schema path is the relative path to the root directory.
+// So the schema of "/some-dir/test-root/x/y/z" is "test:x/y/z".
+class TestScheme : public URIScheme {
+public:
+  static const char *Scheme;
+
+  static const char *TestRoot;
+
+  llvm::Expected
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+  llvm::StringRef HintPath) const override {
+auto Pos = HintPath.find(TestRoot);
+assert(Pos != llvm::StringRef::npos);
+return (HintPath.substr(0, Pos + llvm::StringRef(TestRoot).size()) + Body)
+.str();
+  }
+
+  llvm::Expected
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+auto Pos = AbsolutePath.find(TestRoot);
+if (Pos == llvm::StringRef::npos)
+  return llvm::make_error(
+  llvm::Twine("Directory ") + TestRoot + " not found in path " +
+  AbsolutePath,
+  llvm::inconvertibleErrorCode());
+
+return URI(Scheme, /*Authority=*/"",
+   AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
+  }
+};
+
+const char *TestScheme::Scheme = "unittest";
+#ifdef _WIN32
+const char *TestScheme::TestRoot = "\\test-root\\";
+#else
+const char *TestScheme::TestRoot = "/test-root/";
+#endif
+
+static URISchemeRegistry::Add X(TestScheme::Scheme, "Test schema");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the plugin.
+volatile int UnittestSchemeAnchorSource = 0;
+
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/QualityTests.cpp
===
--- unittests/clangd/QualityTests.cpp
+++ unittests/clangd/QualityTests.cpp
@@ -18,12 +18,19 @@
 //===--===//
 
 #include "Quality.h"
+#include "TestFS.h"
 #include "TestTU.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
 namespace clang {
 namespace clangd {
+
+// Force the unittest URI scheme to be linked,
+extern volatile int UnittestSchemeAnchorSource;
+static int LLVM_ATTRIBUTE_UNUSED UnittestSchemeAnchorDest =
+UnittestSchemeAnchorSource;
+
 namespace {
 
 TEST(QualityTests, SymbolQualitySignalExt

[PATCH] D47935: [clangd] Boost completion score according to file proximity.

2018-06-12 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

PTAL




Comment at: clangd/Quality.cpp:215
 
 void SymbolRelevanceSignals::merge(const CodeCompletionResult &SemaCCResult) {
   if (SemaCCResult.Availability == CXAvailability_NotAvailable ||

ioeric wrote:
> sammccall wrote:
> > proximity path needs to be set here too
> Alternatively, I wonder if we could give sema result a fixed proximity score 
> as they are symbols that are already included? 
As discussed offline, sema symbols now have a fixed proximity score (not 
entirely sure about the value though).



Comment at: clangd/Quality.h:74
+  // If set, this is used to compute proximity from symbol's declaring file.
+  llvm::StringRef ProximityPath;
   /// Proximity between best declaration and the query. [0-1], 1 is closest.

ioeric wrote:
> ioeric wrote:
> > sammccall wrote:
> > > sammccall wrote:
> > > > It seems OK to have ProximityPath or ProximityScore, but we shouldn't 
> > > > have both: drop proximityscore and calculate it during evaluate()?
> > > what's the plan for associated-header? should this be a smallvector<2>?
> > Just want to make sure I understand. We would copy the symbol URI to use in 
> > `merge` right?
> I think it should be easy to change this to vector when it's actually needed?
Changed to vector anyway...



Comment at: clangd/Quality.h:74
+  // If set, this is used to compute proximity from symbol's declaring file.
+  llvm::StringRef ProximityPath;
   /// Proximity between best declaration and the query. [0-1], 1 is closest.

ioeric wrote:
> ioeric wrote:
> > ioeric wrote:
> > > sammccall wrote:
> > > > sammccall wrote:
> > > > > It seems OK to have ProximityPath or ProximityScore, but we shouldn't 
> > > > > have both: drop proximityscore and calculate it during evaluate()?
> > > > what's the plan for associated-header? should this be a smallvector<2>?
> > > Just want to make sure I understand. We would copy the symbol URI to use 
> > > in `merge` right?
> > I think it should be easy to change this to vector when it's actually 
> > needed?
> Changed to vector anyway...
Experimented with this a bit (removing ProximityScore). As we print the 
proximity score for debugging, we would still want to keep the store. 
Alternatively, I made the proximity paths a parameter of `merge` as we only use 
them for index result anyway.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D47935



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


[PATCH] D48071: [clangd] Add an option controlling caching of compile commands.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: jkorous, MaskRay, ioeric.

Disabled by default and hidden, caching for most implementation
already happens outside clangd, so we rarely need to change it.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48071

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -134,6 +134,12 @@
 "eventually. Don't rely on it."),
 llvm::cl::init(""), llvm::cl::Hidden);
 
+static llvm::cl::opt CacheCompilationArgs(
+"cache-compilation-args",
+llvm::cl::desc("When true, clangd will cache compilation arguments that "
+   "come from the compilation databases."),
+llvm::cl::init(false), llvm::cl::Hidden);
+
 int main(int argc, char *argv[]) {
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::cl::ParseCommandLineOptions(argc, argv, "clangd");
@@ -235,7 +241,8 @@
   CCOpts.Limit = LimitResults;
 
   // Initialize and run ClangdLSPServer.
-  ClangdLSPServer LSPServer(Out, CCOpts, CompileCommandsDirPath, Opts);
+  ClangdLSPServer LSPServer(Out, CCOpts, CompileCommandsDirPath, Opts,
+CacheCompilationArgs);
   constexpr int NoShutdownRequestErrorCode = 1;
   llvm::set_thread_name("clangd.main");
   // Change stdin to binary to not lose \r\n on windows.
Index: clangd/ClangdLSPServer.h
===
--- clangd/ClangdLSPServer.h
+++ clangd/ClangdLSPServer.h
@@ -35,7 +35,7 @@
   /// for compile_commands.json in all parent directories of each file.
   ClangdLSPServer(JSONOutput &Out, const clangd::CodeCompleteOptions &CCOpts,
   llvm::Optional CompileCommandsDir,
-  const ClangdServer::Options &Opts);
+  const ClangdServer::Options &Opts, bool CacheCompileCommands);
 
   /// Run LSP server loop, receiving input for it from \p In. \p In must be
   /// opened in binary mode. Output will be written using Out variable passed to
@@ -101,7 +101,8 @@
   // Various ClangdServer parameters go here. It's important they're created
   // before ClangdServer.
   DirectoryBasedGlobalCompilationDatabase NonCachedCDB;
-  CachingCompilationDb CDB;
+  // Can be null if no caching was requested.
+  std::unique_ptr CachedCDB;
 
   RealFileSystemProvider FSProvider;
   /// Options used for code completion
Index: clangd/ClangdLSPServer.cpp
===
--- clangd/ClangdLSPServer.cpp
+++ clangd/ClangdLSPServer.cpp
@@ -12,6 +12,7 @@
 #include "JSONRPCDispatcher.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
@@ -133,7 +134,8 @@
   if (Params.metadata && !Params.metadata->extraFlags.empty()) {
 NonCachedCDB.setExtraFlagsForFile(File,
   std::move(Params.metadata->extraFlags));
-CDB.invalidate(File);
+if (CachedCDB)
+  CachedCDB->invalidate(File);
   }
 
   std::string &Contents = Params.textDocument.text;
@@ -157,7 +159,8 @@
 // fail rather than giving wrong results.
 DraftMgr.removeDraft(File);
 Server.removeDocument(File);
-CDB.invalidate(File);
+if (CachedCDB)
+  CachedCDB->invalidate(File);
 log(llvm::toString(Contents.takeError()));
 return;
   }
@@ -388,19 +391,25 @@
   if (Settings.compilationDatabasePath.hasValue()) {
 NonCachedCDB.setCompileCommandsDir(
 Settings.compilationDatabasePath.getValue());
-CDB.clear();
+if (CachedCDB)
+  CachedCDB->clear();
 
 reparseOpenedFiles();
   }
 }
 
 ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
  const clangd::CodeCompleteOptions &CCOpts,
  llvm::Optional CompileCommandsDir,
- const ClangdServer::Options &Opts)
-: Out(Out), NonCachedCDB(std::move(CompileCommandsDir)), CDB(NonCachedCDB),
+ const ClangdServer::Options &Opts,
+ bool CacheCompileCommands)
+: Out(Out), NonCachedCDB(std::move(CompileCommandsDir)),
+  CachedCDB(CacheCompileCommands
+? llvm::make_unique(NonCachedCDB)
+: nullptr),
   CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
-  Server(CDB, FSProvider, /*DiagConsumer=*/*this, Opts) {}
+  Server(CachedCDB ? (GlobalCompilationDatabase&) *CachedCDB : NonCachedCDB, FSProvider,
+ /*DiagConsumer=*/*this, Opts) {}
 
 bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
   assert(!IsDone && "Run was called before");
_

[PATCH] D48071: [clangd] Add an option controlling caching of compile commands.

2018-06-12 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Testing should be possible with lit tests, I'll look into that. Let me know if 
there's anything else about this patch that needs attention. Thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48071



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


[PATCH] D48063: [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 150926.
krasimir added a comment.

- Add tests


Repository:
  rC Clang

https://reviews.llvm.org/D48063

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestProto.cpp
  unittests/Format/FormatTestTextProto.cpp

Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -485,8 +485,15 @@
   verifyFormat("keys: []");
   verifyFormat("keys: [ 1 ]");
   verifyFormat("keys: [ 'ala', 'bala' ]");
-  verifyFormat("keys:\n"
-   "[ 'ala', 'bala', 'porto', 'kala', 'too', 'long', 'ng' ]");
+  verifyFormat("keys: [\n"
+   "  'ala',\n"
+   "  'bala',\n"
+   "  'porto',\n"
+   "  'kala',\n"
+   "  'too',\n"
+   "  'long',\n"
+   "  'ng'\n"
+   "]");
   verifyFormat("key: item\n"
"keys: [\n"
"  'ala',\n"
@@ -670,5 +677,28 @@
"}");
 }
 
+TEST_F(FormatTestTextProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("submessage: {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage: <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("repeatedd: [\n"
+   "  'ey'\n"
+   "]");
+  // "{" is going over the column limit.
+  verifyFormat(
+  "submessagee: {\n"
+  "  key: 'a'\n"
+  "}");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: unittests/Format/FormatTestProto.cpp
===
--- unittests/Format/FormatTestProto.cpp
+++ unittests/Format/FormatTestProto.cpp
@@ -624,5 +624,34 @@
"}");
 }
 
+TEST_F(FormatTestProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  repeatedd: [\n"
+   "'ey'\n"
+   "  ]\n"
+   "}");
+}
+
+
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -3103,7 +3103,35 @@
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
 if ((Style.Language == FormatStyle::LK_Proto ||
  Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+((!Style.AlwaysBreakBeforeMultilineStrings &&
+  Right.isStringLiteral()) ||
+ // Prevent cases like:
+ //
+ // submessage:
+ // { key: valu }
+ //
+ // when the snippet does not fit into one line.
+ // Prefer:
+ //
+ // submessage: {
+ //   key: valu
+ // }
+ //
+ // instead, even if it is longer by one line.
+ //
+ // Note that this allows allows the "{" to go over the column limit
+ // when the column limit is just between ":" and "{", but that does
+ // not happen too often and alternative formattings in this case are
+ // not much better.
+ //
+ // The code covers the cases:
+ //
+ // submessage: { ... }
+ // submessage: < ... >
+ // repeated: [ ... ]
+ ((Right.is(tok::l_brace) || Right.is(tok::less)) &&
+  Right.is(TT_DictLiteral)) ||
+ Right.is(TT_ArrayInitializerLSquare)))
   return false;

[PATCH] D48072: Sema: Fix PR12350 destructor name lookup, addressing (some of) DR244

2018-06-12 Thread Jeremy Morse via Phabricator via cfe-commits
jmorse created this revision.
jmorse added reviewers: rsmith, doug.gregor, majnemer.
Herald added a subscriber: cfe-commits.

Hi,

This patch tries to fix a problem in clangs implementation of C++11's
[basic.lookup.qual]p6 as demonstrated in PR12350, by:

- Re-enabling looking in name-specifier prefixes for destructor names, when the 
penultimate name is a class
- In that case, forces the destructor name to be sought as a type-name

Which has some history. Looking in the name-specifier prefix for a
destructor name was partially disabled in r96836 for C++ < 11 because
name hiding could hide the final destructor name lookup (PR6358), and
then for all C++ in r107835 because the initial fix for 
https://reviews.llvm.org/D244 (r209319)
wasn't in.

However, the spec still specifies looking in the name-specifier prefix, and
without doing so bugs like PR12350 can't be fixed. This patch gets around
the original name hiding issue by forcing a type-name lookup if we're
looking in the name-specifier prefix where the penultimate is a class,
avoiding any hiding.

This is almost certainly what the spec intended, IMHO. You can read
[basic.lookup.qual]p6 as supporting this interpretation if you take the
pseudo destructors phrasing "...the type-names are looked up _as_ types
in the scope..." and assume that the class-name form being looked
up "Similarly" means that the second class-name should also be looked
up _as_ a class-name.


Repository:
  rC Clang

https://reviews.llvm.org/D48072

Files:
  lib/Sema/SemaExprCXX.cpp
  test/CXX/drs/dr2xx.cpp
  test/SemaCXX/destructor.cpp


Index: test/SemaCXX/destructor.cpp
===
--- test/SemaCXX/destructor.cpp
+++ test/SemaCXX/destructor.cpp
@@ -493,4 +493,23 @@
   x.foo1();
 }
 }
+
+namespace PR12350 {
+  class basic_string {
+  public:
+~basic_string();
+char *something;
+  };
+
+  namespace notstd {
+typedef basic_string string;
+  }
+
+  void
+  foo(notstd::string *bar)
+  {
+bar->notstd::string::~string(); // OK
+  }
+}
+
 #endif // BE_THE_HEADER
Index: test/CXX/drs/dr2xx.cpp
===
--- test/CXX/drs/dr2xx.cpp
+++ test/CXX/drs/dr2xx.cpp
@@ -502,7 +502,7 @@
 f.N::F::~E();
 // This is valid; we look up the second F in the same scope in which we
 // found the first one, that is, 'N::'.
-f.N::F::~F(); // FIXME: expected-error {{expected the class name after '~' 
to name a destructor}}
+f.N::F::~F();
 // This is technically ill-formed; G is looked up in 'N::' and is not 
found;
 // as above, this is probably a bug in the standard.
 f.N::F::~G();
Index: lib/Sema/SemaExprCXX.cpp
===
--- lib/Sema/SemaExprCXX.cpp
+++ lib/Sema/SemaExprCXX.cpp
@@ -112,6 +112,7 @@
   DeclContext *LookupCtx = nullptr;
   bool isDependent = false;
   bool LookInScope = false;
+  LookupNameKind LookupKind = LookupOrdinaryName;
 
   if (SS.isInvalid())
 return nullptr;
@@ -144,7 +145,9 @@
   LookupCtx = DC;
   isDependent = false;
 } else if (DC && isa(DC)) {
-  LookAtPrefix = false;
+  // Penultimate name is a class-name, we will LookAtPrefix. However, look
+  // up class-name's in the same scope as the first.
+  LookupKind = LookupNestedNameSpecifierName;
   LookInScope = true;
 }
 
@@ -184,7 +187,7 @@
   }
 
   TypeDecl *NonMatchingTypeDecl = nullptr;
-  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
+  LookupResult Found(*this, &II, NameLoc, LookupKind);
   for (unsigned Step = 0; Step != 2; ++Step) {
 // Look for the name first in the computed lookup context (if we
 // have one) and, if that fails to find a match, in the scope (if


Index: test/SemaCXX/destructor.cpp
===
--- test/SemaCXX/destructor.cpp
+++ test/SemaCXX/destructor.cpp
@@ -493,4 +493,23 @@
   x.foo1();
 }
 }
+
+namespace PR12350 {
+  class basic_string {
+  public:
+~basic_string();
+char *something;
+  };
+
+  namespace notstd {
+typedef basic_string string;
+  }
+
+  void
+  foo(notstd::string *bar)
+  {
+bar->notstd::string::~string(); // OK
+  }
+}
+
 #endif // BE_THE_HEADER
Index: test/CXX/drs/dr2xx.cpp
===
--- test/CXX/drs/dr2xx.cpp
+++ test/CXX/drs/dr2xx.cpp
@@ -502,7 +502,7 @@
 f.N::F::~E();
 // This is valid; we look up the second F in the same scope in which we
 // found the first one, that is, 'N::'.
-f.N::F::~F(); // FIXME: expected-error {{expected the class name after '~' to name a destructor}}
+f.N::F::~F();
 // This is technically ill-formed; G is looked up in 'N::' and is not found;
 // as above, this is probably a bug in the standard.
 f.N::F::~G();
Index: lib/Sema/SemaExprCXX.cpp
===
--- lib/Sema/Se

[PATCH] D47154: Try to make builtin address space declarations not useless

2018-06-12 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: include/clang/Basic/BuiltinsAMDGPU.def:49
+
+// FIXME: Need to disallow constant address space.
 BUILTIN(__builtin_amdgcn_div_scale, "dddbb*", "n")

arsenm wrote:
> Anastasia wrote:
> > Do you plan to provide the support for it later? Or if else perhaps we 
> > should elaborate more what's to be done.
> I'm not sure. I don't know how to best enforce this
The only way I guess if we list overloads with each address space explicitly 
(apart from `constant`)? Or may be with the use of `generic` AS, although that 
will only work for CL2.0.



Comment at: lib/AST/ASTContext.cpp:9093
   unsigned AddrSpace = strtoul(Str, &End, 10);
-  if (End != Str && AddrSpace != 0) {
-Type = Context.getAddrSpaceQualType(Type,
-getLangASFromTargetAS(AddrSpace));
+  if (End != Str) {
+// Note AddrSpace == 0 is not the same as an unspecified address space.

arsenm wrote:
> Anastasia wrote:
> > Could we check against LangAS::Default instead of removing this completely.
> I don't think that really make sense, since that would be leaving this the 
> same. I don't really need it for this patch, but I fundamentally think 
> specifying address space 0 is different from an unspecified address space. 
> According to the description for builtins, if no address space is specified 
> than any address space will be accepted. This is different from a builtin 
> requiring address space 0
I thought `Default` AS was meant to be for the case no AS is specified but I 
guess it doesn't work the same in Builtins specification syntax.



Comment at: lib/CodeGen/CGBuiltin.cpp:3500
+if (auto *PtrTy = dyn_cast(PTy)) {
+  if (PtrTy->getAddressSpace() !=
+  ArgValue->getType()->getPointerAddressSpace()) {

arsenm wrote:
> Anastasia wrote:
> > Would this be correct for OpenCL? Should we use  `isAddressSpaceSupersetOf` 
> > helper instead? Would it also sort the issue with constant AS (at least for 
> > OpenCL)? 
> The issue I mentioned for the other builtin is that it modifies the memory, 
> and doesn't have to do with the casting.
> 
> At this point the AddrSpaceCast has to be emitted. The checking if the cast 
> is legal I guess would be in the SemaExpr part. I know at one point I was 
> trying to use isAddressSpaceSupersetOf in rewriteBuiltinFunctionDecl, but 
> there was some problem with that. I think it didn't make sense with the magic 
> where the builtin without an address space is supposed to accept any address 
> space or something along those lines.
Yes, I think Sema has to check it before indeed. I am not sure it works right 
with OpenCL rules though for the Builtin functions.  Would it make sense to add 
a negative test for this then? 


https://reviews.llvm.org/D47154



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


[PATCH] D43015: clang-format: Introduce BreakInheritanceList option

2018-06-12 Thread Carlos Alberto Enciso via Phabricator via cfe-commits
CarlosAlbertoEnciso added a comment.

@Typz,

It seems that the changes done to `ClangFormatStyleOptions.rst` @334408 are 
causing the generation of the documentation to fail, with the following error:

  Warning, treated as error:
  /llvm/tools/clang/docs/ClangFormatStyleOptions.rst:1060: WARNING: Definition 
list ends without a blank line; unexpected unindent.

by reverting to change @332436 the build is fine and no errors are generated.

Thanks


Repository:
  rC Clang

https://reviews.llvm.org/D43015



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


r334493 - Revert r334418 "Enable crash recovery tests on Windows, globs work in the lit internal shell now"

2018-06-12 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Tue Jun 12 04:33:44 2018
New Revision: 334493

URL: http://llvm.org/viewvc/llvm-project?rev=334493&view=rev
Log:
Revert r334418 "Enable crash recovery tests on Windows, globs work in the lit 
internal shell now"

The tests fail on Windows bots, and for me locally.

> Enable crash recovery tests on Windows, globs work in the lit internal shell 
> now

Modified:
cfe/trunk/test/Driver/crash-report-header.h
cfe/trunk/test/Driver/crash-report-modules.m
cfe/trunk/test/Driver/crash-report-spaces.c
cfe/trunk/test/Driver/crash-report.c

Modified: cfe/trunk/test/Driver/crash-report-header.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-header.h?rev=334493&r1=334492&r2=334493&view=diff
==
--- cfe/trunk/test/Driver/crash-report-header.h (original)
+++ cfe/trunk/test/Driver/crash-report-header.h Tue Jun 12 04:33:44 2018
@@ -5,6 +5,9 @@
 // RUN: cat %t/crash-report-header-*.sh | FileCheck --check-prefix=CHECKSH "%s"
 // REQUIRES: crash-recovery
 
+// because of the glob (*.h, *.sh)
+// REQUIRES: shell
+
 #pragma clang __debug parser_crash
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:
 // CHECK-NEXT: note: diagnostic msg: {{.*}}.h

Modified: cfe/trunk/test/Driver/crash-report-modules.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-modules.m?rev=334493&r1=334492&r2=334493&view=diff
==
--- cfe/trunk/test/Driver/crash-report-modules.m (original)
+++ cfe/trunk/test/Driver/crash-report-modules.m Tue Jun 12 04:33:44 2018
@@ -9,6 +9,12 @@
 // RUN: FileCheck --check-prefix=CHECKSH %s -input-file %t/crash-report-*.sh
 // REQUIRES: crash-recovery
 
+// because of the glob (*.m, *.sh)
+// REQUIRES: shell
+
+// FIXME: This XFAIL is cargo-culted from crash-report.c. Do we need it?
+// XFAIL: mingw32
+
 @import simple;
 const int x = MODULE_MACRO;
 
@@ -28,4 +34,4 @@ const int x = MODULE_MACRO;
 // CHECKSH: "-D" "FOO=BAR"
 // CHECKSH-NOT: "-fmodules-cache-path="
 // CHECKSH: "crash-report-modules-{{[^ ]*}}.m"
-// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^ 
]*}}.cache{{(/|)}}vfs{{(/|)}}vfs.yaml"
+// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^ ]*}}.cache/vfs/vfs.yaml"

Modified: cfe/trunk/test/Driver/crash-report-spaces.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-spaces.c?rev=334493&r1=334492&r2=334493&view=diff
==
--- cfe/trunk/test/Driver/crash-report-spaces.c (original)
+++ cfe/trunk/test/Driver/crash-report-spaces.c Tue Jun 12 04:33:44 2018
@@ -6,6 +6,9 @@
 // RUN: cat "%t/crash report spaces"-*.sh | FileCheck --check-prefix=CHECKSH 
"%s"
 // REQUIRES: crash-recovery
 
+// because of the glob (*.c, *.sh)
+// REQUIRES: shell
+
 #pragma clang __debug parser_crash
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:
 // CHECK-NEXT: note: diagnostic msg: {{.*}}.c

Modified: cfe/trunk/test/Driver/crash-report.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report.c?rev=334493&r1=334492&r2=334493&view=diff
==
--- cfe/trunk/test/Driver/crash-report.c (original)
+++ cfe/trunk/test/Driver/crash-report.c Tue Jun 12 04:33:44 2018
@@ -13,6 +13,9 @@
 // RUN: cat %t/crash-report-*.sh | FileCheck --check-prefix=CHECKSH %s
 // REQUIRES: crash-recovery
 
+// because of the glob (*.c, *.sh)
+// REQUIRES: shell
+
 #pragma clang __debug parser_crash
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:
 // CHECK-NEXT: note: diagnostic msg: {{.*}}crash-report-{{.*}}.c


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


Re: r334418 - Enable crash recovery tests on Windows, globs work in the lit internal shell now

2018-06-12 Thread Hans Wennborg via cfe-commits
I've reverted in r334493 in the meantime.

When I run the tests locally, they fail with:

# command stderr:
C:\src\llvm\tools\clang\test\Driver\crash-report.c:17:11: error:
expected string not found in input
// CHECK: Preprocessed source(s) and associated run script(s) are located at:
  ^
:1:1: note: scanning from here
Error: Unable to find `env' in PATH: no such file or directory

Looking at TestRunner.py:823, I suspect the internal shell doesn't
handle 'env' when it's not the first part of a command.

Actually, maybe switching the order from "not env ... %clang" to "env
... not %clang" might work...

On Tue, Jun 12, 2018 at 4:15 AM, via cfe-commits
 wrote:
> Hi Reid,
>
> Actually, it seems all four tests you changed are failing on one Windows bot 
> http://lab.llvm.org:8011/builders/clang-x86-windows-msvc2015/builds/12464.
>
> Can you please take a look and fix the tests?
>
> Douglas Yung
>
>> -Original Message-
>> From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On Behalf
>> Of via cfe-commits
>> Sent: Monday, June 11, 2018 18:37
>> To: r...@google.com
>> Cc: cfe-commits@lists.llvm.org
>> Subject: RE: r334418 - Enable crash recovery tests on Windows, globs
>> work in the lit internal shell now
>>
>> Hi Reid,
>>
>> I don't know if you noticed, but one of the tests you changed with this
>> commit is failing on the PS4 Windows bot. Can you take a look?
>>
>> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-
>> windows10pro-fast/builds/17695/
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r334494 - Re-apply r334418 "Enable crash recovery tests on Windows, globs work in the lit internal shell now"

2018-06-12 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Tue Jun 12 04:51:22 2018
New Revision: 334494

URL: http://llvm.org/viewvc/llvm-project?rev=334494&view=rev
Log:
Re-apply r334418 "Enable crash recovery tests on Windows, globs work in the lit 
internal shell now"

Plus change run lines from

  not env FOO=bar %clang

to

  env FOO=bar not %clang

To not confuse the internal shell.

Modified:
cfe/trunk/test/Driver/crash-report-header.h
cfe/trunk/test/Driver/crash-report-modules.m
cfe/trunk/test/Driver/crash-report-spaces.c
cfe/trunk/test/Driver/crash-report.c

Modified: cfe/trunk/test/Driver/crash-report-header.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-header.h?rev=334494&r1=334493&r2=334494&view=diff
==
--- cfe/trunk/test/Driver/crash-report-header.h (original)
+++ cfe/trunk/test/Driver/crash-report-header.h Tue Jun 12 04:51:22 2018
@@ -1,13 +1,10 @@
 // RUN: rm -rf %t
 // RUN: mkdir %t
-// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 %clang 
-fsyntax-only %s 2>&1 | FileCheck %s
+// RUN: env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 not %clang 
-fsyntax-only %s 2>&1 | FileCheck %s
 // RUN: cat %t/crash-report-header-*.h | FileCheck --check-prefix=CHECKSRC "%s"
 // RUN: cat %t/crash-report-header-*.sh | FileCheck --check-prefix=CHECKSH "%s"
 // REQUIRES: crash-recovery
 
-// because of the glob (*.h, *.sh)
-// REQUIRES: shell
-
 #pragma clang __debug parser_crash
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:
 // CHECK-NEXT: note: diagnostic msg: {{.*}}.h

Modified: cfe/trunk/test/Driver/crash-report-modules.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-modules.m?rev=334494&r1=334493&r2=334494&view=diff
==
--- cfe/trunk/test/Driver/crash-report-modules.m (original)
+++ cfe/trunk/test/Driver/crash-report-modules.m Tue Jun 12 04:51:22 2018
@@ -1,20 +1,14 @@
 // RUN: rm -rf %t
 // RUN: mkdir -p %t/i %t/m %t
 
-// RUN: not env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t \
-// RUN: %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/\
+// RUN: env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t  \
+// RUN: not %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/ \
 // RUN: -fmodules -fmodules-cache-path=%t/m/ -DFOO=BAR 2>&1 | FileCheck %s
 
 // RUN: FileCheck --check-prefix=CHECKSRC %s -input-file %t/crash-report-*.m
 // RUN: FileCheck --check-prefix=CHECKSH %s -input-file %t/crash-report-*.sh
 // REQUIRES: crash-recovery
 
-// because of the glob (*.m, *.sh)
-// REQUIRES: shell
-
-// FIXME: This XFAIL is cargo-culted from crash-report.c. Do we need it?
-// XFAIL: mingw32
-
 @import simple;
 const int x = MODULE_MACRO;
 
@@ -34,4 +28,4 @@ const int x = MODULE_MACRO;
 // CHECKSH: "-D" "FOO=BAR"
 // CHECKSH-NOT: "-fmodules-cache-path="
 // CHECKSH: "crash-report-modules-{{[^ ]*}}.m"
-// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^ ]*}}.cache/vfs/vfs.yaml"
+// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^ 
]*}}.cache{{(/|)}}vfs{{(/|)}}vfs.yaml"

Modified: cfe/trunk/test/Driver/crash-report-spaces.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-spaces.c?rev=334494&r1=334493&r2=334494&view=diff
==
--- cfe/trunk/test/Driver/crash-report-spaces.c (original)
+++ cfe/trunk/test/Driver/crash-report-spaces.c Tue Jun 12 04:51:22 2018
@@ -1,14 +1,11 @@
 // RUN: rm -rf "%t"
 // RUN: mkdir "%t"
 // RUN: cp "%s" "%t/crash report spaces.c"
-// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 %clang 
-fsyntax-only "%t/crash report spaces.c" 2>&1 | FileCheck "%s"
+// RUN: env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 not %clang 
-fsyntax-only "%t/crash report spaces.c" 2>&1 | FileCheck "%s"
 // RUN: cat "%t/crash report spaces"-*.c | FileCheck --check-prefix=CHECKSRC 
"%s"
 // RUN: cat "%t/crash report spaces"-*.sh | FileCheck --check-prefix=CHECKSH 
"%s"
 // REQUIRES: crash-recovery
 
-// because of the glob (*.c, *.sh)
-// REQUIRES: shell
-
 #pragma clang __debug parser_crash
 // CHECK: Preprocessed source(s) and associated run script(s) are located at:
 // CHECK-NEXT: note: diagnostic msg: {{.*}}.c

Modified: cfe/trunk/test/Driver/crash-report.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report.c?rev=334494&r1=334493&r2=334494&view=diff
==
--- cfe/trunk/test/Driver/crash-report.c (original)
+++ cfe/trunk/test/Driver/crash-report.c Tue Jun 12 04:51:22 2018
@@ -1,8 +1,8 @@
 // RUN: rm -rf %t
 // RUN: mkdir %t
-// RUN: not env TMPDIR=%t TEMP=%t TMP=%t RC_DEBUG_OPTIONS=1  \
+// RUN: env TMPDIR=%t TEMP=%t TMP=%t RC_DEBUG_OPTIONS=1  \
 // RUN:  CC_PRINT_HEA

Re: r334418 - Enable crash recovery tests on Windows, globs work in the lit internal shell now

2018-06-12 Thread Hans Wennborg via cfe-commits
On Tue, Jun 12, 2018 at 1:43 PM, Hans Wennborg  wrote:
> I've reverted in r334493 in the meantime.
>
> When I run the tests locally, they fail with:
>
> # command stderr:
> C:\src\llvm\tools\clang\test\Driver\crash-report.c:17:11: error:
> expected string not found in input
> // CHECK: Preprocessed source(s) and associated run script(s) are located at:
>   ^
> :1:1: note: scanning from here
> Error: Unable to find `env' in PATH: no such file or directory
>
> Looking at TestRunner.py:823, I suspect the internal shell doesn't
> handle 'env' when it's not the first part of a command.
>
> Actually, maybe switching the order from "not env ... %clang" to "env
> ... not %clang" might work...

Trying that in r334494. I'll keep an eye on
http://lab.llvm.org:8011/builders/clang-x86-windows-msvc2015
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r334495 - [clangd] Trace time the operations wait on Semaphore.

2018-06-12 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Jun 12 04:56:21 2018
New Revision: 334495

URL: http://llvm.org/viewvc/llvm-project?rev=334495&view=rev
Log:
[clangd] Trace time the operations wait on Semaphore.

The Semaphore is currently used to limit the number of concurrently
running tasks. Tracing the wait times will allow to find out how much
time is wasted waiting on other operations to complete.

Modified:
clang-tools-extra/trunk/clangd/Threading.cpp

Modified: clang-tools-extra/trunk/clangd/Threading.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Threading.cpp?rev=334495&r1=334494&r2=334495&view=diff
==
--- clang-tools-extra/trunk/clangd/Threading.cpp (original)
+++ clang-tools-extra/trunk/clangd/Threading.cpp Tue Jun 12 04:56:21 2018
@@ -1,4 +1,5 @@
 #include "Threading.h"
+#include "Trace.h"
 #include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
@@ -23,9 +24,14 @@ void Notification::wait() const {
 Semaphore::Semaphore(std::size_t MaxLocks) : FreeSlots(MaxLocks) {}
 
 void Semaphore::lock() {
-  std::unique_lock Lock(Mutex);
-  SlotsChanged.wait(Lock, [&]() { return FreeSlots > 0; });
-  --FreeSlots;
+  trace::Span Span("WaitForFreeSemaphoreSlot");
+  // trace::Span can also acquire locks in ctor and dtor, we make sure it
+  // happens when Semaphore's own lock is not held.
+  {
+std::unique_lock Lock(Mutex);
+SlotsChanged.wait(Lock, [&]() { return FreeSlots > 0; });
+--FreeSlots;
+  }
 }
 
 void Semaphore::unlock() {


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


[PATCH] D48053: Correct behavior of __builtin_*_overflow and constexpr.

2018-06-12 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 150934.
erichkeane marked an inline comment as done.
erichkeane added a comment.

Add error checking to perform copy init.


https://reviews.llvm.org/D48053

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/builtins-overflow.cpp


Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -197,30 +197,42 @@
 
   // First two arguments should be integers.
   for (unsigned I = 0; I < 2; ++I) {
-Expr *Arg = TheCall->getArg(I);
-QualType Ty = Arg->getType();
+ExprResult Arg = TheCall->getArg(I);
+QualType Ty = Arg.get()->getType();
 if (!Ty->isIntegerType()) {
-  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
-  << Ty << Arg->getSourceRange();
+  S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
+  << Ty << Arg.get()->getSourceRange();
   return true;
 }
+InitializedEntity Entity = InitializedEntity::InitializeParameter(
+S.getASTContext(), Ty, /*consume*/ false);
+Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
+if (Arg.isInvalid())
+  return true;
+TheCall->setArg(I, Arg.get());
   }
 
   // Third argument should be a pointer to a non-const integer.
   // IRGen correctly handles volatile, restrict, and address spaces, and
   // the other qualifiers aren't possible.
   {
-Expr *Arg = TheCall->getArg(2);
-QualType Ty = Arg->getType();
+ExprResult Arg = TheCall->getArg(2);
+QualType Ty = Arg.get()->getType();
 const auto *PtrTy = Ty->getAs();
 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
   !PtrTy->getPointeeType().isConstQualified())) {
-  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
-  << Ty << Arg->getSourceRange();
+  S.Diag(Arg.get()->getLocStart(),
+ diag::err_overflow_builtin_must_be_ptr_int)
+  << Ty << Arg.get()->getSourceRange();
   return true;
 }
+InitializedEntity Entity = InitializedEntity::InitializeParameter(
+S.getASTContext(), Ty, /*consume*/ false);
+Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
+if (Arg.isInvalid())
+  return true;
+TheCall->setArg(2, Arg.get());
   }
-
   return false;
 }
 
Index: test/SemaCXX/builtins-overflow.cpp
===
--- test/SemaCXX/builtins-overflow.cpp
+++ test/SemaCXX/builtins-overflow.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s
+// expected-no-diagnostics
+
+int a() {
+  const int x = 3;
+  static int z;
+  constexpr int *y = &z;
+  return []() { return __builtin_sub_overflow((int)x, (int)x, (int *)y); }();
+}
+int a2() {
+  const int x = 3;
+  static int z;
+  constexpr int *y = &z;
+  return []() { return __builtin_sub_overflow(x, x, y); }();
+}


Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -197,30 +197,42 @@
 
   // First two arguments should be integers.
   for (unsigned I = 0; I < 2; ++I) {
-Expr *Arg = TheCall->getArg(I);
-QualType Ty = Arg->getType();
+ExprResult Arg = TheCall->getArg(I);
+QualType Ty = Arg.get()->getType();
 if (!Ty->isIntegerType()) {
-  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
-  << Ty << Arg->getSourceRange();
+  S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
+  << Ty << Arg.get()->getSourceRange();
   return true;
 }
+InitializedEntity Entity = InitializedEntity::InitializeParameter(
+S.getASTContext(), Ty, /*consume*/ false);
+Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
+if (Arg.isInvalid())
+  return true;
+TheCall->setArg(I, Arg.get());
   }
 
   // Third argument should be a pointer to a non-const integer.
   // IRGen correctly handles volatile, restrict, and address spaces, and
   // the other qualifiers aren't possible.
   {
-Expr *Arg = TheCall->getArg(2);
-QualType Ty = Arg->getType();
+ExprResult Arg = TheCall->getArg(2);
+QualType Ty = Arg.get()->getType();
 const auto *PtrTy = Ty->getAs();
 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
   !PtrTy->getPointeeType().isConstQualified())) {
-  S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
-  << Ty << Arg->getSourceRange();
+  S.Diag(Arg.get()->getLocStart(),
+ diag::err_overflow_builtin_must_be_ptr_int)
+  << Ty << Arg.get()->getSourceRange();
   return true;
 }
+InitializedEntity Entity = InitializedEntity::InitializeParameter(
+S.getASTContext(), Ty, /*consume*/ false);
+Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
+if (A

[PATCH] D48053: Correct behavior of __builtin_*_overflow and constexpr.

2018-06-12 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:228
+  S.getASTContext(), Ty, /*consume*/ false);
+  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
+  TheCall->setArg(2, Arg.get());

efriedma wrote:
> Is it possible for this initialization to fail?  If it can't fail, please add 
> an assertion; otherwise, you probably need to "return true".  (Not sure off 
> the top of my head how that would happen; maybe it would error out on a 
> `volatile int*`?)
You're correct, it apparently can fail!  I've added a test to return true.  
Based on a reading of the code, performcopyinit diagnoses, so I think this 
patch should be correct.


https://reviews.llvm.org/D48053



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


[PATCH] D45179: [libc++] Add _LIBCPP_FORCE_NODISCARD define to force-enable nodiscard in pre-C++17

2018-06-12 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

What's the status here? The MS STL has this feature under _HAS_NODISCARD and 
it's super useful.


Repository:
  rCXX libc++

https://reviews.llvm.org/D45179



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


[PATCH] D47435: Add __builtin_signbit semantic checking

2018-06-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Ping


Repository:
  rC Clang

https://reviews.llvm.org/D47435



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


r334503 - Fix overload resolution between Ptr-To-Member and Bool

2018-06-12 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Tue Jun 12 06:59:32 2018
New Revision: 334503

URL: http://llvm.org/viewvc/llvm-project?rev=334503&view=rev
Log:
Fix overload resolution between Ptr-To-Member and Bool

As reported here (https://bugs.llvm.org/show_bug.cgi?id=19808)
and discovered independently when looking at plum-hall tests,
we incorrectly implemented over.ics.rank, which says "A conversion
that is not a conversion of a pointer, or pointer to member, to bool
is better than another conversion that is such a conversion.".

In the current Draft (N4750), this is phrased slightly differently in
paragraph 4.1: A conversion that does not convert a pointer, a pointer
to member, or std::nullptr_t to bool is better than one that does.

The comment on isPointerConversionToBool (the changed function)
also confirms that this is the case (note outdated reference):
isPointerConversionToBool - Determines whether this conversion is
a conversion of a pointer or pointer-to-member to bool. This is
used as part of the ranking of standard conversion sequences
(C++ 13.3.3.2p4).

However, despite this comment, it didn't check isMemberPointerType
on the 'FromType', presumably incorrectly assuming that 'isPointerType' 
matched it.  This patch fixes this by adding isMemberPointerType to
this function. Additionally, member function pointers are just 
MemberPointerTypes that point to functions insted of data, so that
is fixed in this patch as well.

Modified:
cfe/trunk/lib/Sema/SemaOverload.cpp
cfe/trunk/test/SemaCXX/overload-call.cpp

Modified: cfe/trunk/lib/Sema/SemaOverload.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaOverload.cpp?rev=334503&r1=334502&r2=334503&view=diff
==
--- cfe/trunk/lib/Sema/SemaOverload.cpp (original)
+++ cfe/trunk/lib/Sema/SemaOverload.cpp Tue Jun 12 06:59:32 2018
@@ -223,6 +223,7 @@ bool StandardConversionSequence::isPoint
   // a pointer.
   if (getToType(1)->isBooleanType() &&
   (getFromType()->isPointerType() ||
+   getFromType()->isMemberPointerType() ||
getFromType()->isObjCObjectPointerType() ||
getFromType()->isBlockPointerType() ||
getFromType()->isNullPtrType() ||

Modified: cfe/trunk/test/SemaCXX/overload-call.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/overload-call.cpp?rev=334503&r1=334502&r2=334503&view=diff
==
--- cfe/trunk/test/SemaCXX/overload-call.cpp (original)
+++ cfe/trunk/test/SemaCXX/overload-call.cpp Tue Jun 12 06:59:32 2018
@@ -667,3 +667,24 @@ namespace ProduceNotesAfterSFINAEFailure
   void f(void*, A); // expected-note {{candidate function not viable}}
   void g() { f(1, 2); } // expected-error {{no matching function}}
 }
+
+namespace PR19808 {
+  struct B {
+int i;
+void bar();
+  };
+  struct D : public B{};
+
+  void f(bool);
+  void f(int D::*);
+  void f(void (D::*)());
+
+  void Usage() {
+int B::*pmem;
+void (B::*pmf)();
+
+// These should not be ambiguous.
+f(pmem);
+f(pmf);
+  }
+}


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


[PATCH] D47435: Add __builtin_signbit semantic checking

2018-06-12 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

The checking by itself looks sane-ish, but i don't have any reasonable 
knowledge in this area.




Comment at: lib/Sema/SemaChecking.cpp:925
+  case Builtin::BI__builtin_signbitl:
 if (SemaBuiltinFPClassification(TheCall, 1))
   return ExprError();

The name of the function is unfortunate given that you call it for 
`__builtin_signbit(int)`.



Comment at: test/Sema/builtins.c:260
+  (void)__builtin_signbit(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbit(1); // expected-error {{floating point 
classification requires argument of floating point type (passed in 'int')}}
+

What about
```
(void)__builtin_signbit(1.0);
```



Comment at: test/Sema/builtins.c:260
+  (void)__builtin_signbit(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbit(1); // expected-error {{floating point 
classification requires argument of floating point type (passed in 'int')}}
+

lebedev.ri wrote:
> What about
> ```
> (void)__builtin_signbit(1.0);
> ```
Hm, is `__builtin_signbit()` taking an integer, or float?
If integer, the comment about `floating point classification` is slightly 
misleading.




Comment at: test/Sema/builtins.c:264
+  (void)__builtin_signbitf(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbitf(1);
+

`1` will be promoted to float?
I'd add one more test with native float:
```
(void)__builtin_signbit(1.0);
```



Comment at: test/Sema/builtins.c:268
+  (void)__builtin_signbitl(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbitl(1);
+}

Same, would be good to see `__builtin_signbitf(1.0);`, 
`__builtin_signbitf(1.0L);`.


Repository:
  rC Clang

https://reviews.llvm.org/D47435



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


[PATCH] D42787: clang-format: do not add extra indent when wrapping last parameter

2018-06-12 Thread Francois Ferrand via Phabricator via cfe-commits
Typz added a comment.

In https://reviews.llvm.org/D42787#1127790, @djasper wrote:

> The normal rule for formatting options apply. If you can dig up a public 
> style guide and a project of reasonable size where it is used, we can add an 
> option.


I don't want to be rude, but it seems to me that in this context this response 
is just a polite way of saying "no" : as discussed already on this patch, this 
is indeed a corner case, and probably not documented anywere, and as far as I 
understand, the current behavior is not referenced in llvm or google coding 
rule either. This is simply the styling that the maintainers find the most 
appropriate.

Hence my question: I know the "rules", but I want to know if you would be open 
to introducing options for tweaking this, in case people do not agree this is 
the most appropriate. Typically, for such corner cases I could imagine a nested 
option, similar to custom brace wrapping, so that the "basic" namespace option 
is not poluted, but further customization can be defined in a nested "advanced" 
option.


Repository:
  rC Clang

https://reviews.llvm.org/D42787



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


[PATCH] D47394: [OpenMP][Clang][NVPTX] Replace bundling with partial linking for the OpenMP NVPTX device offloading toolchain

2018-06-12 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 150947.
gtbercea added a comment.

Added separate test.


Repository:
  rC Clang

https://reviews.llvm.org/D47394

Files:
  include/clang/Driver/Action.h
  include/clang/Driver/Compilation.h
  include/clang/Driver/Driver.h
  include/clang/Driver/Options.td
  include/clang/Driver/ToolChain.h
  lib/Driver/Action.cpp
  lib/Driver/Compilation.cpp
  lib/Driver/Driver.cpp
  lib/Driver/ToolChain.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/Clang.h
  lib/Driver/ToolChains/Cuda.cpp
  test/Driver/openmp-offload-gpu-linux.c
  test/Driver/openmp-offload-gpu.c
  test/Driver/openmp-offload.c

Index: test/Driver/openmp-offload.c
===
--- test/Driver/openmp-offload.c
+++ test/Driver/openmp-offload.c
@@ -480,13 +480,13 @@
 // Create host object and bundle.
 // CHK-BUJOBS: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-emit-obj" {{.*}}"-fopenmp" {{.*}}"-o" "
 // CHK-BUJOBS-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "-x" "ir" "{{.*}}[[HOSTBC]]"
-// CHK-BUJOBS: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs=
+// CHK-BUJOBS: clang-offload-bundler{{.*}}" "-type=o"{{.*}}"-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs=
 // CHK-BUJOBS-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]"
 // CHK-BUJOBS-ST: clang{{.*}}" "-cc1" "-triple" "powerpc64le--linux" "-S" {{.*}}"-fopenmp" {{.*}}"-o" "
 // CHK-BUJOBS-ST-SAME: [[HOSTASM:[^\\/]+\.s]]" "-x" "ir" "{{.*}}[[HOSTBC]]"
 // CHK-BUJOBS-ST: clang{{.*}}" "-cc1as" "-triple" "powerpc64le--linux" "-filetype" "obj" {{.*}}"-o" "
 // CHK-BUJOBS-ST-SAME: [[HOSTOBJ:[^\\/]+\.o]]" "{{.*}}[[HOSTASM]]"
-// CHK-BUJOBS-ST: clang-offload-bundler{{.*}}" "-type=o" "-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs=
+// CHK-BUJOBS-ST: clang-offload-bundler{{.*}}" "-type=o"{{.*}}"-targets=openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu,host-powerpc64le--linux" "-outputs=
 // CHK-BUJOBS-ST-SAME: [[RES:[^\\/]+\.o]]" "-inputs={{.*}}[[T1OBJ]],{{.*}}[[T2OBJ]],{{.*}}[[HOSTOBJ]]"
 
 /// ###
Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -61,7 +61,7 @@
 
 /// Check cubin file generation and bundling
 // RUN:   %clang -### -target powerpc64le-unknown-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
-// RUN:  -no-canonical-prefixes -save-temps %s -c 2>&1 \
+// RUN:  -no-canonical-prefixes -save-temps %s -c -fopenmp-use-target-bundling 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-PTXAS-CUBIN-BUNDLING %s
 
 // CHK-PTXAS-CUBIN-BUNDLING: clang{{.*}}" "-o" "[[PTX:.*\.s]]"
@@ -73,7 +73,7 @@
 /// Check cubin file unbundling and usage by nvlink
 // RUN:   touch %t.o
 // RUN:   %clang -### -target powerpc64le-unknown-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda \
-// RUN:  -no-canonical-prefixes -save-temps %t.o 2>&1 \
+// RUN:  -no-canonical-prefixes -save-temps %t.o -fopenmp-use-target-bundling 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-CUBIN-UNBUNDLING-NVLINK %s
 
 /// Use DAG to ensure that cubin file has been unbundled.
@@ -87,11 +87,11 @@
 // RUN:   touch %t1.o
 // RUN:   touch %t2.o
 // RUN:   %clang -### -no-canonical-prefixes -target powerpc64le-unknown-linux-gnu -fopenmp=libomp \
-// RUN:  -fopenmp-targets=nvptx64-nvidia-cuda %t1.o %t2.o 2>&1 \
+// RUN:  -fopenmp-targets=nvptx64-nvidia-cuda %t1.o %t2.o -fopenmp-use-target-bundling 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-TWOCUBIN %s
 /// Check cubin file generation and usage by nvlink when toolchain has BindArchAction
 // RUN:   %clang -### -no-canonical-prefixes -target x86_64-apple-darwin17.0.0 -fopenmp=libomp \
-// RUN:  -fopenmp-targets=nvptx64-nvidia-cuda %t1.o %t2.o 2>&1 \
+// RUN:  -fopenmp-targets=nvptx64-nvidia-cuda %t1.o %t2.o -fopenmp-use-target-bundling 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-TWOCUBIN %s
 
 // CHK-TWOCUBIN: nvlink{{.*}}openmp-offload-{{.*}}.cubin" "{{.*}}openmp-offload-{{.*}}.cubin"
Index: test/Driver/openmp-offload-gpu-linux.c
===
--- /dev/null
+++ test/Driver/openmp-offload-gpu-linux.c
@@ -0,0 +1,52 @@
+///
+/// Perform driver tests for OpenMP offloading on Linux systems
+///
+
+// UNSUPPORTED: system-windows
+
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: powerpc-registered-target
+// REQUIRES: nvptx-registered-target
+
+/// Check cubin file generation and partial linking with ld
+// RUN:   %clang -### -target powerpc64le-unknown-linux-gnu -fopenmp=libomp -fo

[PATCH] D46915: [Fixed Point Arithmetic] Fixed Point Precision Bits and Fixed Point Literals

2018-06-12 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added inline comments.



Comment at: include/clang/Basic/TargetInfo.h:89
+  // corresponding unsaturated types.
+  unsigned char ShortAccumFBits, ShortAccumIBits;
+  unsigned char AccumFBits, AccumIBits;

leonardchan wrote:
> ebevhan wrote:
> > I suspect it's still possible to calculate the ibits based on the fbits, 
> > even for _Accum.
> > 
> > Are the unsigned values needed? The fbits for unsigned _Fract are the same 
> > as for signed _Fract if SameFBits is set, and +1 otherwise. The same should 
> > go for unsigned _Accum, but I don't think it's entirely clear how this 
> > affects the integral part.
> Similar to the previous comment, if we choose to make SameFBits dependent 
> on/controlled by the target, then I think it would be better for the target 
> to explicitly specify the integral bits since there could be some cases where 
> there may be padding (such as for unsigned _Accum types if this flag is set), 
> and in this case, I think it should be explicit that the `bit_width != IBits 
> + FBits`.
> 
> We also can't fill in that padding for the unsigned _Accum types as an extra 
> integral bit since the standard says that `"each signed accum type has at 
> least as many integral bits as its corresponding unsigned accum type".`
> 
> For the unsigned _Fract values, I think we can get rid of them if we choose 
> to keep the flag instead, but it would no longer apply to unsigned _Accum 
> types since it would allow for extra padding in these types and would 
> conflict with the logic of `bit_width == IBits + FBits`
> 
> For now, I actually think the simplest option is to keep these target 
> properties, but have the target override them individually, with checks to 
> make sure the values adhere to the standard.
Is it not the case that `bitwidth != IBits + FBits` for signed types only? 
Signed types require a sign bit (which is neither a fractional bit nor an 
integral bit, according to spec) but unsigned types do not, and if IBits and 
FBits for the signed and unsigned types are the same, the MSB is simply a 
padding bit, at least for _Accum (for _Fract everything above the fbits is 
padding). 

My reasoning for keeping the number of configurable values down was to limit 
the number of twiddly knobs to make the implementation simpler. Granting a lot 
of freedom is nice, but I suspect that it will be quite hard to get the 
implementation working properly for every valid configuration. I also don't 
really see much of a reason for `FBits != UFBits` in general. I know the spec 
gives a recommendation to implement it that way, but I think the benefit of 
normalizing the signed and unsigned representations outweighs the lost bit in 
the unsigned type.

It's hard to say what the differences are beyond that since I'm not sure how 
you plan on treating padding bits. In our implementation, padding bits (the MSB 
in all of the unsigned types for us) after any operation are zeroed.



Comment at: lib/Basic/TargetInfo.cpp:797
+  // corresponding unsigned accum type.
+  assert(ShortAccumIBits == UnsignedShortAccumIBits ||
+ ShortAccumIBits == UnsignedShortAccumIBits - 1);

Shouldn't these be `ShortAccumIBits >= UnsignedShortAccumIBits` etc.?



Comment at: lib/Lex/LiteralSupport.cpp:737
+  if (!hadError && saw_fixed_point_suffix) {
+assert(isFract || isAccum);
+assert(radix == 16 || radix == 10);

Is `saw_fixed_point_suffix` only used for this assertion? Doesn't `isFract || 
isAccum` imply `saw_fixed_point_suffix`?



Comment at: lib/Lex/LiteralSupport.cpp:1049
+
+bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned 
Scale) {
+  assert(radix == 16 || radix == 10);

The function does a lot of overflow checks that I think are superfluous if the 
required bits are calculated properly. The only overflow check that should be 
needed is the one at the very bottom that truncates the APInt to the final size.



Comment at: lib/Lex/LiteralSupport.cpp:1065
+
+while (!IsExponentPart(*Ptr)) ++Ptr;
+++Ptr;

This whole block is very diligent but I wonder how common overflow in the 
exponent is.

I'm unsure if LLVM has a helper function with `atoll`-like functionality, but 
if it does it's a lot less code to just use that instead. There's also APInt's 
`fromString`, but that seems to assert if the integer doesn't fit in the 
bitwidth. The required bitwidth can be calculated here, though.



Comment at: lib/Lex/LiteralSupport.cpp:1085
+
+  if (radix == 10) {
+// Number of bits needed for decimal literal is

These two calculations look very similar to me. The only difference seems to be 
that the exponent is multiplied by 4 in the decimal case, and not in the 
hexadecimal case.



Comment at: lib/Lex/LiteralSupport.cpp:1141
+}
+if ((radix == 16 && (*Ptr ==

[PATCH] D34156: [LTO] Enable module summary emission by default for regular LTO

2018-06-12 Thread Tobias Edler von Koch via Phabricator via cfe-commits
tobiasvk updated this revision to Diff 150965.
tobiasvk added a comment.

- Rebase for current tree
- Fix -flto -save-temps which the previous patch broke


https://reviews.llvm.org/D34156

Files:
  clang/include/clang/Frontend/CodeGenOptions.def
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/emit-summary-index.c
  clang/test/Misc/thinlto.c

Index: clang/test/Misc/thinlto.c
===
--- clang/test/Misc/thinlto.c
+++ /dev/null
@@ -1,4 +0,0 @@
-// RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-bcanalyzer -dump | FileCheck %s
-// ; Check that the -flto=thin option emits a summary
-// CHECK: getValue();
 if (S == "thin")
-  Opts.EmitSummaryIndex = true;
+  Opts.PrepareForThinLTO = true;
 else if (S != "full")
   Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
   }
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -578,7 +578,7 @@
   CSInfo,
   getSource(SM, SM.getMainFileID())),
   CGOpts.EmitVersionIdentMetadata ? Producer : "",
-  LO.Optimize || CGOpts.PrepareForLTO || CGOpts.EmitSummaryIndex,
+  LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
   CGOpts.DwarfDebugFlags, RuntimeVers,
   CGOpts.EnableSplitDwarf ? "" : CGOpts.SplitDwarfFile, EmissionKind,
   0 /* DWOid */, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -524,7 +524,7 @@
 PMBuilder.Inliner = createFunctionInliningPass(
 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
 (!CodeGenOpts.SampleProfileFile.empty() &&
- CodeGenOpts.EmitSummaryIndex));
+ CodeGenOpts.PrepareForThinLTO));
   }
 
   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
@@ -534,7 +534,7 @@
 
   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
-  PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
+  PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
 
@@ -771,12 +771,20 @@
 
   std::unique_ptr ThinLinkOS, DwoOS;
 
+  // Emit a module summary by default for Regular LTO except for ld64 targets
+  bool EmitLTOSummary =
+  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.PrepareForThinLTO &&
+   llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
+   llvm::Triple::Apple);
+  if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
+TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
+
   switch (Action) {
   case Backend_EmitNothing:
 break;
 
   case Backend_EmitBC:
-if (CodeGenOpts.EmitSummaryIndex) {
+if (CodeGenOpts.PrepareForThinLTO) {
   if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
 if (!ThinLinkOS)
@@ -787,7 +795,8 @@
 }
 else
   PerModulePasses.add(
-  createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
+  createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
+  EmitLTOSummary));
 break;
 
   case Backend_EmitLL:
@@ -935,7 +944,7 @@
   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
 
   if (!CodeGenOpts.DisableLLVMPasses) {
-bool IsThinLTO = CodeGenOpts.EmitSummaryIndex;
+bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
 bool IsLTO = CodeGenOpts.PrepareForLTO;
 
 if (CodeGenOpts.OptimizationLevel == 0) {
@@ -984,6 +993,14 @@
 }
   }
 
+  // Emit a module summary by default for Regular LTO except for ld64 targets
+  bool EmitLTOSummary =
+  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.PrepareForThinLTO &&
+   llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
+   llvm::Triple::Apple);
+  if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
+TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
+
   // FIXME: We still use the legacy pass manager to do code generation. We
   // create that pass manager here and use it as needed below.
   legacy::PassManager CodeGenPasses;
@@ -996,7 +1013,7 @@
 break;
 
   case Backend_EmitBC:
-if (CodeGenOpts.EmitSummaryIndex) {
+if (CodeGenOpts.PrepareForThinLTO) {
   if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
 if (!ThinLinkOS)
@@ -1006,8 +1023,7 @@
: nullptr));

[PATCH] D47435: Add __builtin_signbit semantic checking

2018-06-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 150967.
aaron.ballman marked 5 inline comments as done.
aaron.ballman added a comment.

Updating based on review feedback.


https://reviews.llvm.org/D47435

Files:
  lib/Sema/SemaChecking.cpp
  test/Sema/builtins.c


Index: test/Sema/builtins.c
===
--- test/Sema/builtins.c
+++ test/Sema/builtins.c
@@ -253,3 +253,26 @@
   __sync_fetch_and_add(ptr, 1); // expected-error{{address argument to atomic 
builtin cannot be const-qualified ('const int *' invalid)}}
   __atomic_fetch_add(ptr, 1, 0);  // expected-error {{address argument to 
atomic operation must be a pointer to non-const type ('const int *' invalid)}}
 }
+
+void test22(void) {
+  (void)__builtin_signbit(); // expected-error{{too few arguments to function 
call, expected 1, have 0}}
+  (void)__builtin_signbit(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbit(1); // expected-error {{floating point 
classification requires argument of floating point type (passed in 'int')}}
+  (void)__builtin_signbit(1.0);
+  (void)__builtin_signbit(1.0f);
+  (void)__builtin_signbit(1.0L);
+
+  (void)__builtin_signbitf(); // expected-error{{too few arguments to function 
call, expected 1, have 0}}
+  (void)__builtin_signbitf(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbitf(1);
+  (void)__builtin_signbitf(1.0);
+  (void)__builtin_signbitf(1.0f);
+  (void)__builtin_signbitf(1.0L);
+
+  (void)__builtin_signbitl(); // expected-error{{too few arguments to function 
call, expected 1, have 0}}
+  (void)__builtin_signbitl(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbitl(1);
+  (void)__builtin_signbitl(1.0);
+  (void)__builtin_signbitl(1.0f);
+  (void)__builtin_signbitl(1.0L);
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -960,6 +960,9 @@
   case Builtin::BI__builtin_isinf_sign:
   case Builtin::BI__builtin_isnan:
   case Builtin::BI__builtin_isnormal:
+  case Builtin::BI__builtin_signbit:
+  case Builtin::BI__builtin_signbitf:
+  case Builtin::BI__builtin_signbitl:
 if (SemaBuiltinFPClassification(TheCall, 1))
   return ExprError();
 break;
@@ -4574,15 +4577,19 @@
 diag::err_typecheck_call_invalid_unary_fp)
   << OrigArg->getType() << OrigArg->getSourceRange();
 
-  // If this is an implicit conversion from float -> float or double, remove 
it.
+  // If this is an implicit conversion from float -> float, double, or
+  // long double, remove it.
   if (ImplicitCastExpr *Cast = dyn_cast(OrigArg)) {
 // Only remove standard FloatCasts, leaving other casts inplace
 if (Cast->getCastKind() == CK_FloatingCast) {
   Expr *CastArg = Cast->getSubExpr();
   if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
-  assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) 
||
-  Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) 
&&
-   "promotion from float to either float or double is the only 
expected cast here");
+assert(
+(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
+ Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
+ Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) 
&&
+"promotion from float to either float, double, or long double is "
+"the only expected cast here");
 Cast->setSubExpr(nullptr);
 TheCall->setArg(NumArgs-1, CastArg);
   }


Index: test/Sema/builtins.c
===
--- test/Sema/builtins.c
+++ test/Sema/builtins.c
@@ -253,3 +253,26 @@
   __sync_fetch_and_add(ptr, 1); // expected-error{{address argument to atomic builtin cannot be const-qualified ('const int *' invalid)}}
   __atomic_fetch_add(ptr, 1, 0);  // expected-error {{address argument to atomic operation must be a pointer to non-const type ('const int *' invalid)}}
 }
+
+void test22(void) {
+  (void)__builtin_signbit(); // expected-error{{too few arguments to function call, expected 1, have 0}}
+  (void)__builtin_signbit(1.0, 2.0, 3.0); // expected-error{{too many arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbit(1); // expected-error {{floating point classification requires argument of floating point type (passed in 'int')}}
+  (void)__builtin_signbit(1.0);
+  (void)__builtin_signbit(1.0f);
+  (void)__builtin_signbit(1.0L);
+
+  (void)__builtin_signbitf(); // expected-error{{too few arguments to function call, expected 1, have 0}}
+  (void)__builtin_signbitf(1.0, 2.0, 3.0); // expected-error{{too many arguments to function call, expected 1, ha

[PATCH] D47435: Add __builtin_signbit semantic checking

2018-06-12 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:925
+  case Builtin::BI__builtin_signbitl:
 if (SemaBuiltinFPClassification(TheCall, 1))
   return ExprError();

lebedev.ri wrote:
> The name of the function is unfortunate given that you call it for 
> `__builtin_signbit(int)`.
signbit() is an FP classification macro (see C17 7.12.3 "Classification 
macros"), so I don't think the name is unfortunate.



Comment at: test/Sema/builtins.c:260
+  (void)__builtin_signbit(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbit(1); // expected-error {{floating point 
classification requires argument of floating point type (passed in 'int')}}
+

lebedev.ri wrote:
> lebedev.ri wrote:
> > What about
> > ```
> > (void)__builtin_signbit(1.0);
> > ```
> Hm, is `__builtin_signbit()` taking an integer, or float?
> If integer, the comment about `floating point classification` is slightly 
> misleading.
> 
It accepts a floating-point type.



Comment at: test/Sema/builtins.c:268
+  (void)__builtin_signbitl(1.0, 2.0, 3.0); // expected-error{{too many 
arguments to function call, expected 1, have 3}}
+  (void)__builtin_signbitl(1);
+}

lebedev.ri wrote:
> Same, would be good to see `__builtin_signbitf(1.0);`, 
> `__builtin_signbitf(1.0L);`.
It turns out that double and long double were fine, but the promotion from 
float for this case was a problem. I fixed that as well.


https://reviews.llvm.org/D47435



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


[PATCH] D47435: Add __builtin_signbit semantic checking

2018-06-12 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri accepted this revision.
lebedev.ri added a comment.
This revision is now accepted and ready to land.

Looks good to me, but you probably want a bit for a second opinion.


https://reviews.llvm.org/D47435



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


[PATCH] D47233: [CodeGen] Emit MSVC RTTI for Obj-C EH types

2018-06-12 Thread Dustin L. Howett via Phabricator via cfe-commits
DHowett-MSFT added a comment.

In https://reviews.llvm.org/D47233#1129207, @rjmccall wrote:

> In https://reviews.llvm.org/D47233#1129110, @smeenai wrote:
>
> > WinObjC does this wrapping, for example.
>
>
> I see.  The idea of creating the type descriptors and mangled names ad-hoc 
> for the catchable-types array is clever, and it's nice that the ABI is 
> defined in a way that makes that work.  (Expensive, but hey, it's the 
> exceptions path.)


We ran into some critical issues with this approach on x64. The pointers in the 
exception record are supposed to be image-relative instead of absolute, so I 
tried to make them absolute to libobjc2's load address, but I never quite 
solved it.

A slightly better-documented and cleaner version of the code you linked is here 
.


Repository:
  rC Clang

https://reviews.llvm.org/D47233



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


[PATCH] D42787: clang-format: do not add extra indent when wrapping last parameter

2018-06-12 Thread Daniel Jasper via Phabricator via cfe-commits
djasper added a comment.

You are right that this behavior is what the code authors, but also many other 
people, like to have and so it is what is engrained in clang-format. There are 
likely about a million things that fall into the same category. Now we might 
find that the current default is actually wrong and we have changed many 
defaults in the past. I don't believe that's the case here and there are more 
opinions on this thread.

If people still disagree, there is the question of whether a flag should be 
introduced, and for every single flag that was introduced, somebody did not 
agree with what clang-format was doing. We have established the bar that has to 
be met in order for the cost-benefit-ratio of options to be beneficial. I don't 
see any reason to make an exception here. The fact that it is a rare corner 
case makes it less likely to be important enough to carry the weight of an 
option. Creating a second option class (nested, hidden, ...) does not seem to 
improve the situation to me. That will just create a subsequent mass of 
additional flags that people have wanted in the past or will want in the future 
that don't actually carry their weight (in my opinion - and likely speaking for 
most other clang-format contributors). Discoverability is only one of the 
concerns about the costs of flags.

So in short, unless you can actually meet the usual requirements for flags, the 
answer is: no.


Repository:
  rC Clang

https://reviews.llvm.org/D42787



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


[PATCH] D48083: [clangd] Boost keyword completions.

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

These have few signals other than being keywords, so the boost is high.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48083

Files:
  clangd/Quality.cpp
  clangd/Quality.h
  unittests/clangd/QualityTests.cpp

Index: unittests/clangd/QualityTests.cpp
===
--- unittests/clangd/QualityTests.cpp
+++ unittests/clangd/QualityTests.cpp
@@ -58,6 +58,10 @@
   EXPECT_FALSE(Quality.ReservedName);
   EXPECT_EQ(Quality.References, SymbolQualitySignals().References);
   EXPECT_EQ(Quality.Category, SymbolQualitySignals::Function);
+
+  Quality = {};
+  Quality.merge(CodeCompletionResult("if"));
+  EXPECT_EQ(Quality.Category, SymbolQualitySignals::Keyword);
 }
 
 TEST(QualityTests, SymbolRelevanceSignalExtraction) {
@@ -125,10 +129,12 @@
   EXPECT_GT(WithReferences.evaluate(), Default.evaluate());
   EXPECT_GT(ManyReferences.evaluate(), WithReferences.evaluate());
 
-  SymbolQualitySignals Variable, Macro;
+  SymbolQualitySignals Keyword, Variable, Macro;
+  Keyword.Category = SymbolQualitySignals::Keyword;
   Variable.Category = SymbolQualitySignals::Variable;
   Macro.Category = SymbolQualitySignals::Macro;
   EXPECT_GT(Variable.evaluate(), Default.evaluate());
+  EXPECT_GT(Keyword.evaluate(), Variable.evaluate());
   EXPECT_LT(Macro.evaluate(), Default.evaluate());
 }
 
Index: clangd/Quality.h
===
--- clangd/Quality.h
+++ clangd/Quality.h
@@ -50,12 +50,13 @@
   unsigned References = 0;
 
   enum SymbolCategory {
+Unknown = 0,
 Variable,
 Macro,
 Type,
 Function,
 Namespace,
-Unknown,
+Keyword,
   } Category = Unknown;
 
   void merge(const CodeCompletionResult &SemaCCResult);
Index: clangd/Quality.cpp
===
--- clangd/Quality.cpp
+++ clangd/Quality.cpp
@@ -59,6 +59,29 @@
   return Switch().Visit(&ND);
 }
 
+static SymbolQualitySignals::SymbolCategory categorize(const CodeCompletionResult &R) {
+  if (R.Declaration)
+return categorize(*R.Declaration);
+  if (R.Kind == CodeCompletionResult::RK_Macro)
+return SymbolQualitySignals::Macro;
+  // Everything else is a keyword or a pattern. Patterns are mostly keywords
+  // too, except a few which we recognize by cursor kind.
+  switch (R.CursorKind) {
+case CXCursor_CXXMethod:
+  return SymbolQualitySignals::Function;
+case CXCursor_ModuleImportDecl:
+  return SymbolQualitySignals::Namespace;
+case CXCursor_MacroDefinition:
+  return SymbolQualitySignals::Macro;
+case CXCursor_TypeRef:
+  return SymbolQualitySignals::Type;
+case CXCursor_MemberRef:
+  return SymbolQualitySignals::Variable;
+default:
+  return SymbolQualitySignals::Keyword;
+  }
+}
+
 static SymbolQualitySignals::SymbolCategory
 categorize(const index::SymbolInfo &D) {
   switch (D.Kind) {
@@ -103,10 +126,7 @@
   if (SemaCCResult.Availability == CXAvailability_Deprecated)
 Deprecated = true;
 
-  if (SemaCCResult.Declaration)
-Category = categorize(*SemaCCResult.Declaration);
-  else if (SemaCCResult.Kind == CodeCompletionResult::RK_Macro)
-Category = Macro;
+  Category = categorize(SemaCCResult);
 
   if (SemaCCResult.Declaration) {
 if (auto *ID = SemaCCResult.Declaration->getIdentifier())
@@ -135,6 +155,9 @@
 Score *= 0.1f;
 
   switch (Category) {
+case Keyword:  // Usually relevant, but misses most signals.
+  Score *= 10;
+  break;
 case Type:
 case Function:
 case Variable:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48063: [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: lib/Format/TokenAnnotator.cpp:3104
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
 if ((Style.Language == FormatStyle::LK_Proto ||
  Style.Language == FormatStyle::LK_TextProto) &&

It's really hard to follow the boolean logic here.
Can you break this up into multiple if statements with comments, or extract 
some named subexpressions or something? e.g. 
```
if (proto or textproto) {
  if (bool isSubmessage = ...)
return false;
  if (right is string && !break before multiline)
return false;
  return true;
}


Repository:
  rC Clang

https://reviews.llvm.org/D48063



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


[PATCH] D46024: [clang-format] Add SpaceBeforeCpp11BracedList option.

2018-06-12 Thread Manuel Klimek via Phabricator via cfe-commits
klimek accepted this revision.
klimek added a comment.

In https://reviews.llvm.org/D46024#1129350, @hans wrote:

> In https://reviews.llvm.org/D46024#1121242, @rkirsling wrote:
>
> > FWIW, please note that this space-before-brace style is not specific to 
> > WebKit; CppCoreGuidelines exhibits it as well:
> >  
> > http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es23-prefer-the--initializer-syntax
>
>
> This and WebKit's style seem like compelling arguments to support this option.
>
> klimek, djasper: Do you have any objections against landing this?


Agreed.
Generally LG minus that I'd significantly reduce the number of test cases :)




Comment at: unittests/Format/FormatTest.cpp:6980
ExtraSpaces);
+
+  FormatStyle SpaceBeforeBrace = getLLVMStyle();

There are super many redundant test cases here - I don't think we need to test 
that brace init detection works here, again.
I think given the code change we basically need 2 tests:
one where the previous opens a scope, and one where it doesn't.


Repository:
  rC Clang

https://reviews.llvm.org/D46024



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


[PATCH] D48063: [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 150980.
krasimir added a comment.

- Split-up the if-condition


Repository:
  rC Clang

https://reviews.llvm.org/D48063

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestProto.cpp
  unittests/Format/FormatTestTextProto.cpp

Index: unittests/Format/FormatTestTextProto.cpp
===
--- unittests/Format/FormatTestTextProto.cpp
+++ unittests/Format/FormatTestTextProto.cpp
@@ -485,8 +485,15 @@
   verifyFormat("keys: []");
   verifyFormat("keys: [ 1 ]");
   verifyFormat("keys: [ 'ala', 'bala' ]");
-  verifyFormat("keys:\n"
-   "[ 'ala', 'bala', 'porto', 'kala', 'too', 'long', 'ng' ]");
+  verifyFormat("keys: [\n"
+   "  'ala',\n"
+   "  'bala',\n"
+   "  'porto',\n"
+   "  'kala',\n"
+   "  'too',\n"
+   "  'long',\n"
+   "  'ng'\n"
+   "]");
   verifyFormat("key: item\n"
"keys: [\n"
"  'ala',\n"
@@ -670,5 +677,28 @@
"}");
 }
 
+TEST_F(FormatTestTextProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("submessage: {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage: <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("repeatedd: [\n"
+   "  'ey'\n"
+   "]");
+  // "{" is going over the column limit.
+  verifyFormat(
+  "submessagee: {\n"
+  "  key: 'a'\n"
+  "}");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: unittests/Format/FormatTestProto.cpp
===
--- unittests/Format/FormatTestProto.cpp
+++ unittests/Format/FormatTestProto.cpp
@@ -624,5 +624,34 @@
"}");
 }
 
+TEST_F(FormatTestProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  repeatedd: [\n"
+   "'ey'\n"
+   "  ]\n"
+   "}");
+}
+
+
 } // end namespace tooling
 } // end namespace clang
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -3101,10 +3101,39 @@
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
-  return false;
+if (Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto) {
+  if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+return false;
+  // Prevent cases like:
+  //
+  // submessage:
+  // { key: valu }
+  //
+  // when the snippet does not fit into one line.
+  // Prefer:
+  //
+  // submessage: {
+  //   key: valu
+  // }
+  //
+  // instead, even if it is longer by one line.
+  //
+  // Note that this allows allows the "{" to go over the column limit
+  // when the column limit is just between ":" and "{", but that does
+  // not happen too often and alternative formattings in this case are
+  // not much better.
+  //
+  // The code covers the cases:
+  //
+  // submessage: { ... }
+  // submessage: < ... >
+  // repeated: [ ... ]
+  

r334517 - [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jun 12 10:26:31 2018
New Revision: 334517

URL: http://llvm.org/viewvc/llvm-project?rev=334517&view=rev
Log:
[clang-format] Discourage breaks in submessage entries, hard rule

Summary:
Currently clang-format allows this for text protos:
```
submessage:
{ key: 'aa' }
```
when it is under the column limit and when putting it all on one line exceeds 
the column limit.

This is not a very intuitive formatting, so I'd prefer having
```
submessage: {
  key: 'aa'
}
```
instead, even if it takes one line more.

This patch prevents clang-format from inserting a break between `: {` and 
similar cases.

Reviewers: djasper, sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=334517&r1=334516&r2=334517&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Jun 12 10:26:31 2018
@@ -3101,10 +3101,39 @@ bool TokenAnnotator::canBreakBefore(cons
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
-  return false;
+if (Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto) {
+  if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+return false;
+  // Prevent cases like:
+  //
+  // submessage:
+  // { key: valu }
+  //
+  // when the snippet does not fit into one line.
+  // Prefer:
+  //
+  // submessage: {
+  //   key: valu
+  // }
+  //
+  // instead, even if it is longer by one line.
+  //
+  // Note that this allows allows the "{" to go over the column limit
+  // when the column limit is just between ":" and "{", but that does
+  // not happen too often and alternative formattings in this case are
+  // not much better.
+  //
+  // The code covers the cases:
+  //
+  // submessage: { ... }
+  // submessage: < ... >
+  // repeated: [ ... ]
+  if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
+   Right.is(TT_DictLiteral)) ||
+  Right.is(TT_ArrayInitializerLSquare))
+return false;
+}
 return true;
   }
   if (Right.is(tok::r_square) && Right.MatchingParen &&

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=334517&r1=334516&r2=334517&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Tue Jun 12 10:26:31 2018
@@ -624,5 +624,34 @@ TEST_F(FormatTestProto, BreaksEntriesOfS
"}");
 }
 
+TEST_F(FormatTestProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  repeatedd: [\n"
+   "'ey'\n"
+   "  ]\n"
+   "}");
+}
+
+
 } // end namespace tooling
 } // end namespace clang

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=334517&r1=334516&r2=334517&view=diff
==
--- cfe/trunk/unittests/Format/Format

[PATCH] D48063: [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL334517: [clang-format] Discourage breaks in submessage 
entries, hard rule (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D48063

Files:
  cfe/trunk/lib/Format/TokenAnnotator.cpp
  cfe/trunk/unittests/Format/FormatTestProto.cpp
  cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -3101,10 +3101,39 @@
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
-  return false;
+if (Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto) {
+  if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+return false;
+  // Prevent cases like:
+  //
+  // submessage:
+  // { key: valu }
+  //
+  // when the snippet does not fit into one line.
+  // Prefer:
+  //
+  // submessage: {
+  //   key: valu
+  // }
+  //
+  // instead, even if it is longer by one line.
+  //
+  // Note that this allows allows the "{" to go over the column limit
+  // when the column limit is just between ":" and "{", but that does
+  // not happen too often and alternative formattings in this case are
+  // not much better.
+  //
+  // The code covers the cases:
+  //
+  // submessage: { ... }
+  // submessage: < ... >
+  // repeated: [ ... ]
+  if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
+   Right.is(TT_DictLiteral)) ||
+  Right.is(TT_ArrayInitializerLSquare))
+return false;
+}
 return true;
   }
   if (Right.is(tok::r_square) && Right.MatchingParen &&
Index: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
===
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp
@@ -485,8 +485,15 @@
   verifyFormat("keys: []");
   verifyFormat("keys: [ 1 ]");
   verifyFormat("keys: [ 'ala', 'bala' ]");
-  verifyFormat("keys:\n"
-   "[ 'ala', 'bala', 'porto', 'kala', 'too', 'long', 'ng' ]");
+  verifyFormat("keys: [\n"
+   "  'ala',\n"
+   "  'bala',\n"
+   "  'porto',\n"
+   "  'kala',\n"
+   "  'too',\n"
+   "  'long',\n"
+   "  'ng'\n"
+   "]");
   verifyFormat("key: item\n"
"keys: [\n"
"  'ala',\n"
@@ -670,5 +677,28 @@
"}");
 }
 
+TEST_F(FormatTestTextProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("submessage: {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage {\n"
+   "  key: 'a'\n"
+   "}");
+  verifyFormat("submessage: <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("submessage <\n"
+   "  key: 'a'\n"
+   ">");
+  verifyFormat("repeatedd: [\n"
+   "  'ey'\n"
+   "]");
+  // "{" is going over the column limit.
+  verifyFormat(
+  "submessagee: {\n"
+  "  key: 'a'\n"
+  "}");
+}
+
 } // end namespace tooling
 } // end namespace clang
Index: cfe/trunk/unittests/Format/FormatTestProto.cpp
===
--- cfe/trunk/unittests/Format/FormatTestProto.cpp
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp
@@ -624,5 +624,34 @@
"}");
 }
 
+TEST_F(FormatTestProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: <\n"
+   "key: 'a'\n"
+

[PATCH] D47958: [CUDA][HIP] Allow CUDA __global__ functions to have amdgpu kernel attributes

2018-06-12 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

Thank you.


https://reviews.llvm.org/D47958



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


[PATCH] D48068: [clangd] Move caching of compile args out of ClangdServer.

2018-06-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clangd/GlobalCompilationDatabase.cpp:137
+  // 'It' may be invalid at this point, recompute it.
+  It = Cached.find(File);
+  if (It != Cached.end())

`return try_emplace(File, std::move(Command)).second`?

(This has different behavior if the cache was filled while you unlocked, but 
it's arguably the right behavior and doesn't really matter).



Comment at: clangd/GlobalCompilationDatabase.h:93
+public:
+  explicit CachingCompilationDb(GlobalCompilationDatabase &InnerCDB);
+

const ref


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D48068



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


r334518 - Refactor ExecuteAndWait to take StringRefs.

2018-06-12 Thread Zachary Turner via cfe-commits
Author: zturner
Date: Tue Jun 12 10:43:52 2018
New Revision: 334518

URL: http://llvm.org/viewvc/llvm-project?rev=334518&view=rev
Log:
Refactor ExecuteAndWait to take StringRefs.

This simplifies some code which had StringRefs to begin with, and
makes other code more complicated which had const char* to begin
with.

In the end, I think this makes for a more idiomatic and platform
agnostic API.  Not all platforms launch process with null terminated
c-string arrays for the environment pointer and argv, but the api
was designed that way because it allowed easy pass-through for
posix-based platforms.  There's a little additional overhead now
since on posix based platforms we'll be takign StringRefs which
were constructed from null terminated strings and then copying
them to null terminate them again, but from a readability and
usability standpoint of the API user, I think this API signature
is strictly better.

Modified:
cfe/trunk/lib/Driver/Job.cpp
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Modified: cfe/trunk/lib/Driver/Job.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Job.cpp?rev=334518&r1=334517&r2=334518&view=diff
==
--- cfe/trunk/lib/Driver/Job.cpp (original)
+++ cfe/trunk/lib/Driver/Job.cpp Tue Jun 12 10:43:52 2018
@@ -317,13 +317,11 @@ int Command::Execute(ArrayRef Argv;
 
-  const char **Envp;
-  if (Environment.empty()) {
-Envp = nullptr;
-  } else {
+  Optional> Env;
+  if (!Environment.empty()) {
 assert(Environment.back() == nullptr &&
"Environment vector should be null-terminated by now");
-Envp = const_cast(Environment.data());
+Env = llvm::toStringRefArray(Environment.data());
   }
 
   if (ResponseFile == nullptr) {
@@ -331,8 +329,9 @@ int Command::Execute(ArrayRefhttp://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp?rev=334518&r1=334517&r2=334518&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp Tue Jun 12 
10:43:52 2018
@@ -883,9 +883,9 @@ UbigraphViz::~UbigraphViz() {
   std::string Ubiviz;
   if (auto Path = llvm::sys::findProgramByName("ubiviz"))
 Ubiviz = *Path;
-  const char *args[] = {Ubiviz.c_str(), Filename.c_str(), nullptr};
+  std::array Args = {Ubiviz, Filename};
 
-  if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], nullptr, {}, 0, 0, &ErrMsg)) 
{
+  if (llvm::sys::ExecuteAndWait(Ubiviz, Args, llvm::None, {}, 0, 0, &ErrMsg)) {
 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";
   }
 

Modified: cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp?rev=334518&r1=334517&r2=334518&view=diff
==
--- cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp (original)
+++ cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp Tue Jun 12 
10:43:52 2018
@@ -536,23 +536,22 @@ public:
 // close it and use the name to pass down to clang.
 OS.close();
 SmallString<128> TargetName = getTriple(TargetNames[HostInputIndex]);
-const char *ClangArgs[] = {"clang",
-   "-r",
-   "-target",
-   TargetName.c_str(),
-   "-o",
-   OutputFileNames.front().c_str(),
-   InputFileNames[HostInputIndex].c_str(),
-   BitcodeFileName.c_str(),
-   "-nostdlib",
-   nullptr};
+std::vector ClangArgs = {"clang",
+"-r",
+"-target",
+TargetName.c_str(),
+"-o",
+OutputFileNames.front().c_str(),
+InputFileNames[HostInputIndex].c_str(),
+BitcodeFileName.c_str(),
+"-nostdlib"};
 
 // If the user asked for the commands to be printed out, we do that instead
 // of executing it.
 if (PrintExternalCommands) {
   errs() << "\"" << ClangBinary.get() << "\"";
-  for (unsigned I = 1; ClangArgs[I]; ++I)
-errs() << " \"" << ClangArgs[I] << "\"";
+  for (StringRef Arg : ClangArgs)
+errs() << " \"" << Arg << "\"";
   errs() << "\n";
 } else {
   // Write the bitcode contents to the temporary file.


___
cfe-commits mailing l

[PATCH] D47233: [CodeGen] Emit MSVC RTTI for Obj-C EH types

2018-06-12 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added a comment.

In https://reviews.llvm.org/D47233#1129810, @DHowett-MSFT wrote:

> In https://reviews.llvm.org/D47233#1129207, @rjmccall wrote:
>
> > In https://reviews.llvm.org/D47233#1129110, @smeenai wrote:
> >
> > > WinObjC does this wrapping, for example.
> >
> >
> > I see.  The idea of creating the type descriptors and mangled names ad-hoc 
> > for the catchable-types array is clever, and it's nice that the ABI is 
> > defined in a way that makes that work.  (Expensive, but hey, it's the 
> > exceptions path.)
>
>
> We ran into some critical issues with this approach on x64. The pointers in 
> the exception record are supposed to be image-relative instead of absolute, 
> so I tried to make them absolute to libobjc2's load address, but I never 
> quite solved it.
>
> A slightly better-documented and cleaner version of the code you linked is 
> here 
> .


We solved the x64 issue by just calling RaiseException directly and supplying a 
fake ImageBase. It's a bit kludgy, but it works well. (_CxxThrowException's 
source is included with MSVC, so we just looked at how that was calling 
RaiseException and altered it accordingly.)


Repository:
  rC Clang

https://reviews.llvm.org/D47233



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


[PATCH] D45616: [X86] Lower _mm[256|512]_cmp[.]_mask intrinsics to native llvm IR

2018-06-12 Thread Gabor Buella via Phabricator via cfe-commits
GBuella added inline comments.



Comment at: lib/CodeGen/CGBuiltin.cpp:10071
+  // is _MM_FROUND_CUR_DIRECTION
+  if (cast(Ops[4])->getZExtValue() != 4)
+UsesNonDefaultRounding = true;

efriedma wrote:
> Given we're ignoring floating-point exceptions, we should also ignore the 
> "rounding mode" operand (__MM_FROUND_NO_EXC only affects exceptions, and the 
> other values are irrelevant because there isn't any actual rounding involved).
Oh, alltight. @craig.topper , Do you also agree on ignoring all of these, and 
just lowering all the comparisions to fcmp?
That is the easiest path of course.


https://reviews.llvm.org/D45616



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


[PATCH] D48036: [CUDA] Make min/max shims host+device.

2018-06-12 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

Last comment in the bug pointed out that those overloads should be constexpr in 
c++14. Maybe in a separate patch, though.

https://bugs.llvm.org/show_bug.cgi?id=37753#c5


https://reviews.llvm.org/D48036



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


[PATCH] D46024: [clang-format] Add SpaceBeforeCpp11BracedList option.

2018-06-12 Thread Ross Kirsling via Phabricator via cfe-commits
rkirsling updated this revision to Diff 150984.
rkirsling added a comment.

Addressed feedback—thank you for the review!


Repository:
  rC Clang

https://reviews.llvm.org/D46024

Files:
  docs/ClangFormatStyleOptions.rst
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -7019,6 +7019,11 @@
"  { \"c\", 2 }\n"
"};",
ExtraSpaces);
+
+  FormatStyle SpaceBeforeBrace = getLLVMStyle();
+  SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
+  verifyFormat("vector x {1, 2, 3, 4};", SpaceBeforeBrace);
+  verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
 }
 
 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
@@ -10622,6 +10627,7 @@
   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
+  CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2548,6 +2548,9 @@
   if (Style.isCpp()) {
 if (Left.is(tok::kw_operator))
   return Right.is(tok::coloncolon);
+if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
+!Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
+  return true;
   } else if (Style.Language == FormatStyle::LK_Proto ||
  Style.Language == FormatStyle::LK_TextProto) {
 if (Right.is(tok::period) &&
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -449,6 +449,8 @@
Style.SpaceAfterTemplateKeyword);
 IO.mapOptional("SpaceBeforeAssignmentOperators",
Style.SpaceBeforeAssignmentOperators);
+IO.mapOptional("SpaceBeforeCpp11BracedList",
+   Style.SpaceBeforeCpp11BracedList);
 IO.mapOptional("SpaceBeforeCtorInitializerColon",
Style.SpaceBeforeCtorInitializerColon);
 IO.mapOptional("SpaceBeforeInheritanceColon",
@@ -697,6 +699,7 @@
   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
   LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
   LLVMStyle.SpaceBeforeAssignmentOperators = true;
+  LLVMStyle.SpaceBeforeCpp11BracedList = false;
   LLVMStyle.SpacesInAngles = false;
 
   LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
@@ -892,6 +895,7 @@
   Style.ObjCBlockIndentWidth = 4;
   Style.ObjCSpaceAfterProperty = true;
   Style.PointerAlignment = FormatStyle::PAS_Left;
+  Style.SpaceBeforeCpp11BracedList = true;
   return Style;
 }
 
Index: include/clang/Format/Format.h
===
--- include/clang/Format/Format.h
+++ include/clang/Format/Format.h
@@ -1495,6 +1495,17 @@
   /// \endcode
   bool SpaceBeforeAssignmentOperators;
 
+  /// If ``true``, a space will be inserted before a C++11 braced list
+  /// used to initialize an object (after the preceding identifier or type).
+  /// \code
+  ///true:  false:
+  ///Foo foo { bar };   vs. Foo foo{ bar };
+  ///Foo {};Foo{};
+  ///vector { 1, 2, 3 };   vector{ 1, 2, 3 };
+  ///new int[3] { 1, 2, 3 };new int[3]{ 1, 2, 3 };
+  /// \endcode
+  bool SpaceBeforeCpp11BracedList;
+
   /// If ``false``, spaces will be removed before constructor initializer
   /// colon.
   /// \code
@@ -1738,6 +1749,7 @@
SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
SpaceAfterTemplateKeyword == R.SpaceAfterTemplateKeyword &&
SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
+   SpaceBeforeCpp11BracedList == R.SpaceBeforeCpp11BracedList &&
SpaceBeforeCtorInitializerColon ==
R.SpaceBeforeCtorInitializerColon &&
SpaceBeforeInheritanceColon == R.SpaceBeforeInheritanceColon &&
Index: docs/ClangFormatStyleOptions.rst
===
--- docs/ClangFormatStyleOptions.rst
+++ docs/ClangFormatStyleOptions.rst
@@ -1791,6 +1791,18 @@
  int a = 5; vs. int a=5;
  a += 42a+=42;
 
+**SpaceBeforeCpp11BracedList** (``bool``)
+  If ``true``, a space will be inserted before a C++11 braced list
+  used to initialize an object (after the preceding identifier or type).
+
+  .. code-block:: c++
+
+ t

Re: r334418 - Enable crash recovery tests on Windows, globs work in the lit internal shell now

2018-06-12 Thread Reid Kleckner via cfe-commits
On Tue, Jun 12, 2018 at 4:43 AM Hans Wennborg  wrote:

> Actually, maybe switching the order from "not env ... %clang" to "env
> ... not %clang" might work...
>

Thanks, I was going to try that next.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r334525 - [analyzer] [NFC] Unify Minimal and Extensive diagnostics.

2018-06-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jun 12 12:08:00 2018
New Revision: 334525

URL: http://llvm.org/viewvc/llvm-project?rev=334525&view=rev
Log:
[analyzer] [NFC] Unify Minimal and Extensive diagnostics.

Once we removed AlternateExtensive, I've looked closer into the
difference between Minimal and Extensive, and turns out, the difference
was not that large.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=334525&r1=334524&r2=334525&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Tue Jun 12 12:08:00 2018
@@ -388,7 +388,7 @@ public:
   PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
 
   PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
-return PDC ? PDC->getGenerationScheme() : 
PathDiagnosticConsumer::Extensive;
+return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Minimal;
   }
 
   bool supportsLogicalOpControlFlow() const {
@@ -536,7 +536,7 @@ PathDiagnosticBuilder::getEnclosingStmtL
 
//===--===//
 // "Visitors only" path diagnostic generation algorithm.
 
//===--===//
-static bool GenerateVisitorsOnlyPathDiagnostic(
+static bool generateVisitorsOnlyPathDiagnostics(
 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
 ArrayRef> visitors) {
   // All path generation skips the very first node (the error node).
@@ -586,99 +586,155 @@ static void updateStackPiecesWithMessage
 
 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
 
-/// Add path diagnostic for statement associated with node \p N
-/// to diagnostics \p PD.
-/// Precondition: location associated with \p N is a \c BlockEdge.
-static void generateMinimalDiagnosticsForBlockEdge(const ExplodedNode *N,
-   PathDiagnosticBuilder &PDB,
-   PathDiagnostic &PD) {
-  const LocationContext *LC = N->getLocationContext();
-  SourceManager& SMgr = PDB.getSourceManager();
-  BlockEdge BE = N->getLocation().castAs();
-  const CFGBlock *Src = BE.getSrc();
-  const CFGBlock *Dst = BE.getDst();
-  const Stmt *T = Src->getTerminator();
-  if (!T)
-return;
 
-  auto Start = PathDiagnosticLocation::createBegin(T, SMgr, LC);
-  switch (T->getStmtClass()) {
-  default:
-break;
+std::shared_ptr generateDiagForSwitchOP(
+  const ExplodedNode *N,
+  const CFGBlock *Dst,
+  const SourceManager &SM,
+  const LocationContext *LC,
+  PathDiagnosticBuilder &PDB,
+  PathDiagnosticLocation &Start
+  ) {
+  // Figure out what case arm we took.
+  std::string sbuf;
+  llvm::raw_string_ostream os(sbuf);
+  PathDiagnosticLocation End;
 
-  case Stmt::GotoStmtClass:
-  case Stmt::IndirectGotoStmtClass: {
-const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
+  if (const Stmt *S = Dst->getLabel()) {
+End = PathDiagnosticLocation(S, SM, LC);
 
-if (!S)
+switch (S->getStmtClass()) {
+default:
+  os << "No cases match in the switch statement. "
+"Control jumps to line "
+<< End.asLocation().getExpansionLineNumber();
+  break;
+case Stmt::DefaultStmtClass:
+  os << "Control jumps to the 'default' case at line "
+<< End.asLocation().getExpansionLineNumber();
   break;
 
-std::string sbuf;
-llvm::raw_string_ostream os(sbuf);
-const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
+case Stmt::CaseStmtClass: {
+  os << "Control jumps to 'case ";
+  const auto *Case = cast(S);
+  const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
+
+  // Determine if it is an enum.
+  bool GetRawInt = true;
+
+  if (const auto *DR = dyn_cast(LHS)) {
+// FIXME: Maybe this should be an assertion.  Are there cases
+// were it is not an EnumConstantDecl?
+const auto *D = dyn_cast(DR->getDecl());
+
+if (D) {
+  GetRawInt = false;
+  os << *D;
+}
+  }
 
-os << "Control jumps to line " << 
End.asLocation().getExpansionLineNumber();
-PD.getActivePath().push_front(
-std::make_shared(Start, End, 
os.str()));
-break;
+  if (GetRawInt)
+os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
+
+  os << ":'  at line " << End.asLocation().getExpansionLineNumber();
+  break;
+}
+}
+  } else {
+os << "'Default' branch taken. ";
+End = PDB.ExecutionContinues(os, N);
   }
+  return std::make_shared(Start, End,
+   os.str());
+}
 
-  

r334526 - [analyzer] [NFC] Now let's have only one place for diagnostics generation

2018-06-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jun 12 12:08:17 2018
New Revision: 334526

URL: http://llvm.org/viewvc/llvm-project?rev=334526&view=rev
Log:
[analyzer] [NFC] Now let's have only one place for diagnostics generation

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=334526&r1=334525&r2=334526&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Tue Jun 12 12:08:17 2018
@@ -534,30 +534,6 @@ PathDiagnosticBuilder::getEnclosingStmtL
 }
 
 
//===--===//
-// "Visitors only" path diagnostic generation algorithm.
-//===--===//
-static bool generateVisitorsOnlyPathDiagnostics(
-PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
-ArrayRef> visitors) {
-  // All path generation skips the very first node (the error node).
-  // This is because there is special handling for the end-of-path note.
-  N = N->getFirstPred();
-  if (!N)
-return true;
-
-  BugReport *R = PDB.getBugReport();
-  while (const ExplodedNode *Pred = N->getFirstPred()) {
-for (auto &V : visitors)
-  // Visit all the node pairs, but throw the path pieces away.
-  V->VisitNode(N, Pred, PDB, *R);
-
-N = Pred;
-  }
-
-  return R->isValid();
-}
-
-//===--===//
 // "Minimal" path diagnostic generation algorithm.
 
//===--===//
 using StackDiagPair =
@@ -1285,7 +1261,7 @@ static void generatePathDiagnosticsForNo
 
 /// There are two path diagnostics generation modes: with adding edges (used
 /// for plists) and without  (used for HTML and text).
-/// When edges are added (\p AddPathEdges),
+/// When edges are added (\p ActiveScheme is Extensive),
 /// the path is modified to insert artificially generated
 /// edges.
 /// Otherwise, more detailed diagnostics is emitted for block edges, explaining
@@ -1294,20 +1270,24 @@ static bool generatePathDiagnostics(
 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
 LocationContextMap &LCM,
 ArrayRef> visitors,
-bool AddPathEdges) {
+PathDiagnosticConsumer::PathGenerationScheme ActiveScheme) {
   BugReport *report = PDB.getBugReport();
   StackDiagVector CallStack;
   InterestingExprs IE;
+  bool AddPathEdges = (ActiveScheme == PathDiagnosticConsumer::Extensive);
+  bool GenerateDiagnostics = (ActiveScheme != PathDiagnosticConsumer::None);
 
-  PathDiagnosticLocation PrevLoc = PD.getLocation();
+  PathDiagnosticLocation PrevLoc = GenerateDiagnostics ?
+PD.getLocation() : PathDiagnosticLocation();
 
   const ExplodedNode *NextNode = N->getFirstPred();
   while (NextNode) {
 N = NextNode;
 NextNode = N->getFirstPred();
 
-generatePathDiagnosticsForNode(
-N, PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
+if (GenerateDiagnostics)
+  generatePathDiagnosticsForNode(
+  N, PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
 
 if (!NextNode)
   continue;
@@ -1316,6 +1296,10 @@ static bool generatePathDiagnostics(
 llvm::FoldingSet DeduplicationSet;
 for (auto &V : visitors) {
   if (auto p = V->VisitNode(N, NextNode, PDB, *report)) {
+
+if (!GenerateDiagnostics)
+  continue;
+
 if (DeduplicationSet.GetOrInsertNode(p.get()) != p.get())
   continue;
 
@@ -1342,7 +1326,7 @@ static bool generatePathDiagnostics(
 
   // After constructing the full PathDiagnostic, do a pass over it to compact
   // PathDiagnosticPieces that occur within a macro.
-  if (!AddPathEdges)
+  if (!AddPathEdges && GenerateDiagnostics)
 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
 
   return true;
@@ -2599,19 +2583,7 @@ bool GRBugReporter::generatePathDiagnost
   // hold onto old mappings.
   LCM.clear();
 
-  switch (ActiveScheme) {
-  case PathDiagnosticConsumer::Extensive:
-generatePathDiagnostics(PD, PDB, N, LCM, visitors,
-   /*AddPathEdges=*/true);
-break;
-  case PathDiagnosticConsumer::Minimal:
-generatePathDiagnostics(PD, PDB, N, LCM, visitors,
-   /*AddPathEdges=*/false);
-break;
-  case PathDiagnosticConsumer::None:
-generateVisitorsOnlyPathDiagnostics(PD, PDB, N, visitors);
-break;
-  }
+  generatePathDiagnostics(PD, PDB, N, LCM, visitors, ActiveScheme);
 
   // Clean up the visitors we used.
   visitors.clear();


_

[PATCH] D47756: [analyzer] [NFC] Unify Minimal and Extensive diagnostics.

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334525: [analyzer] [NFC] Unify Minimal and Extensive 
diagnostics. (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D47756?vs=149897&id=150992#toc

Repository:
  rC Clang

https://reviews.llvm.org/D47756

Files:
  lib/StaticAnalyzer/Core/BugReporter.cpp

Index: lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- lib/StaticAnalyzer/Core/BugReporter.cpp
+++ lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -388,7 +388,7 @@
   PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
 
   PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
-return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
+return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Minimal;
   }
 
   bool supportsLogicalOpControlFlow() const {
@@ -536,7 +536,7 @@
 //===--===//
 // "Visitors only" path diagnostic generation algorithm.
 //===--===//
-static bool GenerateVisitorsOnlyPathDiagnostic(
+static bool generateVisitorsOnlyPathDiagnostics(
 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
 ArrayRef> visitors) {
   // All path generation skips the very first node (the error node).
@@ -586,99 +586,155 @@
 
 static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
 
-/// Add path diagnostic for statement associated with node \p N
-/// to diagnostics \p PD.
-/// Precondition: location associated with \p N is a \c BlockEdge.
-static void generateMinimalDiagnosticsForBlockEdge(const ExplodedNode *N,
-   PathDiagnosticBuilder &PDB,
-   PathDiagnostic &PD) {
-  const LocationContext *LC = N->getLocationContext();
-  SourceManager& SMgr = PDB.getSourceManager();
-  BlockEdge BE = N->getLocation().castAs();
-  const CFGBlock *Src = BE.getSrc();
-  const CFGBlock *Dst = BE.getDst();
-  const Stmt *T = Src->getTerminator();
-  if (!T)
-return;
 
-  auto Start = PathDiagnosticLocation::createBegin(T, SMgr, LC);
-  switch (T->getStmtClass()) {
-  default:
-break;
+std::shared_ptr generateDiagForSwitchOP(
+  const ExplodedNode *N,
+  const CFGBlock *Dst,
+  const SourceManager &SM,
+  const LocationContext *LC,
+  PathDiagnosticBuilder &PDB,
+  PathDiagnosticLocation &Start
+  ) {
+  // Figure out what case arm we took.
+  std::string sbuf;
+  llvm::raw_string_ostream os(sbuf);
+  PathDiagnosticLocation End;
 
-  case Stmt::GotoStmtClass:
-  case Stmt::IndirectGotoStmtClass: {
-const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
+  if (const Stmt *S = Dst->getLabel()) {
+End = PathDiagnosticLocation(S, SM, LC);
 
-if (!S)
+switch (S->getStmtClass()) {
+default:
+  os << "No cases match in the switch statement. "
+"Control jumps to line "
+<< End.asLocation().getExpansionLineNumber();
+  break;
+case Stmt::DefaultStmtClass:
+  os << "Control jumps to the 'default' case at line "
+<< End.asLocation().getExpansionLineNumber();
   break;
 
-std::string sbuf;
-llvm::raw_string_ostream os(sbuf);
-const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
+case Stmt::CaseStmtClass: {
+  os << "Control jumps to 'case ";
+  const auto *Case = cast(S);
+  const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
+
+  // Determine if it is an enum.
+  bool GetRawInt = true;
+
+  if (const auto *DR = dyn_cast(LHS)) {
+// FIXME: Maybe this should be an assertion.  Are there cases
+// were it is not an EnumConstantDecl?
+const auto *D = dyn_cast(DR->getDecl());
+
+if (D) {
+  GetRawInt = false;
+  os << *D;
+}
+  }
 
-os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
-PD.getActivePath().push_front(
-std::make_shared(Start, End, os.str()));
-break;
+  if (GetRawInt)
+os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
+
+  os << ":'  at line " << End.asLocation().getExpansionLineNumber();
+  break;
+}
+}
+  } else {
+os << "'Default' branch taken. ";
+End = PDB.ExecutionContinues(os, N);
   }
+  return std::make_shared(Start, End,
+   os.str());
+}
 
-  case Stmt::SwitchStmtClass: {
-// Figure out what case arm we took.
+
+std::shared_ptr generateDiagForGotoOP(
+  const Stmt *S,
+  PathDiagnosticBuilder &PDB,
+  PathDiagnosticLocation &Start) {
 std::string sbuf;
 llvm::raw_string_ostream os(sbuf);
+const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
+os << "Co

[PATCH] D47931: [clangd] Customizable URI schemes for dynamic index.

2018-06-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Not ignoring this patch: the implementation LG, whether it's the right design 
depends on where https://reviews.llvm.org/D47935 ends up I think.
(I suspect this is what we want, is there any urgency to landing this part?)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D47931



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


[PATCH] D47808: [analyzer] [NFC] Now let's have only one place for diagnostics generation

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334526: [analyzer] [NFC] Now let's have only one place 
for diagnostics generation (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D47808?vs=150065&id=150993#toc

Repository:
  rC Clang

https://reviews.llvm.org/D47808

Files:
  lib/StaticAnalyzer/Core/BugReporter.cpp

Index: lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- lib/StaticAnalyzer/Core/BugReporter.cpp
+++ lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -534,30 +534,6 @@
 }
 
 //===--===//
-// "Visitors only" path diagnostic generation algorithm.
-//===--===//
-static bool generateVisitorsOnlyPathDiagnostics(
-PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
-ArrayRef> visitors) {
-  // All path generation skips the very first node (the error node).
-  // This is because there is special handling for the end-of-path note.
-  N = N->getFirstPred();
-  if (!N)
-return true;
-
-  BugReport *R = PDB.getBugReport();
-  while (const ExplodedNode *Pred = N->getFirstPred()) {
-for (auto &V : visitors)
-  // Visit all the node pairs, but throw the path pieces away.
-  V->VisitNode(N, Pred, PDB, *R);
-
-N = Pred;
-  }
-
-  return R->isValid();
-}
-
-//===--===//
 // "Minimal" path diagnostic generation algorithm.
 //===--===//
 using StackDiagPair =
@@ -1285,37 +1261,45 @@
 
 /// There are two path diagnostics generation modes: with adding edges (used
 /// for plists) and without  (used for HTML and text).
-/// When edges are added (\p AddPathEdges),
+/// When edges are added (\p ActiveScheme is Extensive),
 /// the path is modified to insert artificially generated
 /// edges.
 /// Otherwise, more detailed diagnostics is emitted for block edges, explaining
 /// the transitions in words.
 static bool generatePathDiagnostics(
 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
 LocationContextMap &LCM,
 ArrayRef> visitors,
-bool AddPathEdges) {
+PathDiagnosticConsumer::PathGenerationScheme ActiveScheme) {
   BugReport *report = PDB.getBugReport();
   StackDiagVector CallStack;
   InterestingExprs IE;
+  bool AddPathEdges = (ActiveScheme == PathDiagnosticConsumer::Extensive);
+  bool GenerateDiagnostics = (ActiveScheme != PathDiagnosticConsumer::None);
 
-  PathDiagnosticLocation PrevLoc = PD.getLocation();
+  PathDiagnosticLocation PrevLoc = GenerateDiagnostics ?
+PD.getLocation() : PathDiagnosticLocation();
 
   const ExplodedNode *NextNode = N->getFirstPred();
   while (NextNode) {
 N = NextNode;
 NextNode = N->getFirstPred();
 
-generatePathDiagnosticsForNode(
-N, PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
+if (GenerateDiagnostics)
+  generatePathDiagnosticsForNode(
+  N, PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
 
 if (!NextNode)
   continue;
 
 // Add pieces from custom visitors.
 llvm::FoldingSet DeduplicationSet;
 for (auto &V : visitors) {
   if (auto p = V->VisitNode(N, NextNode, PDB, *report)) {
+
+if (!GenerateDiagnostics)
+  continue;
+
 if (DeduplicationSet.GetOrInsertNode(p.get()) != p.get())
   continue;
 
@@ -1342,7 +1326,7 @@
 
   // After constructing the full PathDiagnostic, do a pass over it to compact
   // PathDiagnosticPieces that occur within a macro.
-  if (!AddPathEdges)
+  if (!AddPathEdges && GenerateDiagnostics)
 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
 
   return true;
@@ -2599,19 +2583,7 @@
   // hold onto old mappings.
   LCM.clear();
 
-  switch (ActiveScheme) {
-  case PathDiagnosticConsumer::Extensive:
-generatePathDiagnostics(PD, PDB, N, LCM, visitors,
-   /*AddPathEdges=*/true);
-break;
-  case PathDiagnosticConsumer::Minimal:
-generatePathDiagnostics(PD, PDB, N, LCM, visitors,
-   /*AddPathEdges=*/false);
-break;
-  case PathDiagnosticConsumer::None:
-generateVisitorsOnlyPathDiagnostics(PD, PDB, N, visitors);
-break;
-  }
+  generatePathDiagnostics(PD, PDB, N, LCM, visitors, ActiveScheme);
 
   // Clean up the visitors we used.
   visitors.clear();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48089: [clang-format] Fix crash while reflowing backslash in comments

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
Herald added a subscriber: cfe-commits.

The added test case was currently crashing with an assertion:


Repository:
  rC Clang

https://reviews.llvm.org/D48089

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


Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -3090,6 +3090,21 @@
getLLVMStyleWithColumns(23));
 }
 
+TEST_F(FormatTestComments, ReflowBackslashCrash) {
+// clang-format off
+  EXPECT_EQ(
+"// How to run:\n"
+"// b run \\\n"
+"// 
rrr\n"
+"// \\  -- --output_directory=\"\"",
+  format(
+"// How to run:\n"
+"// b run \\\n"
+"// 
rrr 
\\\n"
+"//  -- --output_directory=\"\""));
+// clang-format on
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/BreakableToken.cpp
+++ lib/Format/BreakableToken.cpp
@@ -789,16 +789,47 @@
 
 void BreakableLineCommentSection::reflow(unsigned LineIndex,
  WhitespaceManager &Whitespaces) const 
{
-  // Reflow happens between tokens. Replace the whitespace between the
-  // tokens by the empty string.
-  Whitespaces.replaceWhitespace(
-  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
-  /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
+// Reflow happens between tokens. Replace the whitespace between the
+// tokens by the empty string.
+Whitespaces.replaceWhitespace(
+*Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
+/*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  } else if (LineIndex > 0) {
+// In case we're reflowing after the '\' in:
+//
+//   // line comment \
+//   // line 2
+//
+// the reflow happens inside the single comment token (it is a single line
+// comment with an unescaped newline).
+// Replace the whitespace between the '\' and '//' with the empty string.
+//
+// Offset points to after the '\' relative to start of the token.
+unsigned Offset = Lines[LineIndex - 1].data() +
+  Lines[LineIndex - 1].size() -
+  tokenAt(LineIndex - 1).TokenText.data();
+// WhitespaceLength is the number of chars between the '\' and the '//' on
+// the next line.
+unsigned WhitespaceLength =
+Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
+Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
+ Offset,
+ /*ReplaceChars=*/WhitespaceLength,
+ /*PreviousPostfix=*/"",
+ /*CurrentPrefix=*/"",
+ /*InPPDirective=*/false,
+ /*Newlines=*/0,
+ /*Spaces=*/0);
+
+  }
   // Replace the indent and prefix of the token with the reflow prefix.
+  unsigned Offset =
+  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
   unsigned WhitespaceLength =
-  Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
+  Content[LineIndex].data() - Lines[LineIndex].data();
   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
-   /*Offset=*/0,
+   Offset,
/*ReplaceChars=*/WhitespaceLength,
/*PreviousPostfix=*/"",
/*CurrentPrefix=*/ReflowPrefix,


Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -3090,6 +3090,21 @@
getLLVMStyleWithColumns(23));
 }
 
+TEST_F(FormatTestComments, ReflowBackslashCrash) {
+// clang-format off
+  EXPECT_EQ(
+"// How to run:\n"
+"// b run \\\n"
+"// rrr\n"
+"// \\  -- --output_directory=\"\"",
+  format(
+"// How to run:\n"
+"// b run \\\n"
+"// rrr \\\n"
+"//  -- --output_directory=\"\""));
+// clang-format on
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/Bre

[PATCH] D47935: [clangd] Boost completion score according to file proximity.

2018-06-12 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Sorry for the delay on this change. There's a bunch of complexity in this 
problem that I haven't seen how to slice through:

1. the signals needed seem like a weird fit for the Symbol*Signals structs for 
some reason (maybe my misdesign)
2. the inconsistency between how we do this for Sema and for Index results 
has... only slightly good reasons
3. the URI vs filename thing is awkward
4. with all this, the actual scoring still seems ad-hoc and is missing 
important parts (main header, transitive includes)

Not all your fault that the code reflects this, the problem is tangly. But it's 
hard for me to reason about APIs or performance or layering.

Looking at the last point (scoring model) because it seems the most tractable. 
I think this is basically an edit distance problem?
(We can call the result "proximity", start at one, and multiply by <1, or call 
it "distance" and start at 0 and add penalties, but it's equivalent).

- we're computing distances between files (glossing over URI-space vs 
file-space)
- the roots are the main file, and maybe the matching header
- edits take us from a filepath to a related filepath:
  - from a file to a header it `#include`s
  - from a file to its parent directory
  - from a parent directory to a child directory
  - from a parent directory to a file in it
- the distance is the smallest sum-of-penalties for any path leading from the 
root to the symbol

What do you think of this model?



**If** the model seems reasonable, then it suggests an approach of building a 
one-per-query data structure that computes the needed edit-distance 
recursively, memoizing results. `SymbolRelevanceResults` could store the symbol 
path and a pointer to the edit-distance machine, and for debugging the machine 
would know how to describe its configuration. URI/path mapping wouldn't be a 
performance concern (I think) if the memoization captured it.

Let's chat offline?




Comment at: clangd/Quality.cpp:171
+/// "uri:///a/b/c" will be treated as /a/b/c
+static float uriProximity(StringRef UX, StringRef UY) {
+  auto SchemeSplitX = UX.split(':');

ioeric wrote:
> sammccall wrote:
> > This doesn't look quite right to me.
> > We can tune the details later, but in practice this seems like it's *very* 
> > hard to get zero proximity, which is our neutral score - you need to be 18 
> > directories away?
> > 
> > FWIW, fozzie appears to give an additive boost proportional to 5-up, where 
> > up is the number of directories from the context you have to traverse up 
> > from the context to get to a parent of the symbol. (There's no penalty for 
> > down-traversals probably for implementation reasons, this should be smaller 
> > than the up-traversal penalty I think)
> The numbers are guessed... definitely happy to tune.
> > We can tune the details later, but in practice this seems like it's *very* 
> > hard to get zero proximity, which is our neutral score - you need to be 18 
> > directories away?
> It's 18 directories away if one file is in an ancestor directories of the 
> other (i.e. only traverse up or down). If you need to traverse up and down, 
> the penalty for each directory is 0.1, which takes 10 directories (up+down, 
> so 
> 5 up in average). I think it's useful to make this distinction because I 
> think it's more likely for a file to use a header if it's in the file path.  
> 
> I'm not sure if we should use zero as the neutral score. For example, if a 
> codebase has deep directory structure, most scores are probably going to be 
> small; conversely, most scores would be relatively big. I think relative 
> scores are more useful.
> 
> > (There's no penalty for down-traversals probably for implementation 
> > reasons, this should be smaller than the up-traversal penalty I think)
> Why do you think down-traversal should take less penalty?
> 
> If you need to traverse up and down, the penalty for each directory is 0.1, 
> which takes 10 directories (up+down, so 5 up in average).
I think you've halved twice there - it still seems to be 10, which is a lot.

> I'm not sure if we should use zero as the neutral score.
Well, zero is currently the neutral score, and this patch doesn't change it :-)
I think starting at 1 for the current file and *multiplying* by p<1 to apply 
penalties should give a reasonable 0-1 score that's relatively sane even for 
codebases of different sizes. Happy to have a different model, but you need to 
explain/implement how it combines with other signals.

> Why do you think down-traversal should take less penalty?
Intuitively, because subprojects are more closely related than superprojects. 
But this didn't occur to me until someone mentioned it, we should check with 
Matei and Alexander.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D47935



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

r334527 - [clang-format] Fix crash while reflowing backslash in comments

2018-06-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jun 12 12:33:15 2018
New Revision: 334527

URL: http://llvm.org/viewvc/llvm-project?rev=334527&view=rev
Log:
[clang-format] Fix crash while reflowing backslash in comments

Summary:
The added test case was currently crashing with an assertion:
```
krasimir@krasimir> cat test.cc  

~
// How to run:
// b run \
// 
rrr 
\
//  -- --output_directory=""
krasimir@krasimir> ~/work/llvm-build/bin/clang-format test.cc   

~
clang-format: 
/usr/local/google/home/krasimir/work/llvm/tools/clang/lib/Format/WhitespaceManager.cpp:117:
 void clang::format::WhitespaceManager::calculateLineBreakInformation(): 
Assertion `PreviousOriginalWhitespaceEndOffset <= 
OriginalWhitespaceStartOffset' failed.
```
The root cause was that BreakableToken was not considering the case of a reflow 
between an unescaped newline in a line comment.

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=334527&r1=334526&r2=334527&view=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Tue Jun 12 12:33:15 2018
@@ -789,16 +789,47 @@ BreakableComment::Split BreakableLineCom
 
 void BreakableLineCommentSection::reflow(unsigned LineIndex,
  WhitespaceManager &Whitespaces) const 
{
-  // Reflow happens between tokens. Replace the whitespace between the
-  // tokens by the empty string.
-  Whitespaces.replaceWhitespace(
-  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
-  /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
+// Reflow happens between tokens. Replace the whitespace between the
+// tokens by the empty string.
+Whitespaces.replaceWhitespace(
+*Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
+/*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  } else if (LineIndex > 0) {
+// In case we're reflowing after the '\' in:
+//
+//   // line comment \
+//   // line 2
+//
+// the reflow happens inside the single comment token (it is a single line
+// comment with an unescaped newline).
+// Replace the whitespace between the '\' and '//' with the empty string.
+//
+// Offset points to after the '\' relative to start of the token.
+unsigned Offset = Lines[LineIndex - 1].data() +
+  Lines[LineIndex - 1].size() -
+  tokenAt(LineIndex - 1).TokenText.data();
+// WhitespaceLength is the number of chars between the '\' and the '//' on
+// the next line.
+unsigned WhitespaceLength =
+Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
+Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
+ Offset,
+ /*ReplaceChars=*/WhitespaceLength,
+ /*PreviousPostfix=*/"",
+ /*CurrentPrefix=*/"",
+ /*InPPDirective=*/false,
+ /*Newlines=*/0,
+ /*Spaces=*/0);
+
+  }
   // Replace the indent and prefix of the token with the reflow prefix.
+  unsigned Offset =
+  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
   unsigned WhitespaceLength =
-  Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
+  Content[LineIndex].data() - Lines[LineIndex].data();
   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
-   /*Offset=*/0,
+   Offset,
/*ReplaceChars=*/WhitespaceLength,
/*PreviousPostfix=*/"",
/*CurrentPrefix=*/ReflowPrefix,

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=334527&r1=334526&r2=334527&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTes

[PATCH] D48089: [clang-format] Fix crash while reflowing backslash in comments

2018-06-12 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334527: [clang-format] Fix crash while reflowing backslash 
in comments (authored by krasimir, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48089?vs=150994&id=150997#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48089

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


Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/BreakableToken.cpp
+++ lib/Format/BreakableToken.cpp
@@ -789,16 +789,47 @@
 
 void BreakableLineCommentSection::reflow(unsigned LineIndex,
  WhitespaceManager &Whitespaces) const 
{
-  // Reflow happens between tokens. Replace the whitespace between the
-  // tokens by the empty string.
-  Whitespaces.replaceWhitespace(
-  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
-  /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
+// Reflow happens between tokens. Replace the whitespace between the
+// tokens by the empty string.
+Whitespaces.replaceWhitespace(
+*Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
+/*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  } else if (LineIndex > 0) {
+// In case we're reflowing after the '\' in:
+//
+//   // line comment \
+//   // line 2
+//
+// the reflow happens inside the single comment token (it is a single line
+// comment with an unescaped newline).
+// Replace the whitespace between the '\' and '//' with the empty string.
+//
+// Offset points to after the '\' relative to start of the token.
+unsigned Offset = Lines[LineIndex - 1].data() +
+  Lines[LineIndex - 1].size() -
+  tokenAt(LineIndex - 1).TokenText.data();
+// WhitespaceLength is the number of chars between the '\' and the '//' on
+// the next line.
+unsigned WhitespaceLength =
+Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
+Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
+ Offset,
+ /*ReplaceChars=*/WhitespaceLength,
+ /*PreviousPostfix=*/"",
+ /*CurrentPrefix=*/"",
+ /*InPPDirective=*/false,
+ /*Newlines=*/0,
+ /*Spaces=*/0);
+
+  }
   // Replace the indent and prefix of the token with the reflow prefix.
+  unsigned Offset =
+  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
   unsigned WhitespaceLength =
-  Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
+  Content[LineIndex].data() - Lines[LineIndex].data();
   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
-   /*Offset=*/0,
+   Offset,
/*ReplaceChars=*/WhitespaceLength,
/*PreviousPostfix=*/"",
/*CurrentPrefix=*/ReflowPrefix,
Index: unittests/Format/FormatTestComments.cpp
===
--- unittests/Format/FormatTestComments.cpp
+++ unittests/Format/FormatTestComments.cpp
@@ -3090,6 +3090,21 @@
getLLVMStyleWithColumns(23));
 }
 
+TEST_F(FormatTestComments, ReflowBackslashCrash) {
+// clang-format off
+  EXPECT_EQ(
+"// How to run:\n"
+"// b run \\\n"
+"// 
rrr\n"
+"// \\  -- --output_directory=\"\"",
+  format(
+"// How to run:\n"
+"// b run \\\n"
+"// 
rrr 
\\\n"
+"//  -- --output_directory=\"\""));
+// clang-format on
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


Index: lib/Format/BreakableToken.cpp
===
--- lib/Format/BreakableToken.cpp
+++ lib/Format/BreakableToken.cpp
@@ -789,16 +789,47 @@
 
 void BreakableLineCommentSection::reflow(unsigned LineIndex,
  WhitespaceManager &Whitespaces) const {
-  // Reflow happens between tokens. Replace the whitespace between the
-  // tokens by the empty string.
-  Whitespaces.replaceWhitespace(
-  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
-  /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
+// Reflow happe

[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris added inline comments.



Comment at: lib/StaticAnalyzer/Core/LoopWidening.cpp:89
+new Callback(LCtx, MRMgr, ITraits));
+  Finder.matchAST(ASTCtx);
+

ormris wrote:
> NoQ wrote:
> > NoQ wrote:
> > > george.karpenkov wrote:
> > > > ormris wrote:
> > > > > george.karpenkov wrote:
> > > > > > IMO using the iterator directly (e.g. like it was done in 
> > > > > > https://github.com/llvm-mirror/clang/blob/master/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp#L213)
> > > > > >  leads to a much cleaner code and saves you from having to define a 
> > > > > > callback class.
> > > > > Hmm... I think that's a better approach. Let me see if I can get that 
> > > > > working.
> > > > @ormris Yeah I'm really not sure why all examples use the callback API 
> > > > by default.
> > > Also, please match only the local AST, i.e. the body of the function 
> > > under analysis, which can be obtained as `LCtx->getDecl()->getBody()`. 
> > > There's no need to scan the whole translation unit.
> > Actually not sure, would widening screw the previous stack frames as well? 
> > We should test that, i guess. And even then, it's better to match a few 
> > stack frames in the current stack trace than to match the whole translation 
> > unit.
> I can't seem to get the new syntax to work. The following assert(0) is never 
> triggered.
> 
> ```
>   auto Matches = match(varDecl(hasType(referenceType())).bind(MatchRef),
>*LCtx->getDecl()->getBody(), ASTCtx);
>   for (BoundNodes Match : Matches) {
> assert(0 && "anything");
> const VarDecl *VD = Match.getNodeAs(MatchRef);
> const VarRegion *VarMem = MRMgr.getVarRegion(VD, LCtx);
> ITraits.setTrait(VarMem,
>  RegionAndSymbolInvalidationTraits::TK_PreserveContents);
>   }
> 
> ```
It appears that "decl()" produces no matches...


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Core/LoopWidening.cpp:89
+new Callback(LCtx, MRMgr, ITraits));
+  Finder.matchAST(ASTCtx);
+

ormris wrote:
> ormris wrote:
> > NoQ wrote:
> > > NoQ wrote:
> > > > george.karpenkov wrote:
> > > > > ormris wrote:
> > > > > > george.karpenkov wrote:
> > > > > > > IMO using the iterator directly (e.g. like it was done in 
> > > > > > > https://github.com/llvm-mirror/clang/blob/master/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp#L213)
> > > > > > >  leads to a much cleaner code and saves you from having to define 
> > > > > > > a callback class.
> > > > > > Hmm... I think that's a better approach. Let me see if I can get 
> > > > > > that working.
> > > > > @ormris Yeah I'm really not sure why all examples use the callback 
> > > > > API by default.
> > > > Also, please match only the local AST, i.e. the body of the function 
> > > > under analysis, which can be obtained as `LCtx->getDecl()->getBody()`. 
> > > > There's no need to scan the whole translation unit.
> > > Actually not sure, would widening screw the previous stack frames as 
> > > well? We should test that, i guess. And even then, it's better to match a 
> > > few stack frames in the current stack trace than to match the whole 
> > > translation unit.
> > I can't seem to get the new syntax to work. The following assert(0) is 
> > never triggered.
> > 
> > ```
> >   auto Matches = match(varDecl(hasType(referenceType())).bind(MatchRef),
> >*LCtx->getDecl()->getBody(), ASTCtx);
> >   for (BoundNodes Match : Matches) {
> > assert(0 && "anything");
> > const VarDecl *VD = Match.getNodeAs(MatchRef);
> > const VarRegion *VarMem = MRMgr.getVarRegion(VD, LCtx);
> > ITraits.setTrait(VarMem,
> >  
> > RegionAndSymbolInvalidationTraits::TK_PreserveContents);
> >   }
> > 
> > ```
> It appears that "decl()" produces no matches...
Mmm, i think when you're matching using `match` rather than `matchAST`, you 
need to write a match for the exact statement rather than any sub-statement. 
I.e., those are like "match" vs. "find". I.e., try wraping your matcher into 
`stmt(hasDescendant(...))`, where `stmt()` would match the whole function body 
(most likely a `CompoundStmt` for the curly braces around the function body, 
but there are some other cases).


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris added inline comments.



Comment at: lib/StaticAnalyzer/Core/LoopWidening.cpp:89
+new Callback(LCtx, MRMgr, ITraits));
+  Finder.matchAST(ASTCtx);
+

NoQ wrote:
> ormris wrote:
> > ormris wrote:
> > > NoQ wrote:
> > > > NoQ wrote:
> > > > > george.karpenkov wrote:
> > > > > > ormris wrote:
> > > > > > > george.karpenkov wrote:
> > > > > > > > IMO using the iterator directly (e.g. like it was done in 
> > > > > > > > https://github.com/llvm-mirror/clang/blob/master/lib/StaticAnalyzer/Checkers/GCDAntipatternChecker.cpp#L213)
> > > > > > > >  leads to a much cleaner code and saves you from having to 
> > > > > > > > define a callback class.
> > > > > > > Hmm... I think that's a better approach. Let me see if I can get 
> > > > > > > that working.
> > > > > > @ormris Yeah I'm really not sure why all examples use the callback 
> > > > > > API by default.
> > > > > Also, please match only the local AST, i.e. the body of the function 
> > > > > under analysis, which can be obtained as 
> > > > > `LCtx->getDecl()->getBody()`. There's no need to scan the whole 
> > > > > translation unit.
> > > > Actually not sure, would widening screw the previous stack frames as 
> > > > well? We should test that, i guess. And even then, it's better to match 
> > > > a few stack frames in the current stack trace than to match the whole 
> > > > translation unit.
> > > I can't seem to get the new syntax to work. The following assert(0) is 
> > > never triggered.
> > > 
> > > ```
> > >   auto Matches = match(varDecl(hasType(referenceType())).bind(MatchRef),
> > >*LCtx->getDecl()->getBody(), ASTCtx);
> > >   for (BoundNodes Match : Matches) {
> > > assert(0 && "anything");
> > > const VarDecl *VD = Match.getNodeAs(MatchRef);
> > > const VarRegion *VarMem = MRMgr.getVarRegion(VD, LCtx);
> > > ITraits.setTrait(VarMem,
> > >  
> > > RegionAndSymbolInvalidationTraits::TK_PreserveContents);
> > >   }
> > > 
> > > ```
> > It appears that "decl()" produces no matches...
> Mmm, i think when you're matching using `match` rather than `matchAST`, you 
> need to write a match for the exact statement rather than any sub-statement. 
> I.e., those are like "match" vs. "find". I.e., try wraping your matcher into 
> `stmt(hasDescendant(...))`, where `stmt()` would match the whole function 
> body (most likely a `CompoundStmt` for the curly braces around the function 
> body, but there are some other cases).
Looks like that worked. Thanks!


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


r334531 - [AArch64] Support reserving x20 register

2018-06-12 Thread Petr Hosek via cfe-commits
Author: phosek
Date: Tue Jun 12 13:00:50 2018
New Revision: 334531

URL: http://llvm.org/viewvc/llvm-project?rev=334531&view=rev
Log:
[AArch64] Support reserving x20 register

Register x20 is a callee-saved register which may be used for other
purposes in certain contexts, for example to hold special variables
within the kernel. This change adds support for reserving this register
both to frontend and backend to make this register usable for these
purposes.

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

Added:
cfe/trunk/test/Driver/aarch64-fixed-x20.c
Modified:
cfe/trunk/docs/ClangCommandLineReference.rst
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=334531&r1=334530&r2=334531&view=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Tue Jun 12 13:00:50 2018
@@ -2296,6 +2296,10 @@ AARCH64
 
 Reserve the x18 register (AArch64 only)
 
+.. option:: -ffixed-x20
+
+Reserve the x20 register (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=334531&r1=334530&r2=334531&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Tue Jun 12 13:00:50 2018
@@ -2004,6 +2004,8 @@ def mno_fix_cortex_a53_835769 : Flag<["-
   HelpText<"Don't workaround Cortex-A53 erratum 835769 (AArch64 only)">;
 def ffixed_x18 : Flag<["-"], "ffixed-x18">, Group,
   HelpText<"Reserve the x18 register (AArch64 only)">;
+def ffixed_x20 : Flag<["-"], "ffixed-x20">, Group,
+  HelpText<"Reserve the x20 register (AArch64 only)">;
 
 def msimd128 : Flag<["-"], "msimd128">, Group;
 def mno_simd128 : Flag<["-"], "mno-simd128">, Group;

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp?rev=334531&r1=334530&r2=334531&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp Tue Jun 12 13:00:50 2018
@@ -198,6 +198,9 @@ void aarch64::getAArch64TargetFeatures(c
   if (Args.hasArg(options::OPT_ffixed_x18))
 Features.push_back("+reserve-x18");
 
+  if (Args.hasArg(options::OPT_ffixed_x20))
+Features.push_back("+reserve-x20");
+
   if (Args.hasArg(options::OPT_mno_neg_immediates))
 Features.push_back("+no-neg-immediates");
 }

Added: cfe/trunk/test/Driver/aarch64-fixed-x20.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-fixed-x20.c?rev=334531&view=auto
==
--- cfe/trunk/test/Driver/aarch64-fixed-x20.c (added)
+++ cfe/trunk/test/Driver/aarch64-fixed-x20.c Tue Jun 12 13:00:50 2018
@@ -0,0 +1,4 @@
+// RUN: %clang -target aarch64-none-gnu -ffixed-x20 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-FIXED-X20 < %t %s
+
+// CHECK-FIXED-X20: "-target-feature" "+reserve-x20"


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


[PATCH] D46552: [AArch64] Support reserving x20 register

2018-06-12 Thread Petr Hosek via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334531: [AArch64] Support reserving x20 register (authored 
by phosek, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D46552?vs=150601&id=151006#toc

Repository:
  rC Clang

https://reviews.llvm.org/D46552

Files:
  docs/ClangCommandLineReference.rst
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/AArch64.cpp
  test/Driver/aarch64-fixed-x20.c


Index: lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- lib/Driver/ToolChains/Arch/AArch64.cpp
+++ lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -198,6 +198,9 @@
   if (Args.hasArg(options::OPT_ffixed_x18))
 Features.push_back("+reserve-x18");
 
+  if (Args.hasArg(options::OPT_ffixed_x20))
+Features.push_back("+reserve-x20");
+
   if (Args.hasArg(options::OPT_mno_neg_immediates))
 Features.push_back("+no-neg-immediates");
 }
Index: docs/ClangCommandLineReference.rst
===
--- docs/ClangCommandLineReference.rst
+++ docs/ClangCommandLineReference.rst
@@ -2296,6 +2296,10 @@
 
 Reserve the x18 register (AArch64 only)
 
+.. option:: -ffixed-x20
+
+Reserve the x20 register (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2004,6 +2004,8 @@
   HelpText<"Don't workaround Cortex-A53 erratum 835769 (AArch64 only)">;
 def ffixed_x18 : Flag<["-"], "ffixed-x18">, Group,
   HelpText<"Reserve the x18 register (AArch64 only)">;
+def ffixed_x20 : Flag<["-"], "ffixed-x20">, Group,
+  HelpText<"Reserve the x20 register (AArch64 only)">;
 
 def msimd128 : Flag<["-"], "msimd128">, Group;
 def mno_simd128 : Flag<["-"], "mno-simd128">, Group;
Index: test/Driver/aarch64-fixed-x20.c
===
--- test/Driver/aarch64-fixed-x20.c
+++ test/Driver/aarch64-fixed-x20.c
@@ -0,0 +1,4 @@
+// RUN: %clang -target aarch64-none-gnu -ffixed-x20 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-FIXED-X20 < %t %s
+
+// CHECK-FIXED-X20: "-target-feature" "+reserve-x20"


Index: lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- lib/Driver/ToolChains/Arch/AArch64.cpp
+++ lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -198,6 +198,9 @@
   if (Args.hasArg(options::OPT_ffixed_x18))
 Features.push_back("+reserve-x18");
 
+  if (Args.hasArg(options::OPT_ffixed_x20))
+Features.push_back("+reserve-x20");
+
   if (Args.hasArg(options::OPT_mno_neg_immediates))
 Features.push_back("+no-neg-immediates");
 }
Index: docs/ClangCommandLineReference.rst
===
--- docs/ClangCommandLineReference.rst
+++ docs/ClangCommandLineReference.rst
@@ -2296,6 +2296,10 @@
 
 Reserve the x18 register (AArch64 only)
 
+.. option:: -ffixed-x20
+
+Reserve the x20 register (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2004,6 +2004,8 @@
   HelpText<"Don't workaround Cortex-A53 erratum 835769 (AArch64 only)">;
 def ffixed_x18 : Flag<["-"], "ffixed-x18">, Group,
   HelpText<"Reserve the x18 register (AArch64 only)">;
+def ffixed_x20 : Flag<["-"], "ffixed-x20">, Group,
+  HelpText<"Reserve the x20 register (AArch64 only)">;
 
 def msimd128 : Flag<["-"], "msimd128">, Group;
 def mno_simd128 : Flag<["-"], "mno-simd128">, Group;
Index: test/Driver/aarch64-fixed-x20.c
===
--- test/Driver/aarch64-fixed-x20.c
+++ test/Driver/aarch64-fixed-x20.c
@@ -0,0 +1,4 @@
+// RUN: %clang -target aarch64-none-gnu -ffixed-x20 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-FIXED-X20 < %t %s
+
+// CHECK-FIXED-X20: "-target-feature" "+reserve-x20"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r334494 - Re-apply r334418 "Enable crash recovery tests on Windows, globs work in the lit internal shell now"

2018-06-12 Thread Galina Kistanova via cfe-commits
Hello Hans,

The test Driver/crash-report-modules.m still fails on one of windows
builder:

http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win/builds/10221

. . .
Failing Tests (1):
Clang :: Driver/crash-report-modules.m

Please have a look?

Thanks

Galina



On Tue, Jun 12, 2018 at 4:51 AM, Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: hans
> Date: Tue Jun 12 04:51:22 2018
> New Revision: 334494
>
> URL: http://llvm.org/viewvc/llvm-project?rev=334494&view=rev
> Log:
> Re-apply r334418 "Enable crash recovery tests on Windows, globs work in
> the lit internal shell now"
>
> Plus change run lines from
>
>   not env FOO=bar %clang
>
> to
>
>   env FOO=bar not %clang
>
> To not confuse the internal shell.
>
> Modified:
> cfe/trunk/test/Driver/crash-report-header.h
> cfe/trunk/test/Driver/crash-report-modules.m
> cfe/trunk/test/Driver/crash-report-spaces.c
> cfe/trunk/test/Driver/crash-report.c
>
> Modified: cfe/trunk/test/Driver/crash-report-header.h
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/
> crash-report-header.h?rev=334494&r1=334493&r2=334494&view=diff
> 
> ==
> --- cfe/trunk/test/Driver/crash-report-header.h (original)
> +++ cfe/trunk/test/Driver/crash-report-header.h Tue Jun 12 04:51:22 2018
> @@ -1,13 +1,10 @@
>  // RUN: rm -rf %t
>  // RUN: mkdir %t
> -// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 %clang
> -fsyntax-only %s 2>&1 | FileCheck %s
> +// RUN: env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 not %clang
> -fsyntax-only %s 2>&1 | FileCheck %s
>  // RUN: cat %t/crash-report-header-*.h | FileCheck
> --check-prefix=CHECKSRC "%s"
>  // RUN: cat %t/crash-report-header-*.sh | FileCheck
> --check-prefix=CHECKSH "%s"
>  // REQUIRES: crash-recovery
>
> -// because of the glob (*.h, *.sh)
> -// REQUIRES: shell
> -
>  #pragma clang __debug parser_crash
>  // CHECK: Preprocessed source(s) and associated run script(s) are located
> at:
>  // CHECK-NEXT: note: diagnostic msg: {{.*}}.h
>
> Modified: cfe/trunk/test/Driver/crash-report-modules.m
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/
> crash-report-modules.m?rev=334494&r1=334493&r2=334494&view=diff
> 
> ==
> --- cfe/trunk/test/Driver/crash-report-modules.m (original)
> +++ cfe/trunk/test/Driver/crash-report-modules.m Tue Jun 12 04:51:22 2018
> @@ -1,20 +1,14 @@
>  // RUN: rm -rf %t
>  // RUN: mkdir -p %t/i %t/m %t
>
> -// RUN: not env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t \
> -// RUN: %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/\
> +// RUN: env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t  \
> +// RUN: not %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/ \
>  // RUN: -fmodules -fmodules-cache-path=%t/m/ -DFOO=BAR 2>&1 | FileCheck %s
>
>  // RUN: FileCheck --check-prefix=CHECKSRC %s -input-file
> %t/crash-report-*.m
>  // RUN: FileCheck --check-prefix=CHECKSH %s -input-file
> %t/crash-report-*.sh
>  // REQUIRES: crash-recovery
>
> -// because of the glob (*.m, *.sh)
> -// REQUIRES: shell
> -
> -// FIXME: This XFAIL is cargo-culted from crash-report.c. Do we need it?
> -// XFAIL: mingw32
> -
>  @import simple;
>  const int x = MODULE_MACRO;
>
> @@ -34,4 +28,4 @@ const int x = MODULE_MACRO;
>  // CHECKSH: "-D" "FOO=BAR"
>  // CHECKSH-NOT: "-fmodules-cache-path="
>  // CHECKSH: "crash-report-modules-{{[^ ]*}}.m"
> -// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^
> ]*}}.cache/vfs/vfs.yaml"
> +// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^
> ]*}}.cache{{(/|)}}vfs{{(/|)}}vfs.yaml"
>
> Modified: cfe/trunk/test/Driver/crash-report-spaces.c
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/
> crash-report-spaces.c?rev=334494&r1=334493&r2=334494&view=diff
> 
> ==
> --- cfe/trunk/test/Driver/crash-report-spaces.c (original)
> +++ cfe/trunk/test/Driver/crash-report-spaces.c Tue Jun 12 04:51:22 2018
> @@ -1,14 +1,11 @@
>  // RUN: rm -rf "%t"
>  // RUN: mkdir "%t"
>  // RUN: cp "%s" "%t/crash report spaces.c"
> -// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 %clang
> -fsyntax-only "%t/crash report spaces.c" 2>&1 | FileCheck "%s"
> +// RUN: env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 not %clang
> -fsyntax-only "%t/crash report spaces.c" 2>&1 | FileCheck "%s"
>  // RUN: cat "%t/crash report spaces"-*.c | FileCheck
> --check-prefix=CHECKSRC "%s"
>  // RUN: cat "%t/crash report spaces"-*.sh | FileCheck
> --check-prefix=CHECKSH "%s"
>  // REQUIRES: crash-recovery
>
> -// because of the glob (*.c, *.sh)
> -// REQUIRES: shell
> -
>  #pragma clang __debug parser_crash
>  // CHECK: Preprocessed source(s) and associated run script(s) are located
> at:
>  // CHECK-NEXT: note: diagnostic m

r334539 - Work around false -Wmissing-braces warning from old clang which has been fixed in r314838

2018-06-12 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Tue Jun 12 13:44:11 2018
New Revision: 334539

URL: http://llvm.org/viewvc/llvm-project?rev=334539&view=rev
Log:
Work around false -Wmissing-braces warning from old clang which has been fixed 
in r314838

Modified:
cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp?rev=334539&r1=334538&r2=334539&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp Tue Jun 12 
13:44:11 2018
@@ -883,7 +883,7 @@ UbigraphViz::~UbigraphViz() {
   std::string Ubiviz;
   if (auto Path = llvm::sys::findProgramByName("ubiviz"))
 Ubiviz = *Path;
-  std::array Args = {Ubiviz, Filename};
+  std::array Args{{Ubiviz, Filename}};
 
   if (llvm::sys::ExecuteAndWait(Ubiviz, Args, llvm::None, {}, 0, 0, &ErrMsg)) {
 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n";


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


[PATCH] D47996: Added modulemap for lldb-mi

2018-06-12 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl accepted this revision.
aprantl added a comment.
This revision is now accepted and ready to land.

That should work. Thanks!


https://reviews.llvm.org/D47996



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


Re: r334494 - Re-apply r334418 "Enable crash recovery tests on Windows, globs work in the lit internal shell now"

2018-06-12 Thread Reid Kleckner via cfe-commits
The length of that path is about 257, or very near MAX_PATH, which suggests
that the version of rm you are using does not tolerate deep paths. This has
been a long standing problem, and our solution to it was to install a
special version of rm.exe on all of our buildbots that reliably handles
long paths and copes with virus scanners and things.

We may try to fix this in lit by reimplementing 'rm' in python, but that is
not a near term solution.

On Tue, Jun 12, 2018 at 1:30 PM Galina Kistanova 
wrote:

> Hello Hans,
>
> The test Driver/crash-report-modules.m still fails on one of windows
> builder:
>
>
> http://lab.llvm.org:8011/builders/llvm-clang-x86_64-expensive-checks-win/builds/10221
>
> . . .
> Failing Tests (1):
> Clang :: Driver/crash-report-modules.m
>
> Please have a look?
>
> Thanks
>
> Galina
>
>
>
> On Tue, Jun 12, 2018 at 4:51 AM, Hans Wennborg via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: hans
>> Date: Tue Jun 12 04:51:22 2018
>> New Revision: 334494
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=334494&view=rev
>> Log:
>> Re-apply r334418 "Enable crash recovery tests on Windows, globs work in
>> the lit internal shell now"
>>
>> Plus change run lines from
>>
>>   not env FOO=bar %clang
>>
>> to
>>
>>   env FOO=bar not %clang
>>
>> To not confuse the internal shell.
>>
>> Modified:
>> cfe/trunk/test/Driver/crash-report-header.h
>> cfe/trunk/test/Driver/crash-report-modules.m
>> cfe/trunk/test/Driver/crash-report-spaces.c
>> cfe/trunk/test/Driver/crash-report.c
>>
>> Modified: cfe/trunk/test/Driver/crash-report-header.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-header.h?rev=334494&r1=334493&r2=334494&view=diff
>>
>> ==
>> --- cfe/trunk/test/Driver/crash-report-header.h (original)
>> +++ cfe/trunk/test/Driver/crash-report-header.h Tue Jun 12 04:51:22 2018
>> @@ -1,13 +1,10 @@
>>  // RUN: rm -rf %t
>>  // RUN: mkdir %t
>> -// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 %clang
>> -fsyntax-only %s 2>&1 | FileCheck %s
>> +// RUN: env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OPTIONS=1 not %clang
>> -fsyntax-only %s 2>&1 | FileCheck %s
>>  // RUN: cat %t/crash-report-header-*.h | FileCheck
>> --check-prefix=CHECKSRC "%s"
>>  // RUN: cat %t/crash-report-header-*.sh | FileCheck
>> --check-prefix=CHECKSH "%s"
>>  // REQUIRES: crash-recovery
>>
>> -// because of the glob (*.h, *.sh)
>> -// REQUIRES: shell
>> -
>>  #pragma clang __debug parser_crash
>>  // CHECK: Preprocessed source(s) and associated run script(s) are
>> located at:
>>  // CHECK-NEXT: note: diagnostic msg: {{.*}}.h
>>
>> Modified: cfe/trunk/test/Driver/crash-report-modules.m
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-modules.m?rev=334494&r1=334493&r2=334494&view=diff
>>
>> ==
>> --- cfe/trunk/test/Driver/crash-report-modules.m (original)
>> +++ cfe/trunk/test/Driver/crash-report-modules.m Tue Jun 12 04:51:22 2018
>> @@ -1,20 +1,14 @@
>>  // RUN: rm -rf %t
>>  // RUN: mkdir -p %t/i %t/m %t
>>
>> -// RUN: not env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t \
>> -// RUN: %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/\
>> +// RUN: env FORCE_CLANG_DIAGNOSTICS_CRASH= TMPDIR=%t TEMP=%t TMP=%t
>> \
>> +// RUN: not %clang -fsyntax-only %s -I %S/Inputs/module -isysroot %/t/i/
>> \
>>  // RUN: -fmodules -fmodules-cache-path=%t/m/ -DFOO=BAR 2>&1 | FileCheck
>> %s
>>
>>  // RUN: FileCheck --check-prefix=CHECKSRC %s -input-file
>> %t/crash-report-*.m
>>  // RUN: FileCheck --check-prefix=CHECKSH %s -input-file
>> %t/crash-report-*.sh
>>  // REQUIRES: crash-recovery
>>
>> -// because of the glob (*.m, *.sh)
>> -// REQUIRES: shell
>> -
>> -// FIXME: This XFAIL is cargo-culted from crash-report.c. Do we need it?
>> -// XFAIL: mingw32
>> -
>>  @import simple;
>>  const int x = MODULE_MACRO;
>>
>> @@ -34,4 +28,4 @@ const int x = MODULE_MACRO;
>>  // CHECKSH: "-D" "FOO=BAR"
>>  // CHECKSH-NOT: "-fmodules-cache-path="
>>  // CHECKSH: "crash-report-modules-{{[^ ]*}}.m"
>> -// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^
>> ]*}}.cache/vfs/vfs.yaml"
>> +// CHECKSH: "-ivfsoverlay" "crash-report-modules-{{[^
>> ]*}}.cache{{(/|)}}vfs{{(/|)}}vfs.yaml"
>>
>> Modified: cfe/trunk/test/Driver/crash-report-spaces.c
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/crash-report-spaces.c?rev=334494&r1=334493&r2=334494&view=diff
>>
>> ==
>> --- cfe/trunk/test/Driver/crash-report-spaces.c (original)
>> +++ cfe/trunk/test/Driver/crash-report-spaces.c Tue Jun 12 04:51:22 2018
>> @@ -1,14 +1,11 @@
>>  // RUN: rm -rf "%t"
>>  // RUN: mkdir "%t"
>>  // RUN: cp "%s" "%t/crash report spaces.c"
>> -// RUN: not env TMPDIR="%t" TEMP="%t" TMP="%t" RC_DEBUG_OP

r334540 - [analyzer] [NFC] Remove most usages of getEndPath

2018-06-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jun 12 13:50:44 2018
New Revision: 334540

URL: http://llvm.org/viewvc/llvm-project?rev=334540&view=rev
Log:
[analyzer] [NFC] Remove most usages of getEndPath

getEndPath is a problematic API, because it's not clear when it's called
(hint: not always at the end of the path), it crashes at runtime with
more than one non-nullptr returning implementation, and diagnostics
internal depend on it being called at some exact place.

However, most visitors don't actually need that: all they want is a
function consistently called after all nodes are traversed, to perform
finalization and to decide whether invalidation is needed.

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

Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h?rev=334540&r1=334539&r2=334540&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
Tue Jun 12 13:50:44 2018
@@ -73,12 +73,17 @@ public:
   VisitNode(const ExplodedNode *Succ, const ExplodedNode *Pred,
 BugReporterContext &BRC, BugReport &BR) = 0;
 
+  /// Last function called on the visitor, no further calls to VisitNode
+  /// would follow.
+  virtual void finalizeVisitor(BugReporterContext &BRC,
+   const ExplodedNode *EndPathNode,
+   BugReport &BR);
+
   /// Provide custom definition for the final diagnostic piece on the
   /// path - the piece, which is displayed before the path is expanded.
   ///
-  /// If returns NULL the default implementation will be used.
-  /// Also note that at most one visitor of a BugReport should generate a
-  /// non-NULL end of path diagnostic piece.
+  /// NOTE that this function can be implemented on at most one used visitor,
+  /// and otherwise it crahes at runtime.
   virtual std::unique_ptr
   getEndPath(BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR);
 
@@ -268,9 +273,8 @@ public:
 return nullptr;
   }
 
-  std::unique_ptr getEndPath(BugReporterContext &BRC,
-  const ExplodedNode *N,
-  BugReport &BR) override;
+  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
+   BugReport &BR) override;
 };
 
 /// When a region containing undefined value or '0' value is passed 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=334540&r1=334539&r2=334540&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Tue Jun 12 13:50:44 2018
@@ -1270,7 +1270,9 @@ static bool generatePathDiagnostics(
 PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
 LocationContextMap &LCM,
 ArrayRef> visitors,
+BugReport *R,
 PathDiagnosticConsumer::PathGenerationScheme ActiveScheme) {
+  const ExplodedNode *LastNode = N;
   BugReport *report = PDB.getBugReport();
   StackDiagVector CallStack;
   InterestingExprs IE;
@@ -1289,8 +1291,12 @@ static bool generatePathDiagnostics(
   generatePathDiagnosticsForNode(
   N, PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
 
-if (!NextNode)
+if (!NextNode) {
+  for (auto &V : visitors) {
+V->finalizeVisitor(PDB, LastNode, *R);
+  }
   continue;
+}
 
 // Add pieces from custom visitors.
 llvm::FoldingSet DeduplicationSet;
@@ -2583,7 +2589,7 @@ bool GRBugReporter::generatePathDiagnost
   // hold onto old mappings.
   LCM.clear();
 
-  generatePathDiagnostics(PD, PDB, N, LCM, visitors, ActiveScheme);
+  generatePathDiagnostics(PD, PDB, N, LCM, visitors, R, ActiveScheme);
 
   // Clean up the visitors we used.
   visitors.clear();

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=334540&r1=334539&r2=334540&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Tue Jun 12 
13:50:44 2018
@@ -181,6 +181,11 @@ BugReporterVisitor::getEndPath(BugReport
   return nul

[PATCH] D48042: [analyzer] Replace most usages of getEndPath

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334540: [analyzer] [NFC] Remove most usages of getEndPath 
(authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48042?vs=150805&id=151017#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48042

Files:
  include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Index: include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -73,12 +73,17 @@
   VisitNode(const ExplodedNode *Succ, const ExplodedNode *Pred,
 BugReporterContext &BRC, BugReport &BR) = 0;
 
+  /// Last function called on the visitor, no further calls to VisitNode
+  /// would follow.
+  virtual void finalizeVisitor(BugReporterContext &BRC,
+   const ExplodedNode *EndPathNode,
+   BugReport &BR);
+
   /// Provide custom definition for the final diagnostic piece on the
   /// path - the piece, which is displayed before the path is expanded.
   ///
-  /// If returns NULL the default implementation will be used.
-  /// Also note that at most one visitor of a BugReport should generate a
-  /// non-NULL end of path diagnostic piece.
+  /// NOTE that this function can be implemented on at most one used visitor,
+  /// and otherwise it crahes at runtime.
   virtual std::unique_ptr
   getEndPath(BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR);
 
@@ -268,9 +273,8 @@
 return nullptr;
   }
 
-  std::unique_ptr getEndPath(BugReporterContext &BRC,
-  const ExplodedNode *N,
-  BugReport &BR) override;
+  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
+   BugReport &BR) override;
 };
 
 /// When a region containing undefined value or '0' value is passed 
Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -181,6 +181,11 @@
   return nullptr;
 }
 
+void
+BugReporterVisitor::finalizeVisitor(BugReporterContext &BRC,
+const ExplodedNode *EndPathNode,
+BugReport &BR) {};
+
 std::unique_ptr BugReporterVisitor::getDefaultEndPath(
 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
   PathDiagnosticLocation L =
@@ -866,12 +871,10 @@
 llvm_unreachable("Invalid visit mode!");
   }
 
-  std::unique_ptr getEndPath(BugReporterContext &BRC,
-  const ExplodedNode *N,
-  BugReport &BR) override {
+  void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
+   BugReport &BR) override {
 if (EnableNullFPSuppression)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
-return nullptr;
   }
 };
 
@@ -2144,10 +2147,8 @@
  Piece->getString() == GenericFalseMessage;
 }
 
-std::unique_ptr
-LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
-const ExplodedNode *N,
-BugReport &BR) {
+void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
+BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
   // Here we suppress false positives coming from system headers. This list is
   // based on known issues.
   ExprEngine &Eng = BRC.getBugReporter().getEngine();
@@ -2161,7 +2162,7 @@
 // TR1, Boost, or llvm/ADT.
 if (Options.shouldSuppressFromCXXStandardLibrary()) {
   BR.markInvalid(getTag(), nullptr);
-  return nullptr;
+  return;
 } else {
   // If the complete 'std' suppression is not enabled, suppress reports
   // from the 'std' namespace that are known to produce false positives.
@@ -2173,7 +2174,7 @@
 const CXXRecordDecl *CD = MD->getParent();
 if (CD->getName() == "list") {
   BR.markInvalid(getTag(), nullptr);
-  return nullptr;
+  return;
 }
   }
 
@@ -2183,7 +2184,7 @@
 const CXXRecordDecl *CD = MD->getParent();
 if (CD->getName() == "__independent_bits_engine") {
   BR.markInvalid(getTag(), nullptr);
-  return nullptr;
+  return;
 }
   }
 
@@ -2202,15 +2203,15 @@
 // data structure.
 if (CD->getName() == "basic_string") {
   

r334541 - [analyzer] [NFC] Move ::dump methods from BugReporter.cpp to PathDiagnostics.cpp

2018-06-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jun 12 13:51:01 2018
New Revision: 334541

URL: http://llvm.org/viewvc/llvm-project?rev=334541&view=rev
Log:
[analyzer] [NFC] Move ::dump methods from BugReporter.cpp to PathDiagnostics.cpp

BugReporter.cpp is already severely overloaded, and those dump methods
are on PathDiagnostics and should belong in the corresponding
implementation file.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/PathDiagnostic.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h?rev=334541&r1=334540&r2=334541&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h 
Tue Jun 12 13:51:01 2018
@@ -296,6 +296,12 @@ public:
   }
 
   const Stmt *asStmt() const { assert(isValid()); return S; }
+  const Stmt *getStmtOrNull() const {
+if (!isValid())
+  return nullptr;
+return asStmt();
+  }
+
   const Decl *asDecl() const { assert(isValid()); return D; }
 
   bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=334541&r1=334540&r2=334541&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Tue Jun 12 13:51:01 2018
@@ -1338,12 +1338,6 @@ static bool generatePathDiagnostics(
   return true;
 }
 
-static const Stmt *getLocStmt(PathDiagnosticLocation L) {
-  if (!L.isValid())
-return nullptr;
-  return L.asStmt();
-}
-
 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
   if (!S)
 return nullptr;
@@ -1448,7 +1442,7 @@ static void addContextEdges(PathPieces &
 // This is important for nested logical expressions (||, &&, ?:) where we
 // want to show all the levels of context.
 while (true) {
-  const Stmt *Dst = getLocStmt(Piece->getEndLocation());
+  const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
 
   // We are looking at an edge. Is the destination within a larger
   // expression?
@@ -1471,9 +1465,11 @@ static void addContextEdges(PathPieces &
 auto *PrevPiece = 
dyn_cast(Prev->get());
 
 if (PrevPiece) {
-  if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) 
{
+  if (const Stmt *PrevSrc =
+  PrevPiece->getStartLocation().getStmtOrNull()) {
 const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
-if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
+if (PrevSrcParent ==
+getStmtParent(DstContext.getStmtOrNull(), PM)) {
   PrevPiece->setEndLocation(DstContext);
   break;
 }
@@ -1509,8 +1505,8 @@ static void simplifySimpleBranches(PathP
 if (!PieceI)
   continue;
 
-const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
-const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
+const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
+const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
 
 if (!s1Start || !s1End)
   continue;
@@ -1543,8 +1539,8 @@ static void simplifySimpleBranches(PathP
 if (!PieceNextI)
   continue;
 
-const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
-const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
+const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
+const Stmt *s2End   = PieceNextI->getEndLocation().getStmtOrNull();
 
 if (!s2Start || !s2End || s1End != s2Start)
   continue;
@@ -1634,8 +1630,8 @@ static void removeContextCycles(PathPiec
   continue;
 }
 
-const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
-const Stmt *s1End   = getLocStmt(PieceI->getEndLocation());
+const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
+const Stmt *s1End   = PieceI->getEndLocation().getStmtOrNull();
 
 PathPieces::iterator NextI = I; ++NextI;
 if (NextI == E)
@@ -1658,8 +1654,8 @@ static void removeContextCycles(PathPiec
   }
 }
 
-const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
-const Stmt *s2End   = getLocStmt(PieceNextI->getEndLocation());
+const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
+const Stmt *s2End   = PieceNextI->getEndLocation().get

r334542 - [analyzer] [NFC] Remove "removeInvalidation" from visitor API

2018-06-12 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Tue Jun 12 13:51:19 2018
New Revision: 334542

URL: http://llvm.org/viewvc/llvm-project?rev=334542&view=rev
Log:
[analyzer] [NFC] Remove "removeInvalidation" from visitor API

removeInvalidation is a very problematic API, as it makes suppression
order-dependent.
Moreover, it was used only once, and could be rewritten in a much
cleaner way.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h?rev=334542&r1=334541&r2=334542&view=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h Tue 
Jun 12 13:51:19 2018
@@ -253,13 +253,6 @@ public:
   void markInvalid(const void *Tag, const void *Data) {
 Invalidations.insert(std::make_pair(Tag, Data));
   }
-
-  /// Reverses the effects of a previous invalidation.
-  ///
-  /// \sa markInvalid
-  void removeInvalidation(const void *Tag, const void *Data) {
-Invalidations.erase(std::make_pair(Tag, Data));
-  }
   
   /// Return the canonical declaration, be it a method or class, where
   /// this issue semantically occurred.

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=334542&r1=334541&r2=334542&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Tue Jun 12 
13:51:19 2018
@@ -616,6 +616,7 @@ class ReturnVisitor : public BugReporter
   } Mode = Initial;
 
   bool EnableNullFPSuppression;
+  bool ShouldInvalidate = true;
 
 public:
   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
@@ -845,7 +846,7 @@ public:
 
   if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  EnableNullFPSuppression))
-BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
+ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
   // false negatives, and continue towards marking this report invalid.
@@ -873,7 +874,7 @@ public:
 
   void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
BugReport &BR) override {
-if (EnableNullFPSuppression)
+if (EnableNullFPSuppression && ShouldInvalidate)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
   }
 };


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


[PATCH] D48035: [analyzer] [NFC] Move ::dump methods from BugReporter.cpp to PathDiagnostics.cpp

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334541: [analyzer] [NFC] Move ::dump methods from 
BugReporter.cpp to PathDiagnostics.cpp (authored by george.karpenkov, committed 
by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48035?vs=150787&id=151018#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48035

Files:
  include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
  lib/StaticAnalyzer/Core/BugReporter.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp

Index: include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
===
--- include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
+++ include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
@@ -296,6 +296,12 @@
   }
 
   const Stmt *asStmt() const { assert(isValid()); return S; }
+  const Stmt *getStmtOrNull() const {
+if (!isValid())
+  return nullptr;
+return asStmt();
+  }
+
   const Decl *asDecl() const { assert(isValid()); return D; }
 
   bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; }
Index: lib/StaticAnalyzer/Core/PathDiagnostic.cpp
===
--- lib/StaticAnalyzer/Core/PathDiagnostic.cpp
+++ lib/StaticAnalyzer/Core/PathDiagnostic.cpp
@@ -1321,3 +1321,84 @@
 
   return os.str();
 }
+
+LLVM_DUMP_METHOD void PathPieces::dump() const {
+  unsigned index = 0;
+  for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
+llvm::errs() << "[" << index++ << "]  ";
+(*I)->dump();
+llvm::errs() << "\n";
+  }
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticCallPiece::dump() const {
+  llvm::errs() << "CALL\n--\n";
+
+  if (const Stmt *SLoc = getLocation().getStmtOrNull())
+SLoc->dump();
+  else if (const auto *ND = dyn_cast_or_null(getCallee()))
+llvm::errs() << *ND << "\n";
+  else
+getLocation().dump();
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticEventPiece::dump() const {
+  llvm::errs() << "EVENT\n--\n";
+  llvm::errs() << getString() << "\n";
+  llvm::errs() << "  at \n";
+  getLocation().dump();
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticControlFlowPiece::dump() const {
+  llvm::errs() << "CONTROL\n--\n";
+  getStartLocation().dump();
+  llvm::errs() << "  to \n";
+  getEndLocation().dump();
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticMacroPiece::dump() const {
+  llvm::errs() << "MACRO\n--\n";
+  // FIXME: Print which macro is being invoked.
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticNotePiece::dump() const {
+  llvm::errs() << "NOTE\n--\n";
+  llvm::errs() << getString() << "\n";
+  llvm::errs() << "  at \n";
+  getLocation().dump();
+}
+
+LLVM_DUMP_METHOD void PathDiagnosticLocation::dump() const {
+  if (!isValid()) {
+llvm::errs() << "\n";
+return;
+  }
+
+  switch (K) {
+  case RangeK:
+// FIXME: actually print the range.
+llvm::errs() << "\n";
+break;
+  case SingleLocK:
+asLocation().dump();
+llvm::errs() << "\n";
+break;
+  case StmtK:
+if (S)
+  S->dump();
+else
+  llvm::errs() << "\n";
+break;
+  case DeclK:
+if (const auto *ND = dyn_cast_or_null(D))
+  llvm::errs() << *ND << "\n";
+else if (isa(D))
+  // FIXME: Make this nicer.
+  llvm::errs() << "\n";
+else if (D)
+  llvm::errs() << "\n";
+else
+  llvm::errs() << "\n";
+break;
+  }
+}
Index: lib/StaticAnalyzer/Core/BugReporter.cpp
===
--- lib/StaticAnalyzer/Core/BugReporter.cpp
+++ lib/StaticAnalyzer/Core/BugReporter.cpp
@@ -1338,12 +1338,6 @@
   return true;
 }
 
-static const Stmt *getLocStmt(PathDiagnosticLocation L) {
-  if (!L.isValid())
-return nullptr;
-  return L.asStmt();
-}
-
 static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
   if (!S)
 return nullptr;
@@ -1448,7 +1442,7 @@
 // This is important for nested logical expressions (||, &&, ?:) where we
 // want to show all the levels of context.
 while (true) {
-  const Stmt *Dst = getLocStmt(Piece->getEndLocation());
+  const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
 
   // We are looking at an edge. Is the destination within a larger
   // expression?
@@ -1471,9 +1465,11 @@
 auto *PrevPiece = dyn_cast(Prev->get());
 
 if (PrevPiece) {
-  if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) {
+  if (const Stmt *PrevSrc =
+  PrevPiece->getStartLocation().getStmtOrNull()) {
 const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
-if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
+if (PrevSrcParent ==
+getStmtParent(DstContext.getStmtOrNull(), PM)) {
   PrevPiece->setEndLocation(D

[PATCH] D48045: [analyzer] [NFC] Remove "removeInvalidation" from visitor API

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL334542: [analyzer] [NFC] Remove 
"removeInvalidation" from visitor API (authored by george.karpenkov, 
committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48045?vs=150809&id=151020#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D48045

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp


Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -253,13 +253,6 @@
   void markInvalid(const void *Tag, const void *Data) {
 Invalidations.insert(std::make_pair(Tag, Data));
   }
-
-  /// Reverses the effects of a previous invalidation.
-  ///
-  /// \sa markInvalid
-  void removeInvalidation(const void *Tag, const void *Data) {
-Invalidations.erase(std::make_pair(Tag, Data));
-  }
   
   /// Return the canonical declaration, be it a method or class, where
   /// this issue semantically occurred.
Index: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -616,6 +616,7 @@
   } Mode = Initial;
 
   bool EnableNullFPSuppression;
+  bool ShouldInvalidate = true;
 
 public:
   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
@@ -845,7 +846,7 @@
 
   if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  EnableNullFPSuppression))
-BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
+ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
   // false negatives, and continue towards marking this report invalid.
@@ -873,7 +874,7 @@
 
   void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
BugReport &BR) override {
-if (EnableNullFPSuppression)
+if (EnableNullFPSuppression && ShouldInvalidate)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
   }
 };


Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -253,13 +253,6 @@
   void markInvalid(const void *Tag, const void *Data) {
 Invalidations.insert(std::make_pair(Tag, Data));
   }
-
-  /// Reverses the effects of a previous invalidation.
-  ///
-  /// \sa markInvalid
-  void removeInvalidation(const void *Tag, const void *Data) {
-Invalidations.erase(std::make_pair(Tag, Data));
-  }
   
   /// Return the canonical declaration, be it a method or class, where
   /// this issue semantically occurred.
Index: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -616,6 +616,7 @@
   } Mode = Initial;
 
   bool EnableNullFPSuppression;
+  bool ShouldInvalidate = true;
 
 public:
   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
@@ -845,7 +846,7 @@
 
   if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  EnableNullFPSuppression))
-BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
+ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
   // false negatives, and continue towards marking this report invalid.
@@ -873,7 +874,7 @@
 
   void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
BugReport &BR) override {
-if (EnableNullFPSuppression)
+if (EnableNullFPSuppression && ShouldInvalidate)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
   }
 };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48045: [analyzer] [NFC] Remove "removeInvalidation" from visitor API

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC334542: [analyzer] [NFC] Remove 
"removeInvalidation" from visitor API (authored by george.karpenkov, 
committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48045?vs=150809&id=151019#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48045

Files:
  include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
  lib/StaticAnalyzer/Core/BugReporterVisitors.cpp


Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -616,6 +616,7 @@
   } Mode = Initial;
 
   bool EnableNullFPSuppression;
+  bool ShouldInvalidate = true;
 
 public:
   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
@@ -845,7 +846,7 @@
 
   if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  EnableNullFPSuppression))
-BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
+ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
   // false negatives, and continue towards marking this report invalid.
@@ -873,7 +874,7 @@
 
   void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
BugReport &BR) override {
-if (EnableNullFPSuppression)
+if (EnableNullFPSuppression && ShouldInvalidate)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
   }
 };
Index: include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -253,13 +253,6 @@
   void markInvalid(const void *Tag, const void *Data) {
 Invalidations.insert(std::make_pair(Tag, Data));
   }
-
-  /// Reverses the effects of a previous invalidation.
-  ///
-  /// \sa markInvalid
-  void removeInvalidation(const void *Tag, const void *Data) {
-Invalidations.erase(std::make_pair(Tag, Data));
-  }
   
   /// Return the canonical declaration, be it a method or class, where
   /// this issue semantically occurred.


Index: lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -616,6 +616,7 @@
   } Mode = Initial;
 
   bool EnableNullFPSuppression;
+  bool ShouldInvalidate = true;
 
 public:
   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
@@ -845,7 +846,7 @@
 
   if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  EnableNullFPSuppression))
-BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
+ShouldInvalidate = false;
 
   // If we /can't/ track the null pointer, we should err on the side of
   // false negatives, and continue towards marking this report invalid.
@@ -873,7 +874,7 @@
 
   void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
BugReport &BR) override {
-if (EnableNullFPSuppression)
+if (EnableNullFPSuppression && ShouldInvalidate)
   BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
   }
 };
Index: include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
===
--- include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
+++ include/clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
@@ -253,13 +253,6 @@
   void markInvalid(const void *Tag, const void *Data) {
 Invalidations.insert(std::make_pair(Tag, Data));
   }
-
-  /// Reverses the effects of a previous invalidation.
-  ///
-  /// \sa markInvalid
-  void removeInvalidation(const void *Tag, const void *Data) {
-Invalidations.erase(std::make_pair(Tag, Data));
-  }
   
   /// Return the canonical declaration, be it a method or class, where
   /// this issue semantically occurred.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46915: [Fixed Point Arithmetic] Fixed Point Precision Bits and Fixed Point Literals

2018-06-12 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan updated this revision to Diff 151016.
leonardchan marked 9 inline comments as done.

Repository:
  rC Clang

https://reviews.llvm.org/D46915

Files:
  include/clang/AST/ASTContext.h
  include/clang/AST/Expr.h
  include/clang/AST/OperationKinds.def
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/AST/Type.h
  include/clang/Basic/DiagnosticCommonKinds.td
  include/clang/Basic/LangOptions.def
  include/clang/Basic/StmtNodes.td
  include/clang/Basic/TargetInfo.h
  include/clang/Driver/Options.td
  include/clang/Lex/LiteralSupport.h
  lib/AST/ASTContext.cpp
  lib/AST/ASTDumper.cpp
  lib/AST/Expr.cpp
  lib/AST/ExprClassification.cpp
  lib/AST/ExprConstant.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/StmtProfile.cpp
  lib/AST/Type.cpp
  lib/Basic/TargetInfo.cpp
  lib/Basic/Targets.cpp
  lib/CodeGen/CGExpr.cpp
  lib/CodeGen/CGExprAgg.cpp
  lib/CodeGen/CGExprComplex.cpp
  lib/CodeGen/CGExprConstant.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Edit/RewriteObjCFoundationAPI.cpp
  lib/Frontend/CompilerInvocation.cpp
  lib/Index/USRGeneration.cpp
  lib/Lex/LiteralSupport.cpp
  lib/Sema/Sema.cpp
  lib/Sema/SemaExceptionSpec.cpp
  lib/Sema/SemaExpr.cpp
  lib/Sema/TreeTransform.h
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineC.cpp
  test/Frontend/fixed_point.c
  test/Frontend/fixed_point_declarations.c
  test/Frontend/fixed_point_errors.c
  test/Frontend/fixed_point_same_fbits.c
  test/Frontend/fixed_point_validation.c
  tools/libclang/CXCursor.cpp

Index: tools/libclang/CXCursor.cpp
===
--- tools/libclang/CXCursor.cpp
+++ tools/libclang/CXCursor.cpp
@@ -305,6 +305,10 @@
 K = CXCursor_IntegerLiteral;
 break;
 
+  case Stmt::FixedPointLiteralClass:
+llvm_unreachable("No cursor for FixedPointLiteralClass");
+break;
+
   case Stmt::FloatingLiteralClass:
 K = CXCursor_FloatingLiteral;
 break;
Index: test/Frontend/fixed_point_validation.c
===
--- /dev/null
+++ test/Frontend/fixed_point_validation.c
@@ -0,0 +1,19 @@
+// RUN: %clang -ffixed-point -S -emit-llvm -o - %s | lli -force-interpreter=true
+
+// Run simple validation tests
+
+#define assert(b) if (!(b)) { return 1; }
+
+int main(){
+  short _Accum s_accum = 0.0hk;
+  short _Accum s_accum2 = 2.0hk;
+  short _Fract s_fract = 0.999hr;
+  short _Fract s_fract2 = -0.999hr;
+
+  assert(s_accum == 0);
+
+  s_accum = s_accum2;
+
+  assert(s_accum == s_accum2);
+  assert(s_accum == 2);
+}
Index: test/Frontend/fixed_point_same_fbits.c
===
--- /dev/null
+++ test/Frontend/fixed_point_same_fbits.c
@@ -0,0 +1,28 @@
+// RUN: %clang -ffixed-point -S -emit-llvm -o - %s | FileCheck %s -check-prefix=DEFAULT
+// RUN: %clang -ffixed-point -fsame-fbits -S -emit-llvm -o - %s | FileCheck %s -check-prefix=SAME
+
+/* The scale for unsigned fixed point types should be the same as that of signed
+ * fixed point types when -fsame-fbits is enabled. */
+
+void func() {
+  unsigned short _Accum u_short_accum = 0.5uhk;
+  unsigned _Accum u_accum = 0.5uk;
+  unsigned long _Accum u_long_accum = 0.5ulk;
+  unsigned short _Fract u_short_fract = 0.5uhr;
+  unsigned _Fract u_fract = 0.5ur;
+  unsigned long _Fract u_long_fract = 0.5ulr;
+
+// DEFAULT: store i16 128, i16* %u_short_accum, align 2
+// DEFAULT: store i32 32768, i32* %u_accum, align 4
+// DEFAULT: store i64 2147483648, i64* %u_long_accum, align 8
+// DEFAULT: store i16 128, i16* %u_short_fract, align 2
+// DEFAULT: store i32 32768, i32* %u_fract, align 4
+// DEFAULT: store i64 2147483648, i64* %u_long_fract, align 8
+
+// SAME: store i16 64, i16* %u_short_accum, align 2
+// SAME: store i32 16384, i32* %u_accum, align 4
+// SAME: store i64 1073741824, i64* %u_long_accum, align 8
+// SAME: store i16 64, i16* %u_short_fract, align 2
+// SAME: store i32 16384, i32* %u_fract, align 4
+// SAME: store i64 1073741824, i64* %u_long_fract, align 8
+}
Index: test/Frontend/fixed_point_errors.c
===
--- test/Frontend/fixed_point_errors.c
+++ test/Frontend/fixed_point_errors.c
@@ -13,7 +13,6 @@
 _Sat long long _Fract sat_longlong_fract; // expected-error{{'long long _Fract' is invalid}}
 _Sat unsigned long long _Fract sat_u_longlong_fract;  // expected-error{{'long long _Fract' is invalid}}
 
-
 /* Although _Complex types work with floating point numbers, the extension
  * provides no info for complex fixed point types. */
 
@@ -78,6 +77,50 @@
 _Sat int i;   // expected-error{{'_Sat' specifier is only valid on '_Fract' or '_Accum', not 'int'}}
 _Sat _Sat _Fract fract;   // expected-warning{{duplicate '_Sat' declaration specifier}}
 
+
+/* Literals that cannot fit into types */
+signed sh

[PATCH] D48053: Correct behavior of __builtin_*_overflow and constexpr.

2018-06-12 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM


https://reviews.llvm.org/D48053



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


[PATCH] D46915: [Fixed Point Arithmetic] Fixed Point Precision Bits and Fixed Point Literals

2018-06-12 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added inline comments.



Comment at: include/clang/Basic/TargetInfo.h:89
+  // corresponding unsaturated types.
+  unsigned char ShortAccumFBits, ShortAccumIBits;
+  unsigned char AccumFBits, AccumIBits;

ebevhan wrote:
> leonardchan wrote:
> > ebevhan wrote:
> > > I suspect it's still possible to calculate the ibits based on the fbits, 
> > > even for _Accum.
> > > 
> > > Are the unsigned values needed? The fbits for unsigned _Fract are the 
> > > same as for signed _Fract if SameFBits is set, and +1 otherwise. The same 
> > > should go for unsigned _Accum, but I don't think it's entirely clear how 
> > > this affects the integral part.
> > Similar to the previous comment, if we choose to make SameFBits dependent 
> > on/controlled by the target, then I think it would be better for the target 
> > to explicitly specify the integral bits since there could be some cases 
> > where there may be padding (such as for unsigned _Accum types if this flag 
> > is set), and in this case, I think it should be explicit that the 
> > `bit_width != IBits + FBits`.
> > 
> > We also can't fill in that padding for the unsigned _Accum types as an 
> > extra integral bit since the standard says that `"each signed accum type 
> > has at least as many integral bits as its corresponding unsigned accum 
> > type".`
> > 
> > For the unsigned _Fract values, I think we can get rid of them if we choose 
> > to keep the flag instead, but it would no longer apply to unsigned _Accum 
> > types since it would allow for extra padding in these types and would 
> > conflict with the logic of `bit_width == IBits + FBits`
> > 
> > For now, I actually think the simplest option is to keep these target 
> > properties, but have the target override them individually, with checks to 
> > make sure the values adhere to the standard.
> Is it not the case that `bitwidth != IBits + FBits` for signed types only? 
> Signed types require a sign bit (which is neither a fractional bit nor an 
> integral bit, according to spec) but unsigned types do not, and if IBits and 
> FBits for the signed and unsigned types are the same, the MSB is simply a 
> padding bit, at least for _Accum (for _Fract everything above the fbits is 
> padding). 
> 
> My reasoning for keeping the number of configurable values down was to limit 
> the number of twiddly knobs to make the implementation simpler. Granting a 
> lot of freedom is nice, but I suspect that it will be quite hard to get the 
> implementation working properly for every valid configuration. I also don't 
> really see much of a reason for `FBits != UFBits` in general. I know the spec 
> gives a recommendation to implement it that way, but I think the benefit of 
> normalizing the signed and unsigned representations outweighs the lost bit in 
> the unsigned type.
> 
> It's hard to say what the differences are beyond that since I'm not sure how 
> you plan on treating padding bits. In our implementation, padding bits (the 
> MSB in all of the unsigned types for us) after any operation are zeroed.
I see. The implementation would be much simpler this way. The initial idea was 
to treat the padding bits as "don't care" bits where we would mask only the 
data bits when doing operations like comparisons that look at the whole integer.



Comment at: lib/Lex/LiteralSupport.cpp:737
+  if (!hadError && saw_fixed_point_suffix) {
+assert(isFract || isAccum);
+assert(radix == 16 || radix == 10);

ebevhan wrote:
> Is `saw_fixed_point_suffix` only used for this assertion? Doesn't `isFract || 
> isAccum` imply `saw_fixed_point_suffix`?
`saw_fixed_point_suffix` is also used to check `isFixedPointLiteral()` which in 
turn is also used to check if not `isIntegerLiteral()` and not 
`isFloatingLiteral()` which are called early on in the constructor.

I could substitute where `saw_fixed_point_suffix` is set true to either setting 
`isAccum` or `isFract` but thought saving those for iterating through the 
suffixes would make checking for repeated `r` or `k` simpler.



Comment at: lib/Lex/LiteralSupport.cpp:1065
+
+while (!IsExponentPart(*Ptr)) ++Ptr;
+++Ptr;

ebevhan wrote:
> This whole block is very diligent but I wonder how common overflow in the 
> exponent is.
> 
> I'm unsure if LLVM has a helper function with `atoll`-like functionality, but 
> if it does it's a lot less code to just use that instead. There's also 
> APInt's `fromString`, but that seems to assert if the integer doesn't fit in 
> the bitwidth. The required bitwidth can be calculated here, though.
Used an APInt instead. It probably won't occur very often, but I would like to 
cover extreme cases.



Comment at: lib/Lex/LiteralSupport.cpp:1175
+  // number of digits past the radix point.
+  --FractBaseShift;
+}

ebevhan wrote:
> This is technically Exponent.
For hex types, the exponent base is 2 but

[PATCH] D47988: [CodeGen] Emit MSVC funclet IR for Obj-C exceptions

2018-06-12 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

In https://reviews.llvm.org/D47988#1127432, @smeenai wrote:

> Any idea why we would see inlining in one case and not the other? i686 vs. 
> x86-64 doesn't make any difference, and neither does -Os vs. -O1 vs. -O2.


My theory is that the inliner is attempting to avoid inlining on cold codepaths 
that are post-dominated by unreachable. When you put an outer try around it, 
the function may continue by unwinding, so the inline cost analysis gives 
different results. Of course, that's all just a wild guess.


Repository:
  rC Clang

https://reviews.llvm.org/D47988



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


[PATCH] D47030: [Fixed Point Arithmetic] Checks for Precision Macros

2018-06-12 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan abandoned this revision.
leonardchan added a comment.

No longer setting fractional and integral bits at configure time. These values 
are set and checked in TargetInfo.


Repository:
  rC Clang

https://reviews.llvm.org/D47030



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


r334550 - [CMake][Darwin] Match cxx-headers -> cxx_headers libcxx target rename.

2018-06-12 Thread Ahmed Bougacha via cfe-commits
Author: ab
Date: Tue Jun 12 14:27:36 2018
New Revision: 334550

URL: http://llvm.org/viewvc/llvm-project?rev=334550&view=rev
Log:
[CMake][Darwin] Match cxx-headers -> cxx_headers libcxx target rename.

This was changed in r334477.

Modified:
cfe/trunk/cmake/caches/Apple-stage2.cmake

Modified: cfe/trunk/cmake/caches/Apple-stage2.cmake
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/cmake/caches/Apple-stage2.cmake?rev=334550&r1=334549&r2=334550&view=diff
==
--- cfe/trunk/cmake/caches/Apple-stage2.cmake (original)
+++ cfe/trunk/cmake/caches/Apple-stage2.cmake Tue Jun 12 14:27:36 2018
@@ -61,7 +61,7 @@ set(LLVM_DISTRIBUTION_COMPONENTS
   LTO
   clang-format
   clang-headers
-  cxx-headers
+  cxx_headers
   ${LLVM_TOOLCHAIN_TOOLS}
   CACHE STRING "")
 


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


Re: [libcxx] r334477 - [CMake] Use common variable for all header targets NFC

2018-06-12 Thread Ahmed Bougacha via cfe-commits
Hey Petr,

FYI: clang has cmake caches that listed cxx-headers as a dependency;
I fixed that in:
r334550 [CMake][Darwin] Match cxx-headers -> cxx_headers libcxx target rename.

-Ahmed


On Mon, Jun 11, 2018 at 11:58 PM, Petr Hosek via cfe-commits
 wrote:
> Author: phosek
> Date: Mon Jun 11 23:58:06 2018
> New Revision: 334477
>
> URL: http://llvm.org/viewvc/llvm-project?rev=334477&view=rev
> Log:
> [CMake] Use common variable for all header targets NFC
>
> This simplifies the handling of header targets.
>
> Modified:
> libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake
> libcxx/trunk/include/CMakeLists.txt
> libcxx/trunk/lib/CMakeLists.txt
>
> Modified: libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake
> URL: 
> http://llvm.org/viewvc/llvm-project/libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake?rev=334477&r1=334476&r2=334477&view=diff
> ==
> --- libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake (original)
> +++ libcxx/trunk/cmake/Modules/HandleLibCXXABI.cmake Mon Jun 11 23:58:06 2018
> @@ -78,8 +78,8 @@ macro(setup_abi_lib abidefines abilib ab
>endforeach()
>
>include_directories("${LIBCXX_BINARY_INCLUDE_DIR}")
> -  add_custom_target(cxx-abi-headers ALL DEPENDS ${abilib_headers})
> -  set(LIBCXX_ABI_HEADERS_TARGET cxx-abi-headers)
> +  add_custom_target(cxx_abi_headers ALL DEPENDS ${abilib_headers})
> +  set(LIBCXX_CXX_ABI_HEADER_TARGET "cxx_abi_headers")
>  endmacro()
>
>
>
> Modified: libcxx/trunk/include/CMakeLists.txt
> URL: 
> http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/CMakeLists.txt?rev=334477&r1=334476&r2=334477&view=diff
> ==
> --- libcxx/trunk/include/CMakeLists.txt (original)
> +++ libcxx/trunk/include/CMakeLists.txt Mon Jun 11 23:58:06 2018
> @@ -228,11 +228,11 @@ if(NOT LIBCXX_USING_INSTALLED_LLVM AND L
>  list(APPEND out_files ${dst})
>endif()
>
> -  add_custom_target(cxx-headers ALL DEPENDS ${out_files} 
> ${LIBCXX_CXX_ABI_LIBRARY_HEADERS})
> +  add_custom_target(cxx_headers ALL DEPENDS ${out_files} 
> ${LIBCXX_CXX_ABI_HEADER_TARGET})
>  else()
> -  add_custom_target(cxx-headers)
> +  add_custom_target(cxx_headers)
>  endif()
> -set_target_properties(cxx-headers PROPERTIES FOLDER "Misc")
> +set_target_properties(cxx_headers PROPERTIES FOLDER "Misc")
>
>  if (LIBCXX_INSTALL_HEADERS)
>foreach(file ${files})
>
> Modified: libcxx/trunk/lib/CMakeLists.txt
> URL: 
> http://llvm.org/viewvc/llvm-project/libcxx/trunk/lib/CMakeLists.txt?rev=334477&r1=334476&r2=334477&view=diff
> ==
> --- libcxx/trunk/lib/CMakeLists.txt (original)
> +++ libcxx/trunk/lib/CMakeLists.txt Mon Jun 11 23:58:06 2018
> @@ -189,8 +189,8 @@ split_list(LIBCXX_LINK_FLAGS)
>
>  # Add an object library that contains the compiled source files.
>  add_library(cxx_objects OBJECT ${exclude_from_all} ${LIBCXX_SOURCES} 
> ${LIBCXX_HEADERS})
> -if(LIBCXX_CXX_ABI_LIBRARY_HEADERS)
> -  add_dependencies(cxx_objects ${LIBCXX_CXX_ABI_LIBRARY_HEADERS})
> +if(LIBCXX_CXX_ABI_HEADER_TARGET)
> +  add_dependencies(cxx_objects ${LIBCXX_CXX_ABI_HEADER_TARGET})
>  endif()
>  if(WIN32 AND NOT MINGW)
>target_compile_definitions(cxx_objects
> @@ -286,8 +286,7 @@ if (LIBCXX_ENABLE_STATIC)
>  endif()
>
>  # Add a meta-target for both libraries.
> -add_custom_target(cxx DEPENDS ${LIBCXX_TARGETS})
> -add_dependencies(cxx cxx-headers ${LIBCXX_ABI_HEADERS_TARGET})
> +add_custom_target(cxx DEPENDS cxx_headers ${LIBCXX_TARGETS})
>
>  if (LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY)
>file(GLOB LIBCXX_EXPERIMENTAL_SOURCES ../src/experimental/*.cpp)
>
>
> ___
> 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] D48098: clang-format-diff: Switch to python3 by default, support python 2.7

2018-06-12 Thread Marco Falke via Phabricator via cfe-commits
MarcoFalke created this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D48098

Files:
  tools/clang-format/clang-format-diff.py


Index: tools/clang-format/clang-format-diff.py
===
--- tools/clang-format/clang-format-diff.py
+++ tools/clang-format/clang-format-diff.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- clang-format-diff.py - ClangFormat Diff Reformatter *- python 
-*--===#
 #
@@ -24,10 +24,9 @@
 
 import argparse
 import difflib
+import io
 import re
-import string
 import subprocess
-import StringIO
 import sys
 
 
@@ -84,14 +83,14 @@
 line_count = int(match.group(3))
   if line_count == 0:
 continue
-  end_line = start_line + line_count - 1;
+  end_line = start_line + line_count - 1
   lines_by_file.setdefault(filename, []).extend(
   ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
 if args.i and args.verbose:
-  print 'Formatting', filename
+  print('Formatting {}'.format(filename))
 command = [args.binary, filename]
 if args.i:
   command.append('-i')
@@ -100,20 +99,23 @@
 command.extend(lines)
 if args.style:
   command.extend(['-style', args.style])
-p = subprocess.Popen(command, stdout=subprocess.PIPE,
- stderr=None, stdin=subprocess.PIPE)
+p = subprocess.Popen(command,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ stdin=subprocess.PIPE,
+ universal_newlines=True)
 stdout, stderr = p.communicate()
 if p.returncode != 0:
-  sys.exit(p.returncode);
+  sys.exit(p.returncode)
 
 if not args.i:
-  with open(filename) as f:
+  with open(filename, encoding="utf8") as f:
 code = f.readlines()
-  formatted_code = StringIO.StringIO(stdout).readlines()
+  formatted_code = io.StringIO(stdout).readlines()
   diff = difflib.unified_diff(code, formatted_code,
   filename, filename,
   '(before formatting)', '(after formatting)')
-  diff_string = string.join(diff, '')
+  diff_string = ''.join(diff)
   if len(diff_string) > 0:
 sys.stdout.write(diff_string)
 


Index: tools/clang-format/clang-format-diff.py
===
--- tools/clang-format/clang-format-diff.py
+++ tools/clang-format/clang-format-diff.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- clang-format-diff.py - ClangFormat Diff Reformatter *- python -*--===#
 #
@@ -24,10 +24,9 @@
 
 import argparse
 import difflib
+import io
 import re
-import string
 import subprocess
-import StringIO
 import sys
 
 
@@ -84,14 +83,14 @@
 line_count = int(match.group(3))
   if line_count == 0:
 continue
-  end_line = start_line + line_count - 1;
+  end_line = start_line + line_count - 1
   lines_by_file.setdefault(filename, []).extend(
   ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
 if args.i and args.verbose:
-  print 'Formatting', filename
+  print('Formatting {}'.format(filename))
 command = [args.binary, filename]
 if args.i:
   command.append('-i')
@@ -100,20 +99,23 @@
 command.extend(lines)
 if args.style:
   command.extend(['-style', args.style])
-p = subprocess.Popen(command, stdout=subprocess.PIPE,
- stderr=None, stdin=subprocess.PIPE)
+p = subprocess.Popen(command,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ stdin=subprocess.PIPE,
+ universal_newlines=True)
 stdout, stderr = p.communicate()
 if p.returncode != 0:
-  sys.exit(p.returncode);
+  sys.exit(p.returncode)
 
 if not args.i:
-  with open(filename) as f:
+  with open(filename, encoding="utf8") as f:
 code = f.readlines()
-  formatted_code = StringIO.StringIO(stdout).readlines()
+  formatted_code = io.StringIO(stdout).readlines()
   diff = difflib.unified_diff(code, formatted_code,
   filename, filename,
   '(before formatting)', '(after formatting)')
-  diff_string = string.join(diff, '')
+  diff_string = ''.join(diff)
   if len(diff_string) > 0:
 sys.stdout.write(diff_string)
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48098: clang-format-diff: Switch to python3 by default, support python 2.7

2018-06-12 Thread Marco Falke via Phabricator via cfe-commits
MarcoFalke updated this revision to Diff 151038.
MarcoFalke added a comment.

In python2.7:
TypeError: 'encoding' is an invalid keyword argument for this function

So remove it for now.


https://reviews.llvm.org/D48098

Files:
  tools/clang-format/clang-format-diff.py


Index: tools/clang-format/clang-format-diff.py
===
--- tools/clang-format/clang-format-diff.py
+++ tools/clang-format/clang-format-diff.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- clang-format-diff.py - ClangFormat Diff Reformatter *- python 
-*--===#
 #
@@ -24,10 +24,9 @@
 
 import argparse
 import difflib
+import io
 import re
-import string
 import subprocess
-import StringIO
 import sys
 
 
@@ -84,14 +83,14 @@
 line_count = int(match.group(3))
   if line_count == 0:
 continue
-  end_line = start_line + line_count - 1;
+  end_line = start_line + line_count - 1
   lines_by_file.setdefault(filename, []).extend(
   ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
 if args.i and args.verbose:
-  print 'Formatting', filename
+  print('Formatting {}'.format(filename))
 command = [args.binary, filename]
 if args.i:
   command.append('-i')
@@ -100,20 +99,23 @@
 command.extend(lines)
 if args.style:
   command.extend(['-style', args.style])
-p = subprocess.Popen(command, stdout=subprocess.PIPE,
- stderr=None, stdin=subprocess.PIPE)
+p = subprocess.Popen(command,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ stdin=subprocess.PIPE,
+ universal_newlines=True)
 stdout, stderr = p.communicate()
 if p.returncode != 0:
-  sys.exit(p.returncode);
+  sys.exit(p.returncode)
 
 if not args.i:
   with open(filename) as f:
 code = f.readlines()
-  formatted_code = StringIO.StringIO(stdout).readlines()
+  formatted_code = io.StringIO(stdout).readlines()
   diff = difflib.unified_diff(code, formatted_code,
   filename, filename,
   '(before formatting)', '(after formatting)')
-  diff_string = string.join(diff, '')
+  diff_string = ''.join(diff)
   if len(diff_string) > 0:
 sys.stdout.write(diff_string)
 


Index: tools/clang-format/clang-format-diff.py
===
--- tools/clang-format/clang-format-diff.py
+++ tools/clang-format/clang-format-diff.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- clang-format-diff.py - ClangFormat Diff Reformatter *- python -*--===#
 #
@@ -24,10 +24,9 @@
 
 import argparse
 import difflib
+import io
 import re
-import string
 import subprocess
-import StringIO
 import sys
 
 
@@ -84,14 +83,14 @@
 line_count = int(match.group(3))
   if line_count == 0:
 continue
-  end_line = start_line + line_count - 1;
+  end_line = start_line + line_count - 1
   lines_by_file.setdefault(filename, []).extend(
   ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
 if args.i and args.verbose:
-  print 'Formatting', filename
+  print('Formatting {}'.format(filename))
 command = [args.binary, filename]
 if args.i:
   command.append('-i')
@@ -100,20 +99,23 @@
 command.extend(lines)
 if args.style:
   command.extend(['-style', args.style])
-p = subprocess.Popen(command, stdout=subprocess.PIPE,
- stderr=None, stdin=subprocess.PIPE)
+p = subprocess.Popen(command,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ stdin=subprocess.PIPE,
+ universal_newlines=True)
 stdout, stderr = p.communicate()
 if p.returncode != 0:
-  sys.exit(p.returncode);
+  sys.exit(p.returncode)
 
 if not args.i:
   with open(filename) as f:
 code = f.readlines()
-  formatted_code = StringIO.StringIO(stdout).readlines()
+  formatted_code = io.StringIO(stdout).readlines()
   diff = difflib.unified_diff(code, formatted_code,
   filename, filename,
   '(before formatting)', '(after formatting)')
-  diff_string = string.join(diff, '')
+  diff_string = ''.join(diff)
   if len(diff_string) > 0:
 sys.stdout.write(diff_string)
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/ma

[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris updated this revision to Diff 151043.
ormris added a comment.

- Use match function iterators rather than a callback class
- Update test


Repository:
  rC Clang

https://reviews.llvm.org/D47044

Files:
  lib/StaticAnalyzer/Core/LoopWidening.cpp
  test/Analysis/loop-widening-preserve-reference-type.cpp


Index: test/Analysis/loop-widening-preserve-reference-type.cpp
===
--- /dev/null
+++ test/Analysis/loop-widening-preserve-reference-type.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-max-loop 4 
-analyzer-config widen-loops=true -verify %s
+
+void clang_analyzer_eval(int);
+
+struct A {
+  ~A() {}
+};
+struct B : public A {};
+
+void invalid_type_region_access() {
+  const A &x = B();
+  for (int i = 0; i < 10; ++i) { }
+  clang_analyzer_eval(&x != 0); // expected-warning{{TRUE}}
+}   // expected-warning@-1{{reference cannot be 
bound to dereferenced null pointer in well-defined C++ code; comparison may be 
assumed to always evaluate to true}}
Index: lib/StaticAnalyzer/Core/LoopWidening.cpp
===
--- lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -14,10 +14,17 @@
 ///
 
//===--===//
 
+#include "clang/AST/AST.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
+#include "llvm/ADT/SmallSet.h"
 
 using namespace clang;
 using namespace ento;
+using namespace clang::ast_matchers;
+
+const auto MatchRef = "matchref";
 
 /// Return the loops condition Stmt or NULL if LoopStmt is not a loop
 static const Expr *getLoopCondition(const Stmt *LoopStmt) {
@@ -49,6 +56,7 @@
   // TODO Nested loops are currently widened as a result of the invalidation
   //  being so inprecise. When the invalidation is improved, the handling
   //  of nested loops will also need to be improved.
+  ASTContext &ASTCtx = LCtx->getAnalysisDeclContext()->getASTContext();
   const StackFrameContext *STC = LCtx->getCurrentStackFrame();
   MemRegionManager &MRMgr = PrevState->getStateManager().getRegionManager();
   const MemRegion *Regions[] = {MRMgr.getStackLocalsRegion(STC),
@@ -60,6 +68,18 @@
  RegionAndSymbolInvalidationTraits::TK_EntireMemSpace);
   }
 
+  // References should not be invalidated.
+  auto Matches = 
match(findAll(stmt(hasDescendant(varDecl(hasType(referenceType())).bind(MatchRef,
+   *LCtx->getDecl()->getBody(), ASTCtx);
+  for (BoundNodes Match : Matches) {
+const VarDecl *VD = Match.getNodeAs(MatchRef);
+assert(VD);
+const VarRegion *VarMem = MRMgr.getVarRegion(VD, LCtx);
+ITraits.setTrait(VarMem,
+ RegionAndSymbolInvalidationTraits::TK_PreserveContents);
+  }
+
+
   // 'this' pointer is not an lvalue, we should not invalidate it. If the loop
   // is located in a method, constructor or destructor, the value of 'this'
   // pointer shoule remain unchanged.


Index: test/Analysis/loop-widening-preserve-reference-type.cpp
===
--- /dev/null
+++ test/Analysis/loop-widening-preserve-reference-type.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-max-loop 4 -analyzer-config widen-loops=true -verify %s
+
+void clang_analyzer_eval(int);
+
+struct A {
+  ~A() {}
+};
+struct B : public A {};
+
+void invalid_type_region_access() {
+  const A &x = B();
+  for (int i = 0; i < 10; ++i) { }
+  clang_analyzer_eval(&x != 0); // expected-warning{{TRUE}}
+}   // expected-warning@-1{{reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to true}}
Index: lib/StaticAnalyzer/Core/LoopWidening.cpp
===
--- lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -14,10 +14,17 @@
 ///
 //===--===//
 
+#include "clang/AST/AST.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
+#include "llvm/ADT/SmallSet.h"
 
 using namespace clang;
 using namespace ento;
+using namespace clang::ast_matchers;
+
+const auto MatchRef = "matchref";
 
 /// Return the loops condition Stmt or NULL if LoopStmt is not a loop
 static const Expr *getLoopCondition(const Stmt *LoopStmt) {
@@ -49,6 +56,7 @@
   // TODO Nested loops are currently widened as a result of the invalidation
   //  being so inp

[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread George Karpenkov via Phabricator via cfe-commits
george.karpenkov accepted this revision.
george.karpenkov added a comment.
This revision is now accepted and ready to land.

Looks good to me, apart from the nit on an unused header.




Comment at: lib/StaticAnalyzer/Core/LoopWidening.cpp:21
 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
+#include "llvm/ADT/SmallSet.h"
 

Seems unused now?


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris updated this revision to Diff 151046.
ormris added a comment.

Remove unneeded header


Repository:
  rC Clang

https://reviews.llvm.org/D47044

Files:
  lib/StaticAnalyzer/Core/LoopWidening.cpp
  test/Analysis/loop-widening-preserve-reference-type.cpp


Index: test/Analysis/loop-widening-preserve-reference-type.cpp
===
--- /dev/null
+++ test/Analysis/loop-widening-preserve-reference-type.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-max-loop 4 
-analyzer-config widen-loops=true -verify %s
+
+void clang_analyzer_eval(int);
+
+struct A {
+  ~A() {}
+};
+struct B : public A {};
+
+void invalid_type_region_access() {
+  const A &x = B();
+  for (int i = 0; i < 10; ++i) { }
+  clang_analyzer_eval(&x != 0); // expected-warning{{TRUE}}
+}   // expected-warning@-1{{reference cannot be 
bound to dereferenced null pointer in well-defined C++ code; comparison may be 
assumed to always evaluate to true}}
Index: lib/StaticAnalyzer/Core/LoopWidening.cpp
===
--- lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -14,10 +14,16 @@
 ///
 
//===--===//
 
+#include "clang/AST/AST.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 
 using namespace clang;
 using namespace ento;
+using namespace clang::ast_matchers;
+
+const auto MatchRef = "matchref";
 
 /// Return the loops condition Stmt or NULL if LoopStmt is not a loop
 static const Expr *getLoopCondition(const Stmt *LoopStmt) {
@@ -49,6 +55,7 @@
   // TODO Nested loops are currently widened as a result of the invalidation
   //  being so inprecise. When the invalidation is improved, the handling
   //  of nested loops will also need to be improved.
+  ASTContext &ASTCtx = LCtx->getAnalysisDeclContext()->getASTContext();
   const StackFrameContext *STC = LCtx->getCurrentStackFrame();
   MemRegionManager &MRMgr = PrevState->getStateManager().getRegionManager();
   const MemRegion *Regions[] = {MRMgr.getStackLocalsRegion(STC),
@@ -60,6 +67,18 @@
  RegionAndSymbolInvalidationTraits::TK_EntireMemSpace);
   }
 
+  // References should not be invalidated.
+  auto Matches = 
match(findAll(stmt(hasDescendant(varDecl(hasType(referenceType())).bind(MatchRef,
+   *LCtx->getDecl()->getBody(), ASTCtx);
+  for (BoundNodes Match : Matches) {
+const VarDecl *VD = Match.getNodeAs(MatchRef);
+assert(VD);
+const VarRegion *VarMem = MRMgr.getVarRegion(VD, LCtx);
+ITraits.setTrait(VarMem,
+ RegionAndSymbolInvalidationTraits::TK_PreserveContents);
+  }
+
+
   // 'this' pointer is not an lvalue, we should not invalidate it. If the loop
   // is located in a method, constructor or destructor, the value of 'this'
   // pointer shoule remain unchanged.


Index: test/Analysis/loop-widening-preserve-reference-type.cpp
===
--- /dev/null
+++ test/Analysis/loop-widening-preserve-reference-type.cpp
@@ -0,0 +1,14 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-max-loop 4 -analyzer-config widen-loops=true -verify %s
+
+void clang_analyzer_eval(int);
+
+struct A {
+  ~A() {}
+};
+struct B : public A {};
+
+void invalid_type_region_access() {
+  const A &x = B();
+  for (int i = 0; i < 10; ++i) { }
+  clang_analyzer_eval(&x != 0); // expected-warning{{TRUE}}
+}   // expected-warning@-1{{reference cannot be bound to dereferenced null pointer in well-defined C++ code; comparison may be assumed to always evaluate to true}}
Index: lib/StaticAnalyzer/Core/LoopWidening.cpp
===
--- lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -14,10 +14,16 @@
 ///
 //===--===//
 
+#include "clang/AST/AST.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 
 using namespace clang;
 using namespace ento;
+using namespace clang::ast_matchers;
+
+const auto MatchRef = "matchref";
 
 /// Return the loops condition Stmt or NULL if LoopStmt is not a loop
 static const Expr *getLoopCondition(const Stmt *LoopStmt) {
@@ -49,6 +55,7 @@
   // TODO Nested loops are currently widened as a result of the invalidation
   //  being so inprecise. When the invalidation is improved, the handling
   //  of nested loops will also need to be improved.
+

[PATCH] D48100: Append new attributes to the end of an AttributeList.

2018-06-12 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur created this revision.
Meinersbur added reviewers: hfinkel, TylerNowicki, ABataev, thakis, rjmccall, 
george.burgess.iv, nicholas, nlewycky.
Herald added subscribers: atanasyan, zzheng.

... instead of prepending it at the beginning (the original behavior since 
implemented in r122535 2010-12-23). This builds up an AttributeList in the the 
order in which the attributes appear in the source.

The reverse order caused nodes for attributes in the AST (e.g. `LoopHint`) to 
be in the reverse order, and therefore printed in the wrong order in 
`-ast-dump`. Some TODO comments mention this. The order was explicitly reversed 
for `enable_if` attribute overload resolution and name mangling, which is not 
necessary anymore with this patch.

The change unfortunately has some secondary effect, especially on diagnostic 
output. In the simplest cases, the CHECK lines or expected diagnostic were 
changed to the the new output. If the kind of error/warning changed, the 
attribute' order was changed instead.

This unfortunately causes some 'previous occurrence here' hints to be textually 
after the main marker. This typically happens when attributes are merged, but 
are incompatible to each other. Interchanging the role of the the main and note 
SourceLocation will also cause the case where two different declaration's 
attributes (in contrast to multiple attributes of the same declaration) are 
merged to be reverse. There is no easy fix because sometimes previous 
attributes are merged into a new declaration's attribute list, sometimes new 
attributes are added to a previous declaration's attribute list. Since 
'previous occurrence here' pointing to locations after the main marker is not 
rare, I left the markers as-is; it is only relevant when the attributes are 
declared in the same declaration anyway.


Repository:
  rC Clang

https://reviews.llvm.org/D48100

Files:
  include/clang/Sema/AttributeList.h
  lib/AST/ItaniumMangle.cpp
  lib/Sema/SemaOverload.cpp
  test/Index/annotate-comments-availability-attrs.cpp
  test/Index/complete-with-annotations.cpp
  test/Misc/ast-print-pragmas.cpp
  test/PCH/pragma-loop.cpp
  test/Parser/pragma-loop-safety.cpp
  test/Parser/pragma-loop.cpp
  test/Parser/pragma-unroll.cpp
  test/Sema/attr-availability-tvos.c
  test/Sema/attr-availability.c
  test/Sema/attr-coldhot.c
  test/Sema/attr-disable-tail-calls.c
  test/Sema/attr-long-call.c
  test/Sema/attr-micromips.c
  test/Sema/attr-notail.c
  test/Sema/attr-ownership.c
  test/Sema/attr-ownership.cpp
  test/Sema/attr-print.c
  test/Sema/attr-swiftcall.c
  test/Sema/attr-target-mv.c
  test/Sema/attr-visibility.c
  test/Sema/internal_linkage.c
  test/Sema/mips-interrupt-attr.c
  test/Sema/ms_abi-sysv_abi.c
  test/Sema/nullability.c
  test/Sema/stdcall-fastcall.c
  test/SemaCXX/attr-print.cpp
  test/SemaCXX/attr-swiftcall.cpp
  test/SemaCXX/decl-microsoft-call-conv.cpp
  test/SemaCXX/ms-uuid.cpp
  test/SemaOpenCL/address-spaces.cl
  test/SemaTemplate/attributes.cpp

Index: test/SemaTemplate/attributes.cpp
===
--- test/SemaTemplate/attributes.cpp
+++ test/SemaTemplate/attributes.cpp
@@ -55,11 +55,11 @@
 }
 
 // CHECK: FunctionTemplateDecl {{.*}} HasAnnotations
-// CHECK:   AnnotateAttr {{.*}} "ANNOTATE_BAR"
 // CHECK:   AnnotateAttr {{.*}} "ANNOTATE_FOO"
+// CHECK:   AnnotateAttr {{.*}} "ANNOTATE_BAR"
 // CHECK: FunctionDecl {{.*}} HasAnnotations
 // CHECK:   TemplateArgument type 'int'
-// CHECK:   AnnotateAttr {{.*}} "ANNOTATE_BAR"
 // CHECK:   AnnotateAttr {{.*}} "ANNOTATE_FOO"
+// CHECK:   AnnotateAttr {{.*}} "ANNOTATE_BAR"
 template [[clang::annotate("ANNOTATE_FOO"), clang::annotate("ANNOTATE_BAR")]] void HasAnnotations();
 void UseAnnotations() { HasAnnotations(); }
Index: test/SemaOpenCL/address-spaces.cl
===
--- test/SemaOpenCL/address-spaces.cl
+++ test/SemaOpenCL/address-spaces.cl
@@ -58,8 +58,8 @@
 
 void func_multiple_addr(void) {
   typedef __private int private_int_t;
-  __local __private int var1;   // expected-error {{multiple address spaces specified for type}}
-  __local __private int *var2;  // expected-error {{multiple address spaces specified for type}}
+  __private __local int var1;   // expected-error {{multiple address spaces specified for type}}
+  __private __local int *var2;  // expected-error {{multiple address spaces specified for type}}
   __local private_int_t var3;   // expected-error {{multiple address spaces specified for type}}
   __local private_int_t *var4;  // expected-error {{multiple address spaces specified for type}}
 }
Index: test/SemaCXX/ms-uuid.cpp
===
--- test/SemaCXX/ms-uuid.cpp
+++ test/SemaCXX/ms-uuid.cpp
@@ -62,14 +62,14 @@
 [uuid("22A0---C000-0049")] class C4 {};
 
 // Both cl and clang-cl error out on this:
-// expected-note@+1 {{previous uuid specified here}}
-class __dec

[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.

I'm still curious whether this also works:

  void foo() {
const A &x = B();
bar();
  }
  
  void bar() {
for (int i = 0; i < 10; ++i) {}
  }

Though we can land this patch and deal with this later.


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris marked an inline comment as done.
ormris added a comment.

Sounds good. I'll go ahead and commit this. Thanks for the review!


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


[PATCH] D47044: [analyzer] Ensure that we only visit a destructor for a reference if type information is available.

2018-06-12 Thread Matthew Voss via Phabricator via cfe-commits
ormris added a comment.

Hmm... I'll take a look.


Repository:
  rC Clang

https://reviews.llvm.org/D47044



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


  1   2   >