[libunwind] 8c03fdf - [libcxxabi, libunwind] support running tests in standalone mode

2020-10-14 Thread Dominik Montada via cfe-commits

Author: Dominik Montada
Date: 2020-10-14T09:10:20+02:00
New Revision: 8c03fdf34a659925a3f09c8f54016e47ea1c7519

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

LOG: [libcxxabi,libunwind] support running tests in standalone mode

Remove check for standalone and shared library mode in libcxxabi to
allow including tests in said mode. This check prevented running the
tests in standalone mode with static libraries, which is the case for
baremetal targets.

Fix check-unwind target trying to use a non-existent llvm-lit executable
in standalone mode. Copy the HandleOutOfTreeLLVM logic from libcxxabi to
libunwind in order to make the tests work in standalone mode.

Reviewed By: ldionne, #libc_abi, #libc

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

Added: 


Modified: 
libcxx/CMakeLists.txt
libcxx/cmake/Modules/HandleOutOfTreeLLVM.cmake
libcxxabi/CMakeLists.txt
libunwind/CMakeLists.txt
libunwind/test/CMakeLists.txt

Removed: 
libcxxabi/cmake/Modules/HandleOutOfTreeLLVM.cmake



diff  --git a/libcxx/CMakeLists.txt b/libcxx/CMakeLists.txt
index ee250374732d..f67f417de238 100644
--- a/libcxx/CMakeLists.txt
+++ b/libcxx/CMakeLists.txt
@@ -28,6 +28,10 @@ set(CMAKE_MODULE_PATH
   ${CMAKE_MODULE_PATH}
   )
 
+set(LIBCXX_SOURCE_DIR  ${CMAKE_CURRENT_SOURCE_DIR})
+set(LIBCXX_BINARY_DIR  ${CMAKE_CURRENT_BINARY_DIR})
+set(LIBCXX_BINARY_INCLUDE_DIR "${LIBCXX_BINARY_DIR}/include/c++build")
+
 if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR OR 
LIBCXX_STANDALONE_BUILD)
   project(libcxx CXX C)
 
@@ -36,6 +40,12 @@ if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR OR 
LIBCXX_STANDALONE_BUIL
   set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}")
   set(PACKAGE_BUGREPORT "llvm-b...@lists.llvm.org")
 
+  # In a standalone build, we don't have llvm to automatically generate the
+  # llvm-lit script for us.  So we need to provide an explicit directory that
+  # the configurator should write the script into.
+  set(LIBCXX_STANDALONE_BUILD 1)
+  set(LLVM_LIT_OUTPUT_DIR "${LIBCXX_BINARY_DIR}/bin")
+
   # Find the LLVM sources and simulate LLVM CMake options.
   include(HandleOutOfTreeLLVM)
 endif()
@@ -381,10 +391,6 @@ endif ()
 # Configure System
 
#===
 
-set(LIBCXX_SOURCE_DIR  ${CMAKE_CURRENT_SOURCE_DIR})
-set(LIBCXX_BINARY_DIR  ${CMAKE_CURRENT_BINARY_DIR})
-set(LIBCXX_BINARY_INCLUDE_DIR "${LIBCXX_BINARY_DIR}/include/c++build")
-
 if(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR AND NOT APPLE)
   set(LIBCXX_LIBRARY_DIR 
${LLVM_LIBRARY_OUTPUT_INTDIR}/${LLVM_DEFAULT_TARGET_TRIPLE}/c++)
   set(LIBCXX_HEADER_DIR ${LLVM_BINARY_DIR})

diff  --git a/libcxx/cmake/Modules/HandleOutOfTreeLLVM.cmake 
b/libcxx/cmake/Modules/HandleOutOfTreeLLVM.cmake
index 457ad4176042..a355fdf99863 100644
--- a/libcxx/cmake/Modules/HandleOutOfTreeLLVM.cmake
+++ b/libcxx/cmake/Modules/HandleOutOfTreeLLVM.cmake
@@ -25,7 +25,6 @@ else()
 endif()
 
 message(STATUS "Configuring for standalone build.")
-set(LIBCXX_STANDALONE_BUILD 1)
 
 # Add LLVM Functions 
 if (WIN32)
@@ -49,11 +48,6 @@ if (NOT DEFINED LLVM_ENABLE_SPHINX)
   set(LLVM_ENABLE_SPHINX OFF)
 endif()
 
-# In a standalone build, we don't have llvm to automatically generate the
-# llvm-lit script for us.  So we need to provide an explicit directory that
-# the configurator should write the script into.
-set(LLVM_LIT_OUTPUT_DIR "${libcxx_BINARY_DIR}/bin")
-
 if (LLVM_INCLUDE_TESTS)
   # Required LIT Configuration 
   # Define the default arguments to use with 'lit', and an option for the user

diff  --git a/libcxxabi/CMakeLists.txt b/libcxxabi/CMakeLists.txt
index c4d76ea22eca..5f0c72685e51 100644
--- a/libcxxabi/CMakeLists.txt
+++ b/libcxxabi/CMakeLists.txt
@@ -21,6 +21,11 @@ set(CMAKE_MODULE_PATH
   ${CMAKE_MODULE_PATH}
   )
 
+set(LIBCXXABI_SOURCE_DIR  ${CMAKE_CURRENT_SOURCE_DIR})
+set(LIBCXXABI_BINARY_DIR  ${CMAKE_CURRENT_BINARY_DIR})
+set(LIBCXXABI_LIBCXX_PATH "${CMAKE_CURRENT_LIST_DIR}/../libcxx" CACHE PATH
+"Specify path to libc++ source.")
+
 if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR OR 
LIBCXXABI_STANDALONE_BUILD)
   project(libcxxabi CXX C)
 
@@ -29,6 +34,16 @@ if (CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR OR 
LIBCXXABI_STANDALONE_B
   set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}")
   set(PACKAGE_BUGREPORT "llvm-b...@lists.llvm.org")
 
+  # Add the CMake module path of libcxx so we can reuse 
HandleOutOfTreeLLVM.cmake
+  set(LIBCXXABI_LIBCXX_CMAKE_PATH "${LIBCXXABI_LIBCXX_PATH}/cmake/Modules")
+  list(APPEND CMAKE_MODULE_PATH "${LIBCXXABI_LIBCXX_CMAKE_PATH}")
+
+  # In a standalone build, we don't have llvm to automaticall

[PATCH] D89184: Support complex target features combinations

2020-10-14 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added a comment.

> D89105   appears to use only `"avx512vl , 
> avx512vnni | avxvnni"`.
> Does it mean `(avx512vl , avx512vnni) | avxvnni` or `avx512vl , (avx512vnni | 
> avxvnni)` ?

We need to express combination to `(avx512vl , avx512vnni) | avxvnni`, the 
previous code will turn it into `avx512vl , (avx512vnni | avxvnni)`.
With this patch, `"avx512vl , avx512vnni | avxvnni"` will turn into `(avx512vl 
, avx512vnni) | avxvnni` by always prioritizing `","`.
I agreed with @echristo that we do need to add some comments for that.


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

https://reviews.llvm.org/D89184

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


[PATCH] D89220: [clang-rename] Simplify the code of handling class paritial specializations, NFC.

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG27c691cf62a9: [clang-rename] Simplify the code of handling 
class paritial specializations… (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89220

Files:
  clang/include/clang/AST/DeclTemplate.h
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp


Index: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -27,6 +27,7 @@
 #include "clang/Tooling/Refactoring.h"
 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
 
 #include 
 #include 
@@ -96,12 +97,6 @@
 return true;
   }
 
-  bool VisitClassTemplatePartialSpecializationDecl(
-  const ClassTemplatePartialSpecializationDecl *PartialSpec) {
-PartialSpecs.push_back(PartialSpec);
-return true;
-  }
-
 private:
   void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) {
 if (!RecordDecl->getDefinition()) {
@@ -118,11 +113,10 @@
   void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) {
 for (const auto *Specialization : TemplateDecl->specializations())
   addUSRsOfCtorDtors(Specialization);
-
-for (const auto *PartialSpec : PartialSpecs) {
-  if (PartialSpec->getSpecializedTemplate() == TemplateDecl)
-addUSRsOfCtorDtors(PartialSpec);
-}
+SmallVector PartialSpecs;
+TemplateDecl->getPartialSpecializations(PartialSpecs);
+llvm::for_each(PartialSpecs,
+   [&](const auto *Spec) { addUSRsOfCtorDtors(Spec); });
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
   }
 
@@ -184,7 +178,6 @@
   std::set USRSet;
   std::vector OverriddenMethods;
   std::vector InstantiatedMethods;
-  std::vector PartialSpecs;
 };
 } // namespace
 
Index: clang/lib/AST/DeclTemplate.cpp
===
--- clang/lib/AST/DeclTemplate.cpp
+++ clang/lib/AST/DeclTemplate.cpp
@@ -440,7 +440,7 @@
 }
 
 llvm::FoldingSetVector &
-ClassTemplateDecl::getPartialSpecializations() {
+ClassTemplateDecl::getPartialSpecializations() const {
   LoadLazySpecializations();
   return getCommonPtr()->PartialSpecializations;
 }
@@ -528,7 +528,7 @@
 }
 
 void ClassTemplateDecl::getPartialSpecializations(
-  SmallVectorImpl &PS) {
+SmallVectorImpl &PS) const {
   llvm::FoldingSetVector &PartialSpecs
 = getPartialSpecializations();
   PS.clear();
Index: clang/include/clang/AST/DeclTemplate.h
===
--- clang/include/clang/AST/DeclTemplate.h
+++ clang/include/clang/AST/DeclTemplate.h
@@ -2266,7 +2266,7 @@
   /// Retrieve the set of partial specializations of this class
   /// template.
   llvm::FoldingSetVector &
-  getPartialSpecializations();
+  getPartialSpecializations() const;
 
   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
 DeclarationName Name, TemplateParameterList *Params,
@@ -2363,7 +2363,7 @@
 
   /// Retrieve the partial specializations as an ordered list.
   void getPartialSpecializations(
-  SmallVectorImpl &PS);
+  SmallVectorImpl &PS) const;
 
   /// Find a class template partial specialization with the given
   /// type T.


Index: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -27,6 +27,7 @@
 #include "clang/Tooling/Refactoring.h"
 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
 
 #include 
 #include 
@@ -96,12 +97,6 @@
 return true;
   }
 
-  bool VisitClassTemplatePartialSpecializationDecl(
-  const ClassTemplatePartialSpecializationDecl *PartialSpec) {
-PartialSpecs.push_back(PartialSpec);
-return true;
-  }
-
 private:
   void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) {
 if (!RecordDecl->getDefinition()) {
@@ -118,11 +113,10 @@
   void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) {
 for (const auto *Specialization : TemplateDecl->specializations())
   addUSRsOfCtorDtors(Specialization);
-
-for (const auto *PartialSpec : PartialSpecs) {
-  if (PartialSpec->getSpecializedTemplate() == TemplateDecl)
-addUSRsOfCtorDtors(PartialSpec);
-}
+SmallVector PartialSpecs;
+TemplateDecl->getPartialSpecializations(PartialSpecs);
+llvm::for_each(PartialSpecs,
+   [&](const auto *Spec) { a

[clang] 27c691c - [clang-rename] Simplify the code of handling class paritial specializations, NFC.

2020-10-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-10-14T09:57:55+02:00
New Revision: 27c691cf62a9b34789516a24233fa0ee7bbd8111

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

LOG: [clang-rename] Simplify the code of handling class paritial 
specializations, NFC.

Instead of collecting all specializations and doing a post-filterin, we
can just get all targeted specializations from 
getPartialSpecializationsizations.

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

Added: 


Modified: 
clang/include/clang/AST/DeclTemplate.h
clang/lib/AST/DeclTemplate.cpp
clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp

Removed: 




diff  --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 9e2254376150..d10103752d81 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2266,7 +2266,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl 
{
   /// Retrieve the set of partial specializations of this class
   /// template.
   llvm::FoldingSetVector &
-  getPartialSpecializations();
+  getPartialSpecializations() const;
 
   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
 DeclarationName Name, TemplateParameterList *Params,
@@ -2363,7 +2363,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl 
{
 
   /// Retrieve the partial specializations as an ordered list.
   void getPartialSpecializations(
-  SmallVectorImpl &PS);
+  SmallVectorImpl &PS) const;
 
   /// Find a class template partial specialization with the given
   /// type T.

diff  --git a/clang/lib/AST/DeclTemplate.cpp b/clang/lib/AST/DeclTemplate.cpp
index 7857e75f57a1..5538651a453d 100644
--- a/clang/lib/AST/DeclTemplate.cpp
+++ b/clang/lib/AST/DeclTemplate.cpp
@@ -440,7 +440,7 @@ ClassTemplateDecl::getSpecializations() const {
 }
 
 llvm::FoldingSetVector &
-ClassTemplateDecl::getPartialSpecializations() {
+ClassTemplateDecl::getPartialSpecializations() const {
   LoadLazySpecializations();
   return getCommonPtr()->PartialSpecializations;
 }
@@ -528,7 +528,7 @@ void ClassTemplateDecl::AddPartialSpecialization(
 }
 
 void ClassTemplateDecl::getPartialSpecializations(
-  SmallVectorImpl &PS) {
+SmallVectorImpl &PS) const {
   llvm::FoldingSetVector &PartialSpecs
 = getPartialSpecializations();
   PS.clear();

diff  --git a/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp 
b/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
index 43dc32e158d3..82ef26e18369 100644
--- a/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -27,6 +27,7 @@
 #include "clang/Tooling/Refactoring.h"
 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
 
 #include 
 #include 
@@ -96,12 +97,6 @@ class AdditionalUSRFinder : public 
RecursiveASTVisitor {
 return true;
   }
 
-  bool VisitClassTemplatePartialSpecializationDecl(
-  const ClassTemplatePartialSpecializationDecl *PartialSpec) {
-PartialSpecs.push_back(PartialSpec);
-return true;
-  }
-
 private:
   void handleCXXRecordDecl(const CXXRecordDecl *RecordDecl) {
 if (!RecordDecl->getDefinition()) {
@@ -118,11 +113,10 @@ class AdditionalUSRFinder : public 
RecursiveASTVisitor {
   void handleClassTemplateDecl(const ClassTemplateDecl *TemplateDecl) {
 for (const auto *Specialization : TemplateDecl->specializations())
   addUSRsOfCtorDtors(Specialization);
-
-for (const auto *PartialSpec : PartialSpecs) {
-  if (PartialSpec->getSpecializedTemplate() == TemplateDecl)
-addUSRsOfCtorDtors(PartialSpec);
-}
+SmallVector PartialSpecs;
+TemplateDecl->getPartialSpecializations(PartialSpecs);
+llvm::for_each(PartialSpecs,
+   [&](const auto *Spec) { addUSRsOfCtorDtors(Spec); });
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
   }
 
@@ -184,7 +178,6 @@ class AdditionalUSRFinder : public 
RecursiveASTVisitor {
   std::set USRSet;
   std::vector OverriddenMethods;
   std::vector InstantiatedMethods;
-  std::vector PartialSpecs;
 };
 } // namespace
 



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


[PATCH] D89221: [clang-rename] Fix rename on function template specializations.

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 298061.
hokein added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89221

Files:
  clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
  clang/test/clang-rename/FunctionTemplate.cpp


Index: clang/test/clang-rename/FunctionTemplate.cpp
===
--- /dev/null
+++ clang/test/clang-rename/FunctionTemplate.cpp
@@ -0,0 +1,19 @@
+template 
+void Foo(T t); // CHECK: void Bar(T t);
+
+template <>
+void Foo(int a); // CHECK: void Bar(int a);
+
+void test() {
+  Foo(1); // CHECK: Bar(1);
+}
+
+// Test 1.
+// RUN: clang-rename -offset=28 -new-name=Bar %s -- | sed 's,//.*,,' | 
FileCheck %s
+// Test 2.
+// RUN: clang-rename -offset=81 -new-name=Bar %s -- | sed 's,//.*,,' | 
FileCheck %s
+// Test 3.
+// RUN: clang-rename -offset=137 -new-name=Bar %s -- | sed 's,//.*,,' | 
FileCheck %s
+
+// To find offsets after modifying the file, use:
+//   grep -Ubo 'Foo.*' 
Index: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -81,6 +81,12 @@
 } else if (const auto *TemplateDecl =
dyn_cast(FoundDecl)) {
   handleClassTemplateDecl(TemplateDecl);
+} else if (const auto *FD = dyn_cast(FoundDecl)) {
+  USRSet.insert(getUSRForDecl(FD));
+  if (const auto *FTD = FD->getPrimaryTemplate())
+handleFunctionTemplateDecl(FTD);
+} else if (const auto *FD = dyn_cast(FoundDecl)) {
+  handleFunctionTemplateDecl(FD);
 } else {
   USRSet.insert(getUSRForDecl(FoundDecl));
 }
@@ -120,6 +126,13 @@
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
   }
 
+  void handleFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
+USRSet.insert(getUSRForDecl(FTD));
+USRSet.insert(getUSRForDecl(FTD->getTemplatedDecl()));
+for (const auto *S : FTD->specializations())
+  USRSet.insert(getUSRForDecl(S));
+  }
+
   void addUSRsOfCtorDtors(const CXXRecordDecl *RD) {
 const auto* RecordDecl = RD->getDefinition();
 


Index: clang/test/clang-rename/FunctionTemplate.cpp
===
--- /dev/null
+++ clang/test/clang-rename/FunctionTemplate.cpp
@@ -0,0 +1,19 @@
+template 
+void Foo(T t); // CHECK: void Bar(T t);
+
+template <>
+void Foo(int a); // CHECK: void Bar(int a);
+
+void test() {
+  Foo(1); // CHECK: Bar(1);
+}
+
+// Test 1.
+// RUN: clang-rename -offset=28 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
+// Test 2.
+// RUN: clang-rename -offset=81 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
+// Test 3.
+// RUN: clang-rename -offset=137 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s
+
+// To find offsets after modifying the file, use:
+//   grep -Ubo 'Foo.*' 
Index: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -81,6 +81,12 @@
 } else if (const auto *TemplateDecl =
dyn_cast(FoundDecl)) {
   handleClassTemplateDecl(TemplateDecl);
+} else if (const auto *FD = dyn_cast(FoundDecl)) {
+  USRSet.insert(getUSRForDecl(FD));
+  if (const auto *FTD = FD->getPrimaryTemplate())
+handleFunctionTemplateDecl(FTD);
+} else if (const auto *FD = dyn_cast(FoundDecl)) {
+  handleFunctionTemplateDecl(FD);
 } else {
   USRSet.insert(getUSRForDecl(FoundDecl));
 }
@@ -120,6 +126,13 @@
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
   }
 
+  void handleFunctionTemplateDecl(const FunctionTemplateDecl *FTD) {
+USRSet.insert(getUSRForDecl(FTD));
+USRSet.insert(getUSRForDecl(FTD->getTemplatedDecl()));
+for (const auto *S : FTD->specializations())
+  USRSet.insert(getUSRForDecl(S));
+  }
+
   void addUSRsOfCtorDtors(const CXXRecordDecl *RD) {
 const auto* RecordDecl = RD->getDefinition();
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89221: [clang-rename] Fix rename on function template specializations.

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

@kbobyrev you may miss this patch, this is a separate patch from D89300 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89221

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


[PATCH] D89025: [RISCV] Add -mtune support

2020-10-14 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng updated this revision to Diff 298060.
kito-cheng added a comment.

ChangeLog

- Fix wording in comment
- Add more comment in testcase
- Fix format issue.


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

https://reviews.llvm.org/D89025

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Basic/Targets/RISCV.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/riscv-cpus.c
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/include/llvm/Support/RISCVTargetParser.def
  llvm/include/llvm/Support/TargetParser.h
  llvm/lib/Support/TargetParser.cpp
  llvm/lib/Target/RISCV/RISCVAsmPrinter.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.cpp
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/lib/Target/RISCV/RISCVTargetMachine.cpp

Index: llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
===
--- llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
+++ llvm/lib/Target/RISCV/RISCVTargetMachine.cpp
@@ -75,13 +75,16 @@
 const RISCVSubtarget *
 RISCVTargetMachine::getSubtargetImpl(const Function &F) const {
   Attribute CPUAttr = F.getFnAttribute("target-cpu");
+  Attribute TuneAttr = F.getFnAttribute("tune-cpu");
   Attribute FSAttr = F.getFnAttribute("target-features");
 
   std::string CPU =
   CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
+  std::string TuneCPU =
+  TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
   std::string FS =
   FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
-  std::string Key = CPU + FS;
+  std::string Key = CPU + TuneCPU + FS;
   auto &I = SubtargetMap[Key];
   if (!I) {
 // This needs to be done before we create a new subtarget since any
@@ -98,7 +101,7 @@
   }
   ABIName = ModuleTargetABI->getString();
 }
-I = std::make_unique(TargetTriple, CPU, FS, ABIName, *this);
+I = std::make_unique(TargetTriple, CPU, TuneCPU, FS, ABIName, *this);
   }
   return I.get();
 }
Index: llvm/lib/Target/RISCV/RISCVSubtarget.h
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.h
+++ llvm/lib/Target/RISCV/RISCVSubtarget.h
@@ -71,13 +71,15 @@
   /// Initializes using the passed in CPU and feature strings so that we can
   /// use initializer lists for subtarget initialization.
   RISCVSubtarget &initializeSubtargetDependencies(const Triple &TT,
-  StringRef CPU, StringRef FS,
+  StringRef CPU,
+  StringRef TuneCPU,
+  StringRef FS,
   StringRef ABIName);
 
 public:
   // Initializes the data members to match that of the specified triple.
-  RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
- StringRef ABIName, const TargetMachine &TM);
+  RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU,
+ StringRef FS, StringRef ABIName, const TargetMachine &TM);
 
   // Parses features string setting specified subtarget options. The
   // definition of this function is auto-generated by tblgen.
Index: llvm/lib/Target/RISCV/RISCVSubtarget.cpp
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.cpp
+++ llvm/lib/Target/RISCV/RISCVSubtarget.cpp
@@ -30,13 +30,16 @@
 void RISCVSubtarget::anchor() {}
 
 RISCVSubtarget &RISCVSubtarget::initializeSubtargetDependencies(
-const Triple &TT, StringRef CPU, StringRef FS, StringRef ABIName) {
+const Triple &TT, StringRef CPU, StringRef TuneCPU, StringRef FS, StringRef ABIName) {
   // Determine default and user-specified characteristics
   bool Is64Bit = TT.isArch64Bit();
   std::string CPUName = std::string(CPU);
+  std::string TuneCPUName = std::string(TuneCPU);
   if (CPUName.empty())
 CPUName = Is64Bit ? "generic-rv64" : "generic-rv32";
-  ParseSubtargetFeatures(CPUName, /*TuneCPU*/ CPUName, FS);
+  if (TuneCPUName.empty())
+TuneCPUName = CPUName;
+  ParseSubtargetFeatures(CPUName, TuneCPUName, FS);
   if (Is64Bit) {
 XLenVT = MVT::i64;
 XLen = 64;
@@ -47,11 +50,12 @@
   return *this;
 }
 
-RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU, StringRef FS,
+RISCVSubtarget::RISCVSubtarget(const Triple &TT, StringRef CPU,
+   StringRef TuneCPU, StringRef FS,
StringRef ABIName, const TargetMachine &TM)
-: RISCVGenSubtargetInfo(TT, CPU, /*TuneCPU*/ CPU, FS),
+: RISCVGenSubtargetInfo(TT, CPU, TuneCPU, FS),
   UserReservedRegister(RISCV::NUM_TARGET_REGS),
-  FrameLowering(initializeSubtargetDependencies(TT, CPU, FS, ABIName)),
+  FrameLowering(initializeSubtargetDependencies(TT, CPU, TuneCPU, FS, ABIName)),
   InstrInfo(*this), RegInfo(getHwMode()), TLInfo(TM, *

[PATCH] D89300: [clang-rename] Fix rename on variable templates.

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/include/clang/AST/DeclTemplate.h:3098
   llvm::FoldingSetVector &
-  getPartialSpecializations();
+  getPartialSpecializations() const;
 

kbobyrev wrote:
> I believe these are from https://reviews.llvm.org/D89221, so probably rebase 
> on top of it?
I think you mean the change in D89220? they are different, this is for 
`VarTemplateDecl`, while that one is for `ClassTemplateDecl`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89300

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


[PATCH] D89025: [RISCV] Add -mtune support

2020-10-14 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng marked 3 inline comments as done.
kito-cheng added a comment.

In D89025#2327749 , @luismarques wrote:

> In D89025#2324334 , @khchen wrote:
>
>> RISCV supports `-mcpu` with default empty arch to align gcc's `-mtune` 
>> behavior since clang didn't support `-mtune` before. But now clang has 
>> `-mtune`, is it a good idea to remove those options? (ex. 
>> `rocket-rv32/rv64`, `sifive-7-rv32/64`)
>
> If possible that would good, since -mcpu is deprecated (for e.g. x86_64) or 
> unsupported in GCC (for e.g. RISC-V). So doing that would further align Clang 
> with GCC. But I wonder if this might be too problematic, in terms of 
> compatibility.

Personally I would like to remove `rocket-rv32/rv64`, `sifive-7-rv32/64`, but I 
didn't remove `rocket-rv32/rv64`, `sifive-7-rv32/64` in version 2 patch,  since 
I concern about compatibility too, Clang/LLVM 11 already included that, I would 
prefer create another patch to remove that and discuss that issue.


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

https://reviews.llvm.org/D89025

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


[PATCH] D89300: [clang-rename] Fix rename on variable templates.

2020-10-14 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang/include/clang/AST/DeclTemplate.h:3098
   llvm::FoldingSetVector &
-  getPartialSpecializations();
+  getPartialSpecializations() const;
 

hokein wrote:
> kbobyrev wrote:
> > I believe these are from https://reviews.llvm.org/D89221, so probably 
> > rebase on top of it?
> I think you mean the change in D89220? they are different, this is for 
> `VarTemplateDecl`, while that one is for `ClassTemplateDecl`.
Ah, you're right, sorry!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89300

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


[PATCH] D89303: [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 298079.
eduucaldas marked 2 inline comments as done.
eduucaldas added a comment.

Answer to comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89303

Files:
  clang/lib/Tooling/Syntax/Tree.cpp


Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -94,48 +94,65 @@
 
 void syntax::Tree::replaceChildRangeLowLevel(Node *BeforeBegin, Node *End,
  Node *New) {
-  assert(!BeforeBegin || BeforeBegin->Parent == this);
+  assert((!BeforeBegin || BeforeBegin->Parent == this) &&
+ "`BeforeBegin` is not a child of `this`.");
+  assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
+  assert(canModify() && "Cannot modify `this`.");
 
 #ifndef NDEBUG
-  for (auto *N = New; N; N = N->getNextSibling()) {
+  for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
 // FIXME: sanity-check the role.
   }
+
+  auto Reachable = [](Node *From, Node *N) {
+if (!N)
+  return true;
+for (auto *It = From; It; It = It->NextSibling)
+  if (It == N)
+return true;
+return false;
+  };
+  assert(Reachable(FirstChild, BeforeBegin) &&
+ "`BeforeBegin` is not reachable.");
+  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
+ "`End` is not after `BeforeBegin`.");
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
+  if (!New && Begin == End)
+return;
+
+  // Mark modification.
+  for (auto *T = this; T && T->Original; T = T->Parent)
+T->Original = false;
 
   // Detach old nodes.
-  for (auto *N = !BeforeBegin ? FirstChild : BeforeBegin->getNextSibling();
-   N != End;) {
+  for (auto *N = Begin; N != End;) {
 auto *Next = N->NextSibling;
 
 N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
-  traverse(N, [&](Node *C) { C->Original = false; });
+  traverse(N, [](Node *C) { C->Original = false; });
 
 N = Next;
   }
 
+  if (!New) {
+Begin = End;
+return;
+  }
   // Attach new nodes.
-  if (BeforeBegin)
-BeforeBegin->NextSibling = New ? New : End;
-  else
-FirstChild = New ? New : End;
-
-  if (New) {
-auto *Last = New;
-for (auto *N = New; N != nullptr; N = N->getNextSibling()) {
-  Last = N;
-  N->Parent = this;
-}
-Last->NextSibling = End;
+  Begin = New;
+  auto *Last = New;
+  for (auto *N = New; N != nullptr; N = N->NextSibling) {
+Last = N;
+N->Parent = this;
   }
-
-  // Mark the node as modified.
-  for (auto *T = this; T && T->Original; T = T->Parent)
-T->Original = false;
+  Last->NextSibling = End;
 }
 
 namespace {


Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -94,48 +94,65 @@
 
 void syntax::Tree::replaceChildRangeLowLevel(Node *BeforeBegin, Node *End,
  Node *New) {
-  assert(!BeforeBegin || BeforeBegin->Parent == this);
+  assert((!BeforeBegin || BeforeBegin->Parent == this) &&
+ "`BeforeBegin` is not a child of `this`.");
+  assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
+  assert(canModify() && "Cannot modify `this`.");
 
 #ifndef NDEBUG
-  for (auto *N = New; N; N = N->getNextSibling()) {
+  for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
 // FIXME: sanity-check the role.
   }
+
+  auto Reachable = [](Node *From, Node *N) {
+if (!N)
+  return true;
+for (auto *It = From; It; It = It->NextSibling)
+  if (It == N)
+return true;
+return false;
+  };
+  assert(Reachable(FirstChild, BeforeBegin) &&
+ "`BeforeBegin` is not reachable.");
+  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
+ "`End` is not after `BeforeBegin`.");
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
+  if (!New && Begin == End)
+return;
+
+  // Mark modification.
+  for (auto *T = this; T && T->Original; T = T->Parent)
+T->Original = false;
 
   // Detach old nodes.
-  for (auto *N = !BeforeBegin ? FirstChild : BeforeBegin->getNextSibling();
-   N != End;) {
+  for (auto *N = Begin; N != End;) {
 auto *Next = N->NextSibling;
 
 N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
-  traverse(N, [&](Node *C) { C->Original = false; });
+  traverse(N, [](Node *C) { C

[PATCH] D89303: [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

2020-10-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Tooling/Syntax/Tree.cpp:122
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+

Could you move this definition up so that it can be used in the last assert 
above?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89303

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


[clang] 4178f8f - [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

2020-10-14 Thread Eduardo Caldas via cfe-commits

Author: Eduardo Caldas
Date: 2020-10-14T09:18:32Z
New Revision: 4178f8f2f08e14abb341fb32dd0f4cc9320df072

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

LOG: [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

* Add assertions for other preconditions.
* If nothing is modified, don't mark it.

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

Added: 


Modified: 
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Tree.cpp 
b/clang/lib/Tooling/Syntax/Tree.cpp
index b558e7ab9a1b..74cd3c1f68b1 100644
--- a/clang/lib/Tooling/Syntax/Tree.cpp
+++ b/clang/lib/Tooling/Syntax/Tree.cpp
@@ -94,48 +94,65 @@ void syntax::Tree::prependChildLowLevel(Node *Child) {
 
 void syntax::Tree::replaceChildRangeLowLevel(Node *BeforeBegin, Node *End,
  Node *New) {
-  assert(!BeforeBegin || BeforeBegin->Parent == this);
+  assert((!BeforeBegin || BeforeBegin->Parent == this) &&
+ "`BeforeBegin` is not a child of `this`.");
+  assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
+  assert(canModify() && "Cannot modify `this`.");
 
 #ifndef NDEBUG
-  for (auto *N = New; N; N = N->getNextSibling()) {
+  for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
 // FIXME: sanity-check the role.
   }
+
+  auto Reachable = [](Node *From, Node *N) {
+if (!N)
+  return true;
+for (auto *It = From; It; It = It->NextSibling)
+  if (It == N)
+return true;
+return false;
+  };
+  assert(Reachable(FirstChild, BeforeBegin) &&
+ "`BeforeBegin` is not reachable.");
+  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
+ "`End` is not after `BeforeBegin`.");
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
+  if (!New && Begin == End)
+return;
+
+  // Mark modification.
+  for (auto *T = this; T && T->Original; T = T->Parent)
+T->Original = false;
 
   // Detach old nodes.
-  for (auto *N = !BeforeBegin ? FirstChild : BeforeBegin->getNextSibling();
-   N != End;) {
+  for (auto *N = Begin; N != End;) {
 auto *Next = N->NextSibling;
 
 N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
-  traverse(N, [&](Node *C) { C->Original = false; });
+  traverse(N, [](Node *C) { C->Original = false; });
 
 N = Next;
   }
 
+  if (!New) {
+Begin = End;
+return;
+  }
   // Attach new nodes.
-  if (BeforeBegin)
-BeforeBegin->NextSibling = New ? New : End;
-  else
-FirstChild = New ? New : End;
-
-  if (New) {
-auto *Last = New;
-for (auto *N = New; N != nullptr; N = N->getNextSibling()) {
-  Last = N;
-  N->Parent = this;
-}
-Last->NextSibling = End;
+  Begin = New;
+  auto *Last = New;
+  for (auto *N = New; N != nullptr; N = N->NextSibling) {
+Last = N;
+N->Parent = this;
   }
-
-  // Mark the node as modified.
-  for (auto *T = this; T && T->Original; T = T->Parent)
-T->Original = false;
+  Last->NextSibling = End;
 }
 
 namespace {



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


[PATCH] D89303: [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4178f8f2f08e: [SyntaxTree] Improve safety of 
`replaceChildRangeLowLevel` (authored by eduucaldas).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89303

Files:
  clang/lib/Tooling/Syntax/Tree.cpp


Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -94,48 +94,65 @@
 
 void syntax::Tree::replaceChildRangeLowLevel(Node *BeforeBegin, Node *End,
  Node *New) {
-  assert(!BeforeBegin || BeforeBegin->Parent == this);
+  assert((!BeforeBegin || BeforeBegin->Parent == this) &&
+ "`BeforeBegin` is not a child of `this`.");
+  assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
+  assert(canModify() && "Cannot modify `this`.");
 
 #ifndef NDEBUG
-  for (auto *N = New; N; N = N->getNextSibling()) {
+  for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
 // FIXME: sanity-check the role.
   }
+
+  auto Reachable = [](Node *From, Node *N) {
+if (!N)
+  return true;
+for (auto *It = From; It; It = It->NextSibling)
+  if (It == N)
+return true;
+return false;
+  };
+  assert(Reachable(FirstChild, BeforeBegin) &&
+ "`BeforeBegin` is not reachable.");
+  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
+ "`End` is not after `BeforeBegin`.");
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
+  if (!New && Begin == End)
+return;
+
+  // Mark modification.
+  for (auto *T = this; T && T->Original; T = T->Parent)
+T->Original = false;
 
   // Detach old nodes.
-  for (auto *N = !BeforeBegin ? FirstChild : BeforeBegin->getNextSibling();
-   N != End;) {
+  for (auto *N = Begin; N != End;) {
 auto *Next = N->NextSibling;
 
 N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (N->Original)
-  traverse(N, [&](Node *C) { C->Original = false; });
+  traverse(N, [](Node *C) { C->Original = false; });
 
 N = Next;
   }
 
+  if (!New) {
+Begin = End;
+return;
+  }
   // Attach new nodes.
-  if (BeforeBegin)
-BeforeBegin->NextSibling = New ? New : End;
-  else
-FirstChild = New ? New : End;
-
-  if (New) {
-auto *Last = New;
-for (auto *N = New; N != nullptr; N = N->getNextSibling()) {
-  Last = N;
-  N->Parent = this;
-}
-Last->NextSibling = End;
+  Begin = New;
+  auto *Last = New;
+  for (auto *N = New; N != nullptr; N = N->NextSibling) {
+Last = N;
+N->Parent = this;
   }
-
-  // Mark the node as modified.
-  for (auto *T = this; T && T->Original; T = T->Parent)
-T->Original = false;
+  Last->NextSibling = End;
 }
 
 namespace {


Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -94,48 +94,65 @@
 
 void syntax::Tree::replaceChildRangeLowLevel(Node *BeforeBegin, Node *End,
  Node *New) {
-  assert(!BeforeBegin || BeforeBegin->Parent == this);
+  assert((!BeforeBegin || BeforeBegin->Parent == this) &&
+ "`BeforeBegin` is not a child of `this`.");
+  assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
+  assert(canModify() && "Cannot modify `this`.");
 
 #ifndef NDEBUG
-  for (auto *N = New; N; N = N->getNextSibling()) {
+  for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
 assert(N->getRole() != NodeRole::Detached && "Roles must be set");
 // FIXME: sanity-check the role.
   }
+
+  auto Reachable = [](Node *From, Node *N) {
+if (!N)
+  return true;
+for (auto *It = From; It; It = It->NextSibling)
+  if (It == N)
+return true;
+return false;
+  };
+  assert(Reachable(FirstChild, BeforeBegin) &&
+ "`BeforeBegin` is not reachable.");
+  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
+ "`End` is not after `BeforeBegin`.");
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
+  if (!New && Begin == End)
+return;
+
+  // Mark modification.
+  for (auto *T = this; T && T->Original; T = T->Parent)
+T->Original = false;
 
   // Detach old nodes.
-  for (auto *N = !BeforeBegin ? FirstChild : BeforeBegin->getNextSibling();
-   N != End;) {
+  for (auto *N = Begin; N != End;) {
 auto *Next = N->NextSibling;
 
 N->setRole(NodeRole::Detached);
 N->Parent = nullptr;
 N->NextSibling = nullptr;
 if (

[PATCH] D89314: [SyntaxTree] Bug fix in `MutationsImpl::addAfter`.

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG72732acade77: [SyntaxTree] Bug fix in 
`MutationsImpl::addAfter`. (authored by eduucaldas).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89314

Files:
  clang/lib/Tooling/Syntax/Mutations.cpp


Index: clang/lib/Tooling/Syntax/Mutations.cpp
===
--- clang/lib/Tooling/Syntax/Mutations.cpp
+++ clang/lib/Tooling/Syntax/Mutations.cpp
@@ -23,6 +23,19 @@
 
 using namespace clang;
 
+static syntax::Node *findPrevious(syntax::Node *N) {
+  assert(N);
+  assert(N->getParent());
+  if (N->getParent()->getFirstChild() == N)
+return nullptr;
+  for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
+   C = C->getNextSibling()) {
+if (C->getNextSibling() == N)
+  return C;
+  }
+  llvm_unreachable("could not find a child node");
+}
+
 // This class has access to the internals of tree nodes. Its sole purpose is to
 // define helpers that allow implementing the high-level mutation operations.
 class syntax::MutationsImpl {
@@ -30,14 +43,15 @@
   /// Add a new node with a specified role.
   static void addAfter(syntax::Node *Anchor, syntax::Node *New, NodeRole Role) 
{
 assert(Anchor != nullptr);
+assert(Anchor->Parent != nullptr);
 assert(New->Parent == nullptr);
 assert(New->NextSibling == nullptr);
-assert(!New->isDetached());
+assert(New->isDetached());
 assert(Role != NodeRole::Detached);
 
 New->setRole(Role);
 auto *P = Anchor->getParent();
-P->replaceChildRangeLowLevel(Anchor, Anchor, New);
+P->replaceChildRangeLowLevel(Anchor, Anchor->getNextSibling(), New);
 
 P->assertInvariants();
   }
@@ -60,6 +74,10 @@
 
   /// Completely remove the node from its parent.
   static void remove(syntax::Node *N) {
+assert(N != nullptr);
+assert(N->Parent != nullptr);
+assert(N->canModify());
+
 auto *P = N->getParent();
 P->replaceChildRangeLowLevel(findPrevious(N), N->getNextSibling(),
  /*New=*/nullptr);
@@ -67,18 +85,6 @@
 P->assertInvariants();
 N->assertInvariants();
   }
-
-private:
-  static syntax::Node *findPrevious(syntax::Node *N) {
-if (N->getParent()->getFirstChild() == N)
-  return nullptr;
-for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
- C = C->getNextSibling()) {
-  if (C->getNextSibling() == N)
-return C;
-}
-llvm_unreachable("could not find a child node");
-  }
 };
 
 void syntax::removeStatement(syntax::Arena &A, syntax::Statement *S) {


Index: clang/lib/Tooling/Syntax/Mutations.cpp
===
--- clang/lib/Tooling/Syntax/Mutations.cpp
+++ clang/lib/Tooling/Syntax/Mutations.cpp
@@ -23,6 +23,19 @@
 
 using namespace clang;
 
+static syntax::Node *findPrevious(syntax::Node *N) {
+  assert(N);
+  assert(N->getParent());
+  if (N->getParent()->getFirstChild() == N)
+return nullptr;
+  for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
+   C = C->getNextSibling()) {
+if (C->getNextSibling() == N)
+  return C;
+  }
+  llvm_unreachable("could not find a child node");
+}
+
 // This class has access to the internals of tree nodes. Its sole purpose is to
 // define helpers that allow implementing the high-level mutation operations.
 class syntax::MutationsImpl {
@@ -30,14 +43,15 @@
   /// Add a new node with a specified role.
   static void addAfter(syntax::Node *Anchor, syntax::Node *New, NodeRole Role) {
 assert(Anchor != nullptr);
+assert(Anchor->Parent != nullptr);
 assert(New->Parent == nullptr);
 assert(New->NextSibling == nullptr);
-assert(!New->isDetached());
+assert(New->isDetached());
 assert(Role != NodeRole::Detached);
 
 New->setRole(Role);
 auto *P = Anchor->getParent();
-P->replaceChildRangeLowLevel(Anchor, Anchor, New);
+P->replaceChildRangeLowLevel(Anchor, Anchor->getNextSibling(), New);
 
 P->assertInvariants();
   }
@@ -60,6 +74,10 @@
 
   /// Completely remove the node from its parent.
   static void remove(syntax::Node *N) {
+assert(N != nullptr);
+assert(N->Parent != nullptr);
+assert(N->canModify());
+
 auto *P = N->getParent();
 P->replaceChildRangeLowLevel(findPrevious(N), N->getNextSibling(),
  /*New=*/nullptr);
@@ -67,18 +85,6 @@
 P->assertInvariants();
 N->assertInvariants();
   }
-
-private:
-  static syntax::Node *findPrevious(syntax::Node *N) {
-if (N->getParent()->getFirstChild() == N)
-  return nullptr;
-for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
- C = C->getNextSibling()) {
-  if (C->getNextSibling() == N)
-return C;
-}
-llvm_unrea

[clang] 72732ac - [SyntaxTree] Bug fix in `MutationsImpl::addAfter`.

2020-10-14 Thread Eduardo Caldas via cfe-commits

Author: Eduardo Caldas
Date: 2020-10-14T09:22:01Z
New Revision: 72732acade77d5ee55a818e2da77a2c5b7033ccb

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

LOG: [SyntaxTree] Bug fix in `MutationsImpl::addAfter`.

* Add assertions to other `MutationsImpl` member functions
* `findPrevious` is a free function

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

Added: 


Modified: 
clang/lib/Tooling/Syntax/Mutations.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Mutations.cpp 
b/clang/lib/Tooling/Syntax/Mutations.cpp
index bf1bcda26455..8def1c729689 100644
--- a/clang/lib/Tooling/Syntax/Mutations.cpp
+++ b/clang/lib/Tooling/Syntax/Mutations.cpp
@@ -23,6 +23,19 @@
 
 using namespace clang;
 
+static syntax::Node *findPrevious(syntax::Node *N) {
+  assert(N);
+  assert(N->getParent());
+  if (N->getParent()->getFirstChild() == N)
+return nullptr;
+  for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
+   C = C->getNextSibling()) {
+if (C->getNextSibling() == N)
+  return C;
+  }
+  llvm_unreachable("could not find a child node");
+}
+
 // This class has access to the internals of tree nodes. Its sole purpose is to
 // define helpers that allow implementing the high-level mutation operations.
 class syntax::MutationsImpl {
@@ -30,14 +43,15 @@ class syntax::MutationsImpl {
   /// Add a new node with a specified role.
   static void addAfter(syntax::Node *Anchor, syntax::Node *New, NodeRole Role) 
{
 assert(Anchor != nullptr);
+assert(Anchor->Parent != nullptr);
 assert(New->Parent == nullptr);
 assert(New->NextSibling == nullptr);
-assert(!New->isDetached());
+assert(New->isDetached());
 assert(Role != NodeRole::Detached);
 
 New->setRole(Role);
 auto *P = Anchor->getParent();
-P->replaceChildRangeLowLevel(Anchor, Anchor, New);
+P->replaceChildRangeLowLevel(Anchor, Anchor->getNextSibling(), New);
 
 P->assertInvariants();
   }
@@ -60,6 +74,10 @@ class syntax::MutationsImpl {
 
   /// Completely remove the node from its parent.
   static void remove(syntax::Node *N) {
+assert(N != nullptr);
+assert(N->Parent != nullptr);
+assert(N->canModify());
+
 auto *P = N->getParent();
 P->replaceChildRangeLowLevel(findPrevious(N), N->getNextSibling(),
  /*New=*/nullptr);
@@ -67,18 +85,6 @@ class syntax::MutationsImpl {
 P->assertInvariants();
 N->assertInvariants();
   }
-
-private:
-  static syntax::Node *findPrevious(syntax::Node *N) {
-if (N->getParent()->getFirstChild() == N)
-  return nullptr;
-for (syntax::Node *C = N->getParent()->getFirstChild(); C != nullptr;
- C = C->getNextSibling()) {
-  if (C->getNextSibling() == N)
-return C;
-}
-llvm_unreachable("could not find a child node");
-  }
 };
 
 void syntax::removeStatement(syntax::Arena &A, syntax::Statement *S) {



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


[clang] 6fbad9b - [SyntaxTree][NFC] Nit on `replaceChildRangeLowLevel`

2020-10-14 Thread Eduardo Caldas via cfe-commits

Author: Eduardo Caldas
Date: 2020-10-14T09:40:37Z
New Revision: 6fbad9bf304c05d37454420f7d5a1c2ab3adab20

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

LOG: [SyntaxTree][NFC] Nit on `replaceChildRangeLowLevel`

Added: 


Modified: 
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Tree.cpp 
b/clang/lib/Tooling/Syntax/Tree.cpp
index 74cd3c1f68b1..87526ad7a976 100644
--- a/clang/lib/Tooling/Syntax/Tree.cpp
+++ b/clang/lib/Tooling/Syntax/Tree.cpp
@@ -99,6 +99,8 @@ void syntax::Tree::replaceChildRangeLowLevel(Node 
*BeforeBegin, Node *End,
   assert((!End || End->Parent == this) && "`End` is not a child of `this`.");
   assert(canModify() && "Cannot modify `this`.");
 
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+
 #ifndef NDEBUG
   for (auto *N = New; N; N = N->NextSibling) {
 assert(N->Parent == nullptr);
@@ -116,10 +118,8 @@ void syntax::Tree::replaceChildRangeLowLevel(Node 
*BeforeBegin, Node *End,
   };
   assert(Reachable(FirstChild, BeforeBegin) &&
  "`BeforeBegin` is not reachable.");
-  assert(Reachable(BeforeBegin ? BeforeBegin->NextSibling : FirstChild, End) &&
- "`End` is not after `BeforeBegin`.");
+  assert(Reachable(Begin, End) && "`End` is not after `BeforeBegin`.");
 #endif
-  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
 
   if (!New && Begin == End)
 return;



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


[PATCH] D89303: [SyntaxTree] Improve safety of `replaceChildRangeLowLevel`

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas marked an inline comment as done.
eduucaldas added inline comments.



Comment at: clang/lib/Tooling/Syntax/Tree.cpp:122
 #endif
+  Node *&Begin = BeforeBegin ? BeforeBegin->NextSibling : FirstChild;
+

gribozavr2 wrote:
> Could you move this definition up so that it can be used in the last assert 
> above?
Done in a separate commit: 6fbad9bf304c05d37454420f7d5a1c2ab3adab20


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89303

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


[PATCH] D89148: [SyntaxTree] Artificial use of the Mutations API.

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 298092.
eduucaldas added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89148

Files:
  clang/include/clang/Tooling/Syntax/Mutations.h
  clang/lib/Tooling/Syntax/Mutations.cpp
  clang/unittests/Tooling/Syntax/MutationsTest.cpp


Index: clang/unittests/Tooling/Syntax/MutationsTest.cpp
===
--- clang/unittests/Tooling/Syntax/MutationsTest.cpp
+++ clang/unittests/Tooling/Syntax/MutationsTest.cpp
@@ -52,6 +52,16 @@
 EXPECT_FALSE(S->isOriginal())
 << "node removed from tree cannot be marked as original";
   };
+
+  Transformation ParenthesizeRHS = [this](const llvm::Annotations &Input,
+  TranslationUnit *Root) {
+auto *BOE = cast(
+nodeByRange(Input.range(), Root));
+ASSERT_TRUE(BOE->canModify()) << "cannot remove a statement";
+syntax::parenthesizeRHS(*Arena, BOE);
+EXPECT_FALSE(BOE->isOriginal())
+<< "modified node cannot be marked as original";
+  };
 };
 
 INSTANTIATE_TEST_CASE_P(SyntaxTreeTests, MutationTest,
@@ -71,4 +81,22 @@
   CheckTransformation(RemoveStatement, "void test() { if (1) [[{}]] else {} }",
   "void test() { if (1) ; else {} }");
 }
+
+TEST_P(MutationTest, Parenthesize_RHS) {
+  CheckTransformation(ParenthesizeRHS, R"cpp(void test() { [[1 + 2]]; })cpp",
+  "void test() { 1 + (2); }");
+}
+
+TEST_P(MutationTest, Parenthesize_RHS_MACRO) {
+  CheckTransformation(ParenthesizeRHS, R"cpp(
+#define THENUMBER 42
+void test() {
+  [[1 + (THENUMBER)]];
+})cpp",
+  R"cpp(
+#define THENUMBER 42
+void test() {
+  1 + ((THENUMBER));
+})cpp");
+}
 } // namespace
Index: clang/lib/Tooling/Syntax/Mutations.cpp
===
--- clang/lib/Tooling/Syntax/Mutations.cpp
+++ clang/lib/Tooling/Syntax/Mutations.cpp
@@ -8,6 +8,7 @@
 #include "clang/Tooling/Syntax/Mutations.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/Token.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "clang/Tooling/Syntax/BuildTree.h"
@@ -102,3 +103,22 @@
 
   MutationsImpl::replace(S, createEmptyStatement(A));
 }
+
+void syntax::parenthesizeRHS(syntax::Arena &A,
+ syntax::BinaryOperatorExpression *BOE) {
+  assert(BOE);
+  assert(BOE->canModify());
+
+  auto *RHS = BOE->getRhs();
+  auto *BeforeRHS = findPrevious(RHS);
+  MutationsImpl::remove(RHS);
+
+  auto *NewRHS =
+  createTree(A,
+ {{createLeaf(A, tok::l_paren), NodeRole::OpenParen},
+  {RHS, NodeRole::SubExpression},
+  {createLeaf(A, tok::r_paren), NodeRole::CloseParen}},
+ NodeKind::ParenExpression);
+
+  MutationsImpl::addAfter(BeforeRHS, NewRHS, NodeRole::RightHandSide);
+}
Index: clang/include/clang/Tooling/Syntax/Mutations.h
===
--- clang/include/clang/Tooling/Syntax/Mutations.h
+++ clang/include/clang/Tooling/Syntax/Mutations.h
@@ -31,6 +31,7 @@
 /// EXPECTS: S->canModify() == true
 void removeStatement(syntax::Arena &A, syntax::Statement *S);
 
+void parenthesizeRHS(syntax::Arena &A, syntax::BinaryOperatorExpression *BOE);
 } // namespace syntax
 } // namespace clang
 


Index: clang/unittests/Tooling/Syntax/MutationsTest.cpp
===
--- clang/unittests/Tooling/Syntax/MutationsTest.cpp
+++ clang/unittests/Tooling/Syntax/MutationsTest.cpp
@@ -52,6 +52,16 @@
 EXPECT_FALSE(S->isOriginal())
 << "node removed from tree cannot be marked as original";
   };
+
+  Transformation ParenthesizeRHS = [this](const llvm::Annotations &Input,
+  TranslationUnit *Root) {
+auto *BOE = cast(
+nodeByRange(Input.range(), Root));
+ASSERT_TRUE(BOE->canModify()) << "cannot remove a statement";
+syntax::parenthesizeRHS(*Arena, BOE);
+EXPECT_FALSE(BOE->isOriginal())
+<< "modified node cannot be marked as original";
+  };
 };
 
 INSTANTIATE_TEST_CASE_P(SyntaxTreeTests, MutationTest,
@@ -71,4 +81,22 @@
   CheckTransformation(RemoveStatement, "void test() { if (1) [[{}]] else {} }",
   "void test() { if (1) ; else {} }");
 }
+
+TEST_P(MutationTest, Parenthesize_RHS) {
+  CheckTransformation(ParenthesizeRHS, R"cpp(void test() { [[1 + 2]]; })cpp",
+  "void test() { 1 + (2); }");
+}
+
+TEST_P(MutationTest, Parenthesize_RHS_MACRO) {
+  CheckTransformation(ParenthesizeRHS, R"cpp(
+#define THENUMBER 42
+void test() {
+  [[1 + (THENUMBER)]];
+})cpp",
+  R"cpp(
+#define THENUMBER 42
+void test() {
+  1 + ((THENUMBER));
+})cpp");
+}
 } // namespace
Index: clang/lib

[PATCH] D82756: Port some floating point options to new option marshalling infrastructure

2020-10-14 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/test/CodeGen/fp-function-attrs.cpp:2
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ffast-math -ffinite-math-only 
-menable-unsafe-fp-math \
+// RUN:   -menable-no-infs -menable-no-nans -fno-signed-zeros 
-freciprocal-math \
+// RUN:   -fapprox-func -mreassociate -ffp-contract=fast -emit-llvm -o - %s | 
FileCheck %s

dang wrote:
> Anastasia wrote:
> > dang wrote:
> > > Anastasia wrote:
> > > > dang wrote:
> > > > > Anastasia wrote:
> > > > > > Not clear why do you need to pass these extra flags now?
> > > > > Previously passing -ffast-math to CC1 implied all these other flags. 
> > > > > I am trying to make CC1 option parsing as simple as possible, so that 
> > > > > we can then make it easy to generate a command line from a 
> > > > > CompilerInvocation instance. You can refer to [[ 
> > > > > http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html | 
> > > > > http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html ]] for 
> > > > > more details on why we want to be able to do this
> > > > Just to understand, there used to be implied flags and it made the 
> > > > manual command line use of clang more compact and easy... Is the idea 
> > > > now to change those compound flags such that individul flags always 
> > > > need to be passed?
> > > > 
> > > > Although I thought you are still adding the implicit flags:
> > > > 
> > > >   {options::OPT_cl_fast_relaxed_math,
> > > >[&](const Arg *Arg) {
> > > >  RenderArg(Arg);
> > > > 
> > > >  
> > > > CmdArgs.push_back(GetArgString(options::OPT_cl_mad_enable));
> > > >  CmdArgs.push_back(GetArgString(options::OPT_ffast_math));
> > > >  
> > > > CmdArgs.push_back(GetArgString(options::OPT_ffinite_math_only));
> > > >  CmdArgs.push_back(
> > > >  GetArgString(options::OPT_menable_unsafe_fp_math));
> > > >  CmdArgs.push_back(GetArgString(options::OPT_mreassociate));
> > > >  
> > > > CmdArgs.push_back(GetArgString(options::OPT_menable_no_nans));
> > > >  CmdArgs.push_back(
> > > >  GetArgString(options::OPT_menable_no_infinities));
> > > >  
> > > > CmdArgs.push_back(GetArgString(options::OPT_fno_signed_zeros));
> > > >  
> > > > CmdArgs.push_back(GetArgString(options::OPT_freciprocal_math));
> > > >  CmdArgs.push_back(GetArgString(options::OPT_fapprox_func));
> > > >}}
> > > > 
> > > > Do I just misunderstand something?
> > > The command line of the driver doesn't change. This patch only affects 
> > > what CC1 understands, now CC1 doesn't know anymore that 
> > > `-cl-fast-relaxed-math` implies all these other options so the driver is 
> > > responsible for specifying them when it constructs the CC1 command line.
> > > 
> > > To summarize, the clang driver command line isn't affected by this patch 
> > > and it shouldn't be so let me know if something is wrong there. However, 
> > > manually constructed `clang -cc1` invocations need to specify the all the 
> > > implied flags manually now.
> > Yes I understand, however, I am wondering whether this is intuitive because 
> > it seems the behavior of clang with `-cc1` and without will be different if 
> > the same `-cl-fast-relaxed-math` flag is passed.
> > 
> > I also find adding all the flags manually is too verbode if 
> > `-cl-fast-relaxed-math` assumes to enable all the extra setting.
> My understanding is that `-cc1` is an internal interface, so end-users should 
> never use `-cc1` directly and/or rely on itss interface. It is already the 
> case that flags mean very different things to the driver and `-cc1` for 
> example "--target=" and "-triple". Furthermore, this impacted very few tests 
> which leads me to believe that few compiler developers actually rely on this 
> behavior.
> 
> Do you think this would be a major inconvenience to compiler developers to 
> have to manually expand it out?
Hi @Anastasia, I'll be taking over this patch. I agree with Daniel that `-cc1` 
is an internal interface that doesn't need to match the public driver interface.
The current approach is by far the simplest to get command-line option 
marshaling working.

What are your thoughts?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82756

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


[PATCH] D89380: [clang-tidy] Fix for cppcoreguidelines-prefer-member-initializer to handle classes declared in macros

2020-10-14 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware created this revision.
baloghadamsoftware added reviewers: aaron.ballman, gribozavr2.
baloghadamsoftware added a project: clang-tools-extra.
Herald added subscribers: martong, gamesh411, Szelethus, dkrupp, rnkovacs, 
kbarton, xazax.hun, whisperity, nemanjai.
Herald added a project: clang.
baloghadamsoftware requested review of this revision.

`cppcoreguidelines-prefer-member-initializer` crashes on classes declared 
inside macros (see bug 47778 ). 
This patch fixes this issue.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89380

Files:
  
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
@@ -488,3 +488,18 @@
 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: 'x' should be initialized in a member initializer of the constructor [cppcoreguidelines-prefer-member-initializer]
 // CHECK-FIXES: {{^\ *$}}
 }
+
+#define MACRO1 struct InMacro1 { int i; InMacro1() { i = 0; } };
+// CHECK-MESSAGES: :[[@LINE-1]]:54: warning: 'i' should be initialized in a member initializer of the constructor [cppcoreguidelines-prefer-member-initializer]
+// CHECK-FIXES: #define MACRO1 struct InMacro1 { int i; InMacro1() : i(0) { } };
+MACRO1
+
+#define MACRO2 struct InMacro2 { int i, j; InMacro2() : i(0) { j = 1; } };
+// CHECK-MESSAGES: :[[@LINE-1]]:64: warning: 'j' should be initialized in a member initializer of the constructor [cppcoreguidelines-prefer-member-initializer]
+// CHECK-FIXES: #define MACRO2 struct InMacro2 { int i, j; InMacro2() : i(0), j(1) { } };
+MACRO2
+
+#define MACRO3 struct InMacro3 { int i, j; InMacro3() : j(1) { i = 0; } };
+// CHECK-MESSAGES: :[[@LINE-1]]:64: warning: 'i' should be initialized in a member initializer of the constructor [cppcoreguidelines-prefer-member-initializer]
+// CHECK-FIXES: #define MACRO3 struct InMacro3 { int i, j; InMacro3() : i(0), j(1) { } };
+MACRO3
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -144,99 +144,132 @@
 const FieldDecl *Field;
 const Expr *InitValue;
 std::tie(Field, InitValue) = isAssignmentToMemberOf(Class, S);
-if (Field) {
-  if (IsUseDefaultMemberInitEnabled && getLangOpts().CPlusPlus11 &&
-  Ctor->isDefaultConstructor() &&
-  (getLangOpts().CPlusPlus20 || !Field->isBitField()) &&
-  (!isa(Class->getDeclContext()) ||
-   !cast(Class->getDeclContext())->isUnion()) &&
-  shouldBeDefaultMemberInitializer(InitValue)) {
-auto Diag =
-diag(S->getBeginLoc(), "%0 should be initialized in an in-class"
-   " default member initializer")
-<< Field;
-
-SourceLocation FieldEnd =
-Lexer::getLocForEndOfToken(Field->getSourceRange().getEnd(), 0,
-   *Result.SourceManager, getLangOpts());
-Diag << FixItHint::CreateInsertion(FieldEnd,
-   UseAssignment ? " = " : "{")
- << FixItHint::CreateInsertionFromRange(
-FieldEnd,
-CharSourceRange(InitValue->getSourceRange(), true))
- << FixItHint::CreateInsertion(FieldEnd, UseAssignment ? "" : "}");
-
-SourceLocation SemiColonEnd =
-Lexer::findNextToken(S->getEndLoc(), *Result.SourceManager,
- getLangOpts())
-->getEndLoc();
-CharSourceRange StmtRange =
-CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
-
-Diag << FixItHint::CreateRemoval(StmtRange);
+if (!Field)
+  continue;
+assert(InitValue && "An assigment to a field must also have an assigned"
+" value");
+
+SourceLocation BeginLoc = S->getBeginLoc();
+SourceLocation EndLoc = S->getEndLoc();
+SourceRange InitValueRange = InitValue->getSourceRange();
+if (BeginLoc.isMacroID()) {
+  BeginLoc = Result.SourceManager->getSpellingLoc(BeginLoc);
+  EndLoc = Result.SourceManager->getSpellingLoc(EndLoc);
+  InitValueRange = SourceRange(
+  Result.SourceManager->getSpellingLoc(InitValueRange.getBegin()),
+  Result.SourceManager->getSpellingLoc(InitValueRange.getEnd()));
+}
+
+if (IsUseD

[PATCH] D89366: [WebAssembly] v128.load{8, 16, 32, 64}_lane instructions

2020-10-14 Thread Heejin Ahn via Phabricator via cfe-commits
aheejin accepted this revision.
aheejin added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Basic/BuiltinsWebAssembly.def:180
+TARGET_BUILTIN(__builtin_wasm_load32_lane, "V4iIii*", "nU", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load64_lane, "V2LLiIiLLi*", "nU", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store8_lane, "vV16ScIiSc*", "n", "simd128")

`U` in the third argument [[ 
https://github.com/llvm/llvm-project/blob/72732acade77d5ee55a818e2da77a2c5b7033ccb/clang/include/clang/Basic/Builtins.def#L75
 | means ]] pure. Can we say loads are pure? (The same for existing 
`__builtin_wasm_load32_zero` and `__builtin_wasm_load64_zero`)



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:16782
+return Builder.CreateCall(Callee, {Vec, LaneIdx, Ptr});
+  }
   case WebAssembly::BI__builtin_wasm_shuffle_v8x16: {

Would it be better to follow the arguments order in the original proposal?  The 
order in [[ https://github.com/WebAssembly/simd/pull/350 | here ]] is mem, v, 
and lane. (I don't know why loads need `v` though) The same for intrinsic and 
instruction.



Comment at: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td:246
+
+// TODO: Also support the oher load patterns for load_lane once the insructions
+// are merged to the proposal.





Comment at: llvm/lib/Target/WebAssembly/WebAssemblyInstrSIMD.td:315
+defm : StoreLanePatNoOffset;
+
 
//===--===//





Comment at: llvm/test/CodeGen/WebAssembly/simd-load-lane-offset.ll:4
+
+; Test SIMD v128.load{8,16,32,64}_lane instructions. TODO: Use the offset 
field.
+

Maybe add a comment on which patterns are currently supported and unsupported 
among this file?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89366

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


[PATCH] D89233: [clangd] Refine recoveryAST flags in clangd

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/Compiler.cpp:84
 
-  // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus) {
-CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
-CI->getLangOpts()->RecoveryASTType = Inputs.Opts.PreserveRecoveryASTType;
-  }
+  if (Inputs.Opts.BuildRecoveryAST)
+CI->getLangOpts()->RecoveryAST = true;

sammccall wrote:
> I don't have any problem with the changes to the flags, but we can also do 
> experiments just with config now:
> 
> ```
> CompileFlags:
>   Add: [-Xclang, -frecovery-ast]
> ```
> 
> in ~/.config/clangd/config.yaml
this sounds a new idea, but it looks like our internal client doesn't fully 
support config (yet?). 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89233

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


[PATCH] D89233: [clangd] Refine recoveryAST flags in clangd

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 298116.
hokein added a comment.

address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89233

Files:
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -59,8 +59,6 @@
 FS.OverlayRealFileSystemForModules = true;
   Inputs.TFS = &FS;
   Inputs.Opts = ParseOptions();
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
   Inputs.Opts.ClangTidyOpts.WarningsAsErrors = ClangTidyWarningsAsErrors;
   Inputs.Index = ExternalIndex;
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -148,6 +148,17 @@
   EXPECT_DECLS("LabelStmt", "label:");
 }
 
+TEST_F(TargetDeclTest, RecoveryForC) {
+  Flags = {"-xc", "-Xclang", "-frecovery-ast"};
+  Code = R"cpp(
+// error-ok: testing behavior on broken code
+// int f();
+int f(int);
+int x = [[f]]();
+  )cpp";
+  EXPECT_DECLS("DeclRefExpr", "int f(int)");
+}
+
 TEST_F(TargetDeclTest, Recovery) {
   Code = R"cpp(
 // error-ok: testing behavior on broken code
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -111,8 +111,6 @@
 
   MockFS FS;
   auto Inputs = TU.inputs(FS);
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {
@@ -1100,8 +1098,6 @@
   MockFS FS;
   auto Inputs = TU.inputs(FS);
   Inputs.Index = Index.get();
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -310,7 +310,7 @@
 opt RecoveryAST{
 "recovery-ast",
 cat(Features),
-desc("Preserve expressions in AST for broken code (C++ only)."),
+desc("Preserve expressions in AST for broken code."),
 init(ClangdServer::Options().BuildRecoveryAST),
 };
 
Index: clang-tools-extra/clangd/Compiler.cpp
===
--- clang-tools-extra/clangd/Compiler.cpp
+++ clang-tools-extra/clangd/Compiler.cpp
@@ -81,11 +81,11 @@
   // Don't crash on `#pragma clang __debug parser_crash`
   CI->getPreprocessorOpts().DisablePragmaDebugCrash = true;
 
-  // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus) {
-CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
-CI->getLangOpts()->RecoveryASTType = Inputs.Opts.PreserveRecoveryASTType;
-  }
+  if (Inputs.Opts.BuildRecoveryAST)
+CI->getLangOpts()->RecoveryAST = true;
+  if (Inputs.Opts.PreserveRecoveryASTType)
+CI->getLangOpts()->RecoveryASTType = true;
+
   return CI;
 }
 
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -128,11 +128,13 @@
 /// enabled.
 ClangTidyOptionsBuilder GetClangTidyOptions;
 
-/// If true, turn on the `-frecovery-ast` clang flag.
-bool BuildRecoveryAST = true;
+/// If true, force -frecovery-ast flag.
+/// If false, respect the value in clang.
+bool BuildRecoveryAST = false;
 
-/// If true, turn on the `-frecovery-ast-type` clang flag.
-bool PreserveRecoveryASTType = true;
+/// If true, force -frecovery-ast-type flag.
+/// If false, respect the value in clang.
+bool PreserveRecoveryASTType = false;
 
 /// Clangd's workspace root. Relevant for "workspace" operations not bound
 /// to a particular file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Marco Antognini via Phabricator via cfe-commits
mantognini created this revision.
Herald added subscribers: cfe-commits, kerbowa, Anastasia, yaxunl, nhaehnle, 
jvesely, jholewinski.
Herald added a project: clang.
mantognini updated this revision to Diff 298093.
mantognini added a comment.
mantognini published this revision for review.

Addressed buildbot issues.


Many non-language extensions are defined but also unused. This patch
removes them with their tests as they do not require compiler support.

The cl_khr_select_fprounding_mode extension is also removed because it
has been deprecated since OpenCL 1.1 and Clang doesn't have any specific
support for it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89372

Files:
  clang/include/clang/Basic/OpenCLExtensions.def
  clang/lib/Basic/Targets/AMDGPU.h
  clang/lib/Basic/Targets/NVPTX.h
  clang/test/Misc/amdgcn.languageOptsOpenCL.cl
  clang/test/Misc/nvptx.languageOptsOpenCL.cl
  clang/test/Misc/r600.languageOptsOpenCL.cl
  clang/test/Preprocessor/init.c
  clang/test/SemaOpenCL/extension-version.cl

Index: clang/test/SemaOpenCL/extension-version.cl
===
--- clang/test/SemaOpenCL/extension-version.cl
+++ clang/test/SemaOpenCL/extension-version.cl
@@ -34,26 +34,8 @@
 #endif
 #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics: enable
 
-#ifndef cl_khr_gl_sharing
-#error "Missing cl_khr_gl_sharing define"
-#endif
-#pragma OPENCL EXTENSION cl_khr_gl_sharing: enable
-
-#ifndef cl_khr_icd
-#error "Missing cl_khr_icd define"
-#endif
-#pragma OPENCL EXTENSION cl_khr_icd: enable
-
 // Core features in CL 1.1
 
-#ifndef cl_khr_byte_addressable_store
-#error "Missing cl_khr_byte_addressable_store define"
-#endif
-#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 110) && defined TEST_CORE_FEATURES
-// expected-warning@-2{{OpenCL extension 'cl_khr_byte_addressable_store' is core feature or supported optional core feature - ignoring}}
-#endif
-
 #ifndef cl_khr_global_int32_base_atomics
 #error "Missing cl_khr_global_int32_base_atomics define"
 #endif
@@ -86,15 +68,6 @@
 // expected-warning@-2{{OpenCL extension 'cl_khr_local_int32_extended_atomics' is core feature or supported optional core feature - ignoring}}
 #endif
 
-#if (defined(__OPENCL_C_VERSION__) && __OPENCL_C_VERSION__ < 110)
-// Deprecated abvoe 1.0
-#ifndef cl_khr_select_fprounding_mode
-#error "Missing cl_khr_select_fp_rounding_mode define"
-#endif
-#pragma OPENCL EXTENSION cl_khr_select_fprounding_mode: enable
-#endif
-
-
 // Core feature in CL 1.2
 #ifndef cl_khr_fp64
 #error "Missing cl_khr_fp64 define"
@@ -113,87 +86,6 @@
 // expected-warning@-2{{OpenCL extension 'cl_khr_3d_image_writes' is core feature or supported optional core feature - ignoring}}
 #endif
 
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 110)
-#ifndef cl_khr_gl_event
-#error "Missing cl_khr_gl_event define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_gl_event' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cl_khr_gl_event : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 110)
-#ifndef cl_khr_d3d10_sharing
-#error "Missing cl_khr_d3d10_sharing define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_d3d10_sharing' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cl_khr_d3d10_sharing : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 110)
-#ifndef cles_khr_int64
-#error "Missing cles_khr_int64 define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cles_khr_int64' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cles_khr_int64 : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 120)
-#ifndef cl_khr_context_abort
-#error "Missing cl_context_abort define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_context_abort' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cl_khr_context_abort : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 120)
-#ifndef cl_khr_d3d11_sharing
-#error "Missing cl_khr_d3d11_sharing define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_d3d11_sharing' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cl_khr_d3d11_sharing : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 120)
-#ifndef cl_khr_dx9_media_sharing
-#error "Missing cl_khr_dx9_media_sharing define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_dx9_media_sharing' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION cl_khr_dx9_media_sharing : enable
-
-#if (defined(__OPENCL_CPP_VERSION__) || __OPENCL_C_VERSION__ >= 120)
-#ifndef cl_khr_image2d_from_buffer
-#error "Missing cl_khr_image2d_from_buffer define"
-#endif
-#else
-// expected-warning@+2{{unsupported OpenCL extension 'cl_khr_image2d_from_buffer' - ignoring}}
-#endif
-#pragma OPENCL EXTENSION

[clang-tools-extra] 3fcca80 - [clangd] Refine recoveryAST flags in clangd

2020-10-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-10-14T13:42:11+02:00
New Revision: 3fcca804b2916b68d34523e9f88c77272a256d77

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

LOG: [clangd] Refine recoveryAST flags in clangd

so that we could start experiment for C.

Previously, these flags in clangd were only meaningful for C++. We need
to flip them for C, this patch repurpose these flags.

- if true, just set it.
- if false, just respect the value in clang.

this would allow us to keep flags on for C++, and optionally flip them on for C.

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/Compiler.cpp
clang-tools-extra/clangd/tool/ClangdMain.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/clangd/unittests/TestTU.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.h 
b/clang-tools-extra/clangd/ClangdServer.h
index 555f387ff329..612524aae98d 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -128,11 +128,13 @@ class ClangdServer {
 /// enabled.
 ClangTidyOptionsBuilder GetClangTidyOptions;
 
-/// If true, turn on the `-frecovery-ast` clang flag.
-bool BuildRecoveryAST = true;
+/// If true, force -frecovery-ast flag.
+/// If false, respect the value in clang.
+bool BuildRecoveryAST = false;
 
-/// If true, turn on the `-frecovery-ast-type` clang flag.
-bool PreserveRecoveryASTType = true;
+/// If true, force -frecovery-ast-type flag.
+/// If false, respect the value in clang.
+bool PreserveRecoveryASTType = false;
 
 /// Clangd's workspace root. Relevant for "workspace" operations not bound
 /// to a particular file.

diff  --git a/clang-tools-extra/clangd/Compiler.cpp 
b/clang-tools-extra/clangd/Compiler.cpp
index f5875e2a7971..c22585fc53f9 100644
--- a/clang-tools-extra/clangd/Compiler.cpp
+++ b/clang-tools-extra/clangd/Compiler.cpp
@@ -81,11 +81,11 @@ buildCompilerInvocation(const ParseInputs &Inputs, 
clang::DiagnosticConsumer &D,
   // Don't crash on `#pragma clang __debug parser_crash`
   CI->getPreprocessorOpts().DisablePragmaDebugCrash = true;
 
-  // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus) {
-CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
-CI->getLangOpts()->RecoveryASTType = Inputs.Opts.PreserveRecoveryASTType;
-  }
+  if (Inputs.Opts.BuildRecoveryAST)
+CI->getLangOpts()->RecoveryAST = true;
+  if (Inputs.Opts.PreserveRecoveryASTType)
+CI->getLangOpts()->RecoveryASTType = true;
+
   return CI;
 }
 

diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 78d8355a2c5d..faa8c7508a93 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -310,7 +310,7 @@ opt CrossFileRename{
 opt RecoveryAST{
 "recovery-ast",
 cat(Features),
-desc("Preserve expressions in AST for broken code (C++ only)."),
+desc("Preserve expressions in AST for broken code."),
 init(ClangdServer::Options().BuildRecoveryAST),
 };
 

diff  --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index de73bc66a178..510f358920c1 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -111,8 +111,6 @@ CodeCompleteResult completions(const TestTU &TU, Position 
Point,
 
   MockFS FS;
   auto Inputs = TU.inputs(FS);
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {
@@ -1100,8 +1098,6 @@ SignatureHelp signatures(llvm::StringRef Text, Position 
Point,
   MockFS FS;
   auto Inputs = TU.inputs(FS);
   Inputs.Index = Index.get();
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index 1ea2aa34f289..a68ea1d6a3dc 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -148,6 +148,17 @@ TEST_F(TargetDeclTest, Exprs) {
   EXPECT_DECLS("LabelStmt", "label:");
 }
 
+TEST_F(TargetDeclTest, RecoveryForC) {
+  Flags = {"-xc", "-Xclang", "-frecovery-ast"};
+  Code = R"cpp(
+// error-ok: testing behavior on broken

[PATCH] D89233: [clangd] Refine recoveryAST flags in clangd

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3fcca804b291: [clangd] Refine recoveryAST flags in clangd 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89233

Files:
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Compiler.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp

Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -59,8 +59,6 @@
 FS.OverlayRealFileSystemForModules = true;
   Inputs.TFS = &FS;
   Inputs.Opts = ParseOptions();
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
   Inputs.Opts.ClangTidyOpts.WarningsAsErrors = ClangTidyWarningsAsErrors;
   Inputs.Index = ExternalIndex;
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -148,6 +148,17 @@
   EXPECT_DECLS("LabelStmt", "label:");
 }
 
+TEST_F(TargetDeclTest, RecoveryForC) {
+  Flags = {"-xc", "-Xclang", "-frecovery-ast"};
+  Code = R"cpp(
+// error-ok: testing behavior on broken code
+// int f();
+int f(int);
+int x = [[f]]();
+  )cpp";
+  EXPECT_DECLS("DeclRefExpr", "int f(int)");
+}
+
 TEST_F(TargetDeclTest, Recovery) {
   Code = R"cpp(
 // error-ok: testing behavior on broken code
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -111,8 +111,6 @@
 
   MockFS FS;
   auto Inputs = TU.inputs(FS);
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {
@@ -1100,8 +1098,6 @@
   MockFS FS;
   auto Inputs = TU.inputs(FS);
   Inputs.Index = Index.get();
-  Inputs.Opts.BuildRecoveryAST = true;
-  Inputs.Opts.PreserveRecoveryASTType = true;
   IgnoreDiagnostics Diags;
   auto CI = buildCompilerInvocation(Inputs, Diags);
   if (!CI) {
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -310,7 +310,7 @@
 opt RecoveryAST{
 "recovery-ast",
 cat(Features),
-desc("Preserve expressions in AST for broken code (C++ only)."),
+desc("Preserve expressions in AST for broken code."),
 init(ClangdServer::Options().BuildRecoveryAST),
 };
 
Index: clang-tools-extra/clangd/Compiler.cpp
===
--- clang-tools-extra/clangd/Compiler.cpp
+++ clang-tools-extra/clangd/Compiler.cpp
@@ -81,11 +81,11 @@
   // Don't crash on `#pragma clang __debug parser_crash`
   CI->getPreprocessorOpts().DisablePragmaDebugCrash = true;
 
-  // Recovery expression currently only works for C++.
-  if (CI->getLangOpts()->CPlusPlus) {
-CI->getLangOpts()->RecoveryAST = Inputs.Opts.BuildRecoveryAST;
-CI->getLangOpts()->RecoveryASTType = Inputs.Opts.PreserveRecoveryASTType;
-  }
+  if (Inputs.Opts.BuildRecoveryAST)
+CI->getLangOpts()->RecoveryAST = true;
+  if (Inputs.Opts.PreserveRecoveryASTType)
+CI->getLangOpts()->RecoveryASTType = true;
+
   return CI;
 }
 
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -128,11 +128,13 @@
 /// enabled.
 ClangTidyOptionsBuilder GetClangTidyOptions;
 
-/// If true, turn on the `-frecovery-ast` clang flag.
-bool BuildRecoveryAST = true;
+/// If true, force -frecovery-ast flag.
+/// If false, respect the value in clang.
+bool BuildRecoveryAST = false;
 
-/// If true, turn on the `-frecovery-ast-type` clang flag.
-bool PreserveRecoveryASTType = true;
+/// If true, force -frecovery-ast-type flag.
+/// If false, respect the value in clang.
+bool PreserveRecoveryASTType = false;
 
 /// Clangd's workspace root. Relevant for "workspace" operations not bound
 /// to a particular file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.or

[PATCH] D88498: [FPEnv] Evaluate initializers in constant rounding mode

2020-10-14 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 298119.
sepavloff added a comment.

Updated patch

- Reverted check to the previous version, in which it applied to C++ file level 
variables also.
- Added workaround for constexpr functions. Now they are parsed with constant 
rounding mode, which allows to use them with option `-frounding-math`.

Setting call-site rounding mode is not implemented yet.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88498

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/test/AST/const-fpfeatures-strict.c

Index: clang/test/AST/const-fpfeatures-strict.c
===
--- /dev/null
+++ clang/test/AST/const-fpfeatures-strict.c
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -S -emit-llvm -ffp-exception-behavior=strict -Wno-unknown-pragmas %s -o - | FileCheck %s
+
+// nextUp(1.F) == 0x1.02p0F
+
+struct S {
+  float f;
+};
+
+static struct S var_01 = {0x1.01p0};
+struct S *func_01() {
+  return &var_01;
+}
+
+struct S var_02 = {0x1.01p0};
+
+struct S *func_03() {
+  static struct S var_03 = {0x1.01p0};
+  return &var_03;
+}
+
+// CHECK: @var_01 = {{.*}} %struct.S { float 1.00e+00 }
+// CHECK: @var_02 = {{.*}} %struct.S { float 1.00e+00 }
+// CHECK: @func_03.var_03 = {{.*}} %struct.S { float 1.00e+00 }
+
+#pragma STDC FENV_ROUND FE_UPWARD
+
+static struct S var_04 = {0x1.01p0};
+struct S *func_04() {
+  return &var_04;
+}
+
+struct S var_05 = {0x1.01p0};
+
+struct S *func_06() {
+  static struct S var_06 = {0x1.01p0};
+  return &var_06;
+}
+
+// CHECK: @var_04 = {{.*}} %struct.S { float 0x3FF02000 }
+// CHECK: @var_05 = {{.*}} %struct.S { float 0x3FF02000 }
+// CHECK: @func_06.var_06 = {{.*}} %struct.S { float 0x3FF02000 }
Index: clang/lib/Parse/ParseStmt.cpp
===
--- clang/lib/Parse/ParseStmt.cpp
+++ clang/lib/Parse/ParseStmt.cpp
@@ -2253,6 +2253,11 @@
   Sema::PragmaStackSentinelRAII
 PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
 
+  Sema::FPFeaturesStateRAII SavedFPFeatues(Actions);
+  if (auto Fn = dyn_cast_or_null(Decl))
+if (Fn->isConstexpr())
+  Actions.adjustFPFeaturesForGlobal();
+
   // Do not enter a scope for the brace, as the arguments are in the same scope
   // (the function body) as the body itself.  Instead, just read the statement
   // list and put it into a CompoundStmt for safe keeping.
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2284,6 +2284,17 @@
   }
 
   PreferredType.enterVariableInit(Tok.getLocation(), ThisDecl);
+
+  Sema::FPFeaturesStateRAII FPO(Actions);
+  if (auto VD = dyn_cast_or_null(ThisDecl))
+if (!VD->isInvalidDecl()) {
+  // If variable requires constant initialization, set constant
+  // rounding mode.
+  if (VD->isFileVarDecl() || VD->isConstexpr() ||
+  (!getLangOpts().CPlusPlus && VD->isStaticLocal()))
+Actions.adjustFPFeaturesForGlobal();
+}
+
   ExprResult Init = ParseInitializer();
 
   // If this is the only decl in (possibly) range based for statement,
Index: clang/include/clang/Sema/Sema.h
===
--- clang/include/clang/Sema/Sema.h
+++ clang/include/clang/Sema/Sema.h
@@ -589,13 +589,7 @@
   // This stack tracks the current state of Sema.CurFPFeatures.
   PragmaStack FpPragmaStack;
   FPOptionsOverride CurFPFeatureOverrides() {
-FPOptionsOverride result;
-if (!FpPragmaStack.hasValue()) {
-  result = FPOptionsOverride();
-} else {
-  result = FpPragmaStack.CurrentValue;
-}
-return result;
+return FpPragmaStack.CurrentValue;
   }
 
   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
@@ -1429,7 +1423,6 @@
 
   const LangOptions &getLangOpts() const { return LangOpts; }
   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
-  FPOptions &getCurFPFeatures() { return CurFPFeatures; }
 
   DiagnosticsEngine &getDiagnostics() const { return Diags; }
   SourceManager &getSourceManager() const { return SourceMgr; }
@@ -1439,6 +1432,24 @@
   ASTMutationListener *getASTMutationListener() const;
   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
 
+  const FPOptions &getCurFPFeatures() const { return CurFPFeatures; }
+  void setCurFPFeatures(FPOptions FPO) {
+FpPragmaStack.CurrentValue = FPOptionsOverride(FPO, CurFPFeatures);
+CurFPFeatures = FPO;
+  }
+
+  /// Adjust floating point options applied to parsing some global objects.
+  void adjustFPFeaturesForGlobal() {
+if (getCurFPFeatures()

[PATCH] D89319: [ASTImporter] Fix crash caused by unimported type of FromatAttr

2020-10-14 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Thanks for the review!




Comment at: clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp:2
+int foo(const char * fmt, ...)
+__attribute__ ((__format__ (__scanf__, 1, 2)));

teemperor wrote:
> (Not sure if we care about that in tests, but that's technically not in LLVM 
> code style)
Yeah, actually clang-format indicated this as well, so just now I changed the 
code to the clang-formatted one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89319

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


[PATCH] D89319: [ASTImporter] Fix crash caused by unimported type of FromatAttr

2020-10-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
martong marked an inline comment as done.
Closed by commit rGdd965711c9f0: [ASTImporter] Fix crash caused by unimported 
type of FromatAttr (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D89319?vs=297854&id=298120#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89319

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
  clang/test/ASTMerge/attr/testFormatAttr.cpp
  clang/unittests/AST/ASTImporterTest.cpp


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5767,6 +5767,31 @@
   EXPECT_TRUE(ToA);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int foo(const char * fmt, ...)
+  __attribute__ ((__format__ (__scanf__, 1, 2)));
+  )",
+  Lang_CXX03, "input.cc");
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  ASSERT_TRUE(FromD);
+
+  auto *ToD = Import(FromD, Lang_CXX03);
+  ASSERT_TRUE(ToD);
+  ToD->dump(); // Should not crash!
+
+  auto *FromAttr = FromD->getAttr();
+  auto *ToAttr = ToD->getAttr();
+  EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited());
+  EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion());
+  EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit());
+  EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax());
+  EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(),
+ToAttr->getAttributeSpellingListIndex());
+  EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName());
+}
 template 
 auto ExtendWithOptions(const T &Values, const std::vector &Args) {
   auto Copy = Values;
Index: clang/test/ASTMerge/attr/testFormatAttr.cpp
===
--- /dev/null
+++ clang/test/ASTMerge/attr/testFormatAttr.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -x c++-header -o %t.a.ast %S/Inputs/FormatAttr.cpp
+// RUN: %clang_cc1 -x c++ -ast-merge %t.a.ast /dev/null -ast-dump
Index: clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
===
--- /dev/null
+++ clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
@@ -0,0 +1 @@
+int foo(const char *fmt, ...) __attribute__((__format__(__scanf__, 1, 2)));
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -8100,6 +8100,16 @@
 ToAttr = To;
 break;
   }
+  case attr::Format: {
+const auto *From = cast(FromAttr);
+FormatAttr *To;
+IdentifierInfo *ToAttrType = Import(From->getType());
+To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(),
+From->getFirstArg(), ToRange, From->getSyntax());
+To->setInherited(From->isInherited());
+ToAttr = To;
+break;
+  }
   default:
 // FIXME: 'clone' copies every member but some of them should be imported.
 // Handle other Attrs that have parameters that should be imported.


Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5767,6 +5767,31 @@
   EXPECT_TRUE(ToA);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int foo(const char * fmt, ...)
+  __attribute__ ((__format__ (__scanf__, 1, 2)));
+  )",
+  Lang_CXX03, "input.cc");
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  ASSERT_TRUE(FromD);
+
+  auto *ToD = Import(FromD, Lang_CXX03);
+  ASSERT_TRUE(ToD);
+  ToD->dump(); // Should not crash!
+
+  auto *FromAttr = FromD->getAttr();
+  auto *ToAttr = ToD->getAttr();
+  EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited());
+  EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion());
+  EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit());
+  EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax());
+  EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(),
+ToAttr->getAttributeSpellingListIndex());
+  EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName());
+}
 template 
 auto ExtendWithOptions(const T &Values, const std::vector &Args) {
   auto Copy = Values;
Index: clang/test/ASTMerge/attr/testFormatAttr.cpp
===
--- /dev/null
+++ clang/test/ASTMerge/attr/testFormatAttr.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -x c++-header -o %t.a.ast %S/Inputs/FormatAttr.cpp
+// RUN: %clang_

[clang] dd96571 - [ASTImporter] Fix crash caused by unimported type of FromatAttr

2020-10-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-10-14T13:54:48+02:00
New Revision: dd965711c9f0e4b6e1dc9b465fe049c38e05d5aa

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

LOG: [ASTImporter] Fix crash caused by unimported type of FromatAttr

During the import of FormatAttrs we forgot to import the type (e.g
`__scanf__`) of the attribute. This caused a segfault when we wanted to
traverse the AST (e.g. by the dump() method).

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

Added: 
clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
clang/test/ASTMerge/attr/testFormatAttr.cpp

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

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 05cc717581ef..275e91235690 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8100,6 +8100,16 @@ Expected ASTImporter::Import(const Attr 
*FromAttr) {
 ToAttr = To;
 break;
   }
+  case attr::Format: {
+const auto *From = cast(FromAttr);
+FormatAttr *To;
+IdentifierInfo *ToAttrType = Import(From->getType());
+To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(),
+From->getFirstArg(), ToRange, From->getSyntax());
+To->setInherited(From->isInherited());
+ToAttr = To;
+break;
+  }
   default:
 // FIXME: 'clone' copies every member but some of them should be imported.
 // Handle other Attrs that have parameters that should be imported.

diff  --git a/clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp 
b/clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
new file mode 100644
index ..f249a6e65e0a
--- /dev/null
+++ b/clang/test/ASTMerge/attr/Inputs/FormatAttr.cpp
@@ -0,0 +1 @@
+int foo(const char *fmt, ...) __attribute__((__format__(__scanf__, 1, 2)));

diff  --git a/clang/test/ASTMerge/attr/testFormatAttr.cpp 
b/clang/test/ASTMerge/attr/testFormatAttr.cpp
new file mode 100644
index ..18329c1e1127
--- /dev/null
+++ b/clang/test/ASTMerge/attr/testFormatAttr.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -x c++-header -o %t.a.ast %S/Inputs/FormatAttr.cpp
+// RUN: %clang_cc1 -x c++ -ast-merge %t.a.ast /dev/null -ast-dump

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 51391d221626..967dc035d11f 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5767,6 +5767,31 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportExprOfAlignmentAttr) {
   EXPECT_TRUE(ToA);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  int foo(const char * fmt, ...)
+  __attribute__ ((__format__ (__scanf__, 1, 2)));
+  )",
+  Lang_CXX03, "input.cc");
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  ASSERT_TRUE(FromD);
+
+  auto *ToD = Import(FromD, Lang_CXX03);
+  ASSERT_TRUE(ToD);
+  ToD->dump(); // Should not crash!
+
+  auto *FromAttr = FromD->getAttr();
+  auto *ToAttr = ToD->getAttr();
+  EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited());
+  EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion());
+  EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit());
+  EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax());
+  EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(),
+ToAttr->getAttributeSpellingListIndex());
+  EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName());
+}
 template 
 auto ExtendWithOptions(const T &Values, const std::vector &Args) {
   auto Copy = Values;



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


[PATCH] D89360: Treat constant contexts as being in the default rounding mode.

2020-10-14 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

I would propose to consider solution in D88498 
. It tries to fix the real reason of the 
malfunction - using dynamic rounding mode for evaluation of global variable 
initializers. With the workaround for constexpr functions it allows to compile 
the test attached and still correctly detect runtime nature of local variable 
initializers.




Comment at: clang/lib/AST/ExprConstant.cpp:2533-2534
+  // exception state matches the default floating-point environment.
+  if (Info.InConstantContext)
+return true;
+

It turns off the check made by this function. In the case of global variable 
initializer it fixes the error (using dynamic rounding mode instead of default) 
but for local variable initializer it creates a new error. Constant evaluator 
cannot detect that the initializer in the code:
```
void g() {
  const int k = 3 * (1.0 / 3.0);
  ...
}
```
is not a constant expression.



Comment at: clang/test/SemaCXX/rounding-math.cpp:9
+
+constexpr int f(int n) { return int(n * (1.0 / 3.0)); }
+

This code requires additional solution. The function body is built using 
dynamic rounding mode, which breaks its constexprness. We can avoid this kind 
of errors if we assume that body of a constexpr function is parsed using 
constant rounding mode (in this example it is the default mode). It makes 
parsing constexpr function different from non-constexpr ones, but enables 
convenient use:
```
constexpr int add(float x, float y) { return x + y; }

#pragma STDC FENV_ROUND FE_UPWARD
int a2 = add(2.0F, 0x1.02p0F);

#pragma STDC FENV_ROUND FE_DOWNWARD
int a3 = add(2.0F, 0x1.02p0F);
```
If calls of constexpr functions are processes with FP options acting in the 
call site, a call to constexpr function becomes equivalent to execution of 
statements of its body.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89360

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


[PATCH] D89220: [clang-rename] Simplify the code of handling class paritial specializations, NFC.

2020-10-14 Thread Danila Malyutin via Phabricator via cfe-commits
danilaml added inline comments.



Comment at: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp:119
+llvm::for_each(PartialSpecs,
+   [&](const auto *Spec) { addUSRsOfCtorDtors(Spec); });
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());

Btw, this breaks on GCC <= 7.1, due to 
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67274
Workaround is to use `this->`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89220

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


[PATCH] D89318: [ASTImporter] Fix crash caused by unset AttributeSpellingListIndex

2020-10-14 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added a comment.

Thanks for the reivew!




Comment at: clang/lib/AST/ASTImporter.cpp:8109
+  FromAttr->getAttributeSpellingListIndex());
+  ToAttr->setPackExpansion(FromAttr->isPackExpansion());
+  ToAttr->setImplicit(FromAttr->isImplicit());

shafik wrote:
> Why move these two but not `setInherited(...)` it is not really explained in 
> the description.
Yeah, `setInherited` is a member of `InheritableAttr`, so the `Attr` base class 
does not have it.
Anyway, I changed the code and moved the calls of `setInherited` to an `if` 
block where we dyn_cast to `InheritableAttr`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89318

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


[PATCH] D89318: [ASTImporter] Fix crash caused by unset AttributeSpellingListIndex

2020-10-14 Thread Gabor Marton via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
martong marked an inline comment as done.
Closed by commit rG73c6beb2f705: [ASTImporter] Fix crash caused by unset 
AttributeSpellingListIndex (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D89318?vs=297853&id=298126#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89318

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
  clang/test/ASTMerge/attr/testRestrictAttr.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5767,11 +5767,35 @@
   EXPECT_TRUE(ToA);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportRestrictAttr) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  void *foo(unsigned, unsigned) __attribute__((__malloc__));
+  )",
+  Lang_CXX03, "input.cc");
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  ASSERT_TRUE(FromD);
+
+  auto *ToD = Import(FromD, Lang_CXX03);
+  ASSERT_TRUE(ToD);
+  ToD->dump(); // Should not crash!
+
+  auto *FromAttr = FromD->getAttr();
+  auto *ToAttr = ToD->getAttr();
+  EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited());
+  EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion());
+  EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit());
+  EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax());
+  EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(),
+ToAttr->getAttributeSpellingListIndex());
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) {
   Decl *FromTU = getTuDecl(
   R"(
   int foo(const char * fmt, ...)
-  __attribute__ ((__format__ (__scanf__, 1, 2)));
+  __attribute__ ((__format__ (__scanf__, 1, 2)));
   )",
   Lang_CXX03, "input.cc");
   auto *FromD = FirstDeclMatcher().match(
@@ -5792,6 +5816,7 @@
 ToAttr->getAttributeSpellingListIndex());
   EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName());
 }
+
 template 
 auto ExtendWithOptions(const T &Values, const std::vector &Args) {
   auto Copy = Values;
Index: clang/test/ASTMerge/attr/testRestrictAttr.cpp
===
--- /dev/null
+++ clang/test/ASTMerge/attr/testRestrictAttr.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -x c++-header -o %t.a.ast %S/Inputs/RestrictAttr.cpp
+// RUN: %clang_cc1 -x c++ -ast-merge %t.a.ast /dev/null -ast-dump
Index: clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
===
--- /dev/null
+++ clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
@@ -0,0 +1 @@
+void *foo(unsigned, unsigned) __attribute__((__malloc__));
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -8094,9 +8094,6 @@
   else
 return ToTOrErr.takeError();
 }
-To->setInherited(From->isInherited());
-To->setPackExpansion(From->isPackExpansion());
-To->setImplicit(From->isImplicit());
 ToAttr = To;
 break;
   }
@@ -8106,7 +8103,6 @@
 IdentifierInfo *ToAttrType = Import(From->getType());
 To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(),
 From->getFirstArg(), ToRange, From->getSyntax());
-To->setInherited(From->isInherited());
 ToAttr = To;
 break;
   }
@@ -8117,8 +8113,15 @@
 ToAttr->setRange(ToRange);
 break;
   }
+
   assert(ToAttr && "Attribute should be created.");
-  
+  if (const auto *InheritableFromAttr = dyn_cast(FromAttr))
+cast(ToAttr)->setInherited(
+InheritableFromAttr->isInherited());
+  ToAttr->setAttributeSpellingListIndex(
+  FromAttr->getAttributeSpellingListIndex());
+  ToAttr->setPackExpansion(FromAttr->isPackExpansion());
+  ToAttr->setImplicit(FromAttr->isImplicit());
   return ToAttr;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 73c6beb - [ASTImporter] Fix crash caused by unset AttributeSpellingListIndex

2020-10-14 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-10-14T14:10:08+02:00
New Revision: 73c6beb2f7053fe8b5150072c2b5cd930de38a22

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

LOG: [ASTImporter] Fix crash caused by unset AttributeSpellingListIndex

During the import of attributes we forgot to set the spelling list
index. This caused a segfault when we wanted to traverse the AST
(e.g. by the dump() method).

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

Added: 
clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
clang/test/ASTMerge/attr/testRestrictAttr.cpp

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

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 275e91235690..29fcf6c2a2a9 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8094,9 +8094,6 @@ Expected ASTImporter::Import(const Attr 
*FromAttr) {
   else
 return ToTOrErr.takeError();
 }
-To->setInherited(From->isInherited());
-To->setPackExpansion(From->isPackExpansion());
-To->setImplicit(From->isImplicit());
 ToAttr = To;
 break;
   }
@@ -8106,7 +8103,6 @@ Expected ASTImporter::Import(const Attr 
*FromAttr) {
 IdentifierInfo *ToAttrType = Import(From->getType());
 To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(),
 From->getFirstArg(), ToRange, From->getSyntax());
-To->setInherited(From->isInherited());
 ToAttr = To;
 break;
   }
@@ -8117,8 +8113,15 @@ Expected ASTImporter::Import(const Attr 
*FromAttr) {
 ToAttr->setRange(ToRange);
 break;
   }
+
   assert(ToAttr && "Attribute should be created.");
-  
+  if (const auto *InheritableFromAttr = dyn_cast(FromAttr))
+cast(ToAttr)->setInherited(
+InheritableFromAttr->isInherited());
+  ToAttr->setAttributeSpellingListIndex(
+  FromAttr->getAttributeSpellingListIndex());
+  ToAttr->setPackExpansion(FromAttr->isPackExpansion());
+  ToAttr->setImplicit(FromAttr->isImplicit());
   return ToAttr;
 }
 

diff  --git a/clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp 
b/clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
new file mode 100644
index ..2055a23b7c3c
--- /dev/null
+++ b/clang/test/ASTMerge/attr/Inputs/RestrictAttr.cpp
@@ -0,0 +1 @@
+void *foo(unsigned, unsigned) __attribute__((__malloc__));

diff  --git a/clang/test/ASTMerge/attr/testRestrictAttr.cpp 
b/clang/test/ASTMerge/attr/testRestrictAttr.cpp
new file mode 100644
index ..65903d8f66ca
--- /dev/null
+++ b/clang/test/ASTMerge/attr/testRestrictAttr.cpp
@@ -0,0 +1,2 @@
+// RUN: %clang -x c++-header -o %t.a.ast %S/Inputs/RestrictAttr.cpp
+// RUN: %clang_cc1 -x c++ -ast-merge %t.a.ast /dev/null -ast-dump

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 967dc035d11f..209374dd7048 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -5767,11 +5767,35 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportExprOfAlignmentAttr) {
   EXPECT_TRUE(ToA);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportRestrictAttr) {
+  Decl *FromTU = getTuDecl(
+  R"(
+  void *foo(unsigned, unsigned) __attribute__((__malloc__));
+  )",
+  Lang_CXX03, "input.cc");
+  auto *FromD = FirstDeclMatcher().match(
+  FromTU, functionDecl(hasName("foo")));
+  ASSERT_TRUE(FromD);
+
+  auto *ToD = Import(FromD, Lang_CXX03);
+  ASSERT_TRUE(ToD);
+  ToD->dump(); // Should not crash!
+
+  auto *FromAttr = FromD->getAttr();
+  auto *ToAttr = ToD->getAttr();
+  EXPECT_EQ(FromAttr->isInherited(), ToAttr->isInherited());
+  EXPECT_EQ(FromAttr->isPackExpansion(), ToAttr->isPackExpansion());
+  EXPECT_EQ(FromAttr->isImplicit(), ToAttr->isImplicit());
+  EXPECT_EQ(FromAttr->getSyntax(), ToAttr->getSyntax());
+  EXPECT_EQ(FromAttr->getAttributeSpellingListIndex(),
+ToAttr->getAttributeSpellingListIndex());
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, ImportFormatAttr) {
   Decl *FromTU = getTuDecl(
   R"(
   int foo(const char * fmt, ...)
-  __attribute__ ((__format__ (__scanf__, 1, 2)));
+  __attribute__ ((__format__ (__scanf__, 1, 2)));
   )",
   Lang_CXX03, "input.cc");
   auto *FromD = FirstDeclMatcher().match(
@@ -5792,6 +5816,7 @@ TEST_P(ASTImporterOptionSpecificTestBase, 
ImportFormatAttr) {
 ToAttr->getAttributeSpellingListIndex());
   EXPECT_EQ(FromAttr->getType()->getName(), ToAttr->getType()->getName());
 }
+
 template 
 auto ExtendWithOptions(const T &Values, const std::vector &Args) {
   auto Copy = Values;



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lis

[PATCH] D84362: [NFC] Refactor DiagnosticBuilder and PartialDiagnostic

2020-10-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 298125.
yaxunl added a comment.

revised by John's comments.

Extracted common part of DiagnosticEngine and PartialDiagnostics as 
DiagnosticStorage.

Make member functions of the base class of DiagnosticBuilder and 
ParticalDiagnostics non-virtual.


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

https://reviews.llvm.org/D84362

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/Attr.h
  clang/include/clang/AST/CanonicalType.h
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/AST/DeclarationName.h
  clang/include/clang/AST/DependentDiagnostic.h
  clang/include/clang/AST/NestedNameSpecifier.h
  clang/include/clang/AST/TemplateBase.h
  clang/include/clang/AST/TemplateName.h
  clang/include/clang/AST/Type.h
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Basic/PartialDiagnostic.h
  clang/include/clang/Sema/DelayedDiagnostic.h
  clang/include/clang/Sema/Ownership.h
  clang/include/clang/Sema/ParsedAttr.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Tooling/Refactoring/RefactoringRuleContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/TemplateBase.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/Basic/Diagnostic.cpp
  clang/unittests/Basic/DiagnosticTest.cpp

Index: clang/unittests/Basic/DiagnosticTest.cpp
===
--- clang/unittests/Basic/DiagnosticTest.cpp
+++ clang/unittests/Basic/DiagnosticTest.cpp
@@ -74,7 +74,7 @@
 TEST(DiagnosticTest, diagnosticError) {
   DiagnosticsEngine Diags(new DiagnosticIDs(), new DiagnosticOptions,
   new IgnoringDiagConsumer());
-  PartialDiagnostic::StorageAllocator Alloc;
+  PartialDiagnostic::DiagStorageAllocator Alloc;
   llvm::Expected> Value = DiagnosticError::create(
   SourceLocation(), PartialDiagnostic(diag::err_cannot_open_file, Alloc)
 << "file"
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -40,8 +40,9 @@
 
 using namespace clang;
 
-const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
-   DiagNullabilityKind nullability) {
+const StreamableDiagnosticBase &clang::
+operator<<(const StreamableDiagnosticBase &DB,
+   DiagNullabilityKind nullability) {
   StringRef string;
   switch (nullability.first) {
   case NullabilityKind::NonNull:
@@ -61,8 +62,8 @@
   return DB;
 }
 
-const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
-   llvm::Error &&E) {
+const StreamableDiagnosticBase &clang::
+operator<<(const StreamableDiagnosticBase &DB, llvm::Error &&E) {
   DB.AddString(toString(std::move(E)));
   return DB;
 }
@@ -481,13 +482,15 @@
 
   CurDiagLoc = storedDiag.getLocation();
   CurDiagID = storedDiag.getID();
-  NumDiagArgs = 0;
+  DiagStorage.NumDiagArgs = 0;
 
-  DiagRanges.clear();
-  DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
+  DiagStorage.DiagRanges.clear();
+  DiagStorage.DiagRanges.append(storedDiag.range_begin(),
+storedDiag.range_end());
 
-  DiagFixItHints.clear();
-  DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
+  DiagStorage.FixItHints.clear();
+  DiagStorage.FixItHints.append(storedDiag.fixit_begin(),
+storedDiag.fixit_end());
 
   assert(Client && "DiagnosticConsumer not set!");
   Level DiagLevel = storedDiag.getLevel();
@@ -1140,13 +1143,13 @@
   return Target.IncludeInDiagnosticCounts();
 }
 
-PartialDiagnostic::StorageAllocator::StorageAllocator() {
+PartialDiagnostic::DiagStorageAllocator::DiagStorageAllocator() {
   for (unsigned I = 0; I != NumCached; ++I)
 FreeList[I] = Cached + I;
   NumFreeListEntries = NumCached;
 }
 
-PartialDiagnostic::StorageAllocator::~StorageAllocator() {
+PartialDiagnostic::DiagStorageAllocator::~DiagStorageAllocator() {
   // Don't assert if we are in a CrashRecovery context, as this invariant may
   // be invalidated during a crash.
   assert((NumFreeListEntries == NumCached ||
Index: clang/lib/AST/TemplateName.cpp
===
--- clang/lib/AST/TemplateName.cpp
+++ clang/lib/AST/TemplateName.cpp
@@ -254,8 +254,8 @@
   }
 }
 
-const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
-   TemplateName N) {
+const StreamableDiagnosticBase &clang::
+operator<<(const StreamableDiagnosticBase &DB, TemplateName N) {
   std::string NameStr;
   llvm::raw_string_ostream OS(NameStr);
   LangOptions LO;
@@ -268,20 +268,6 @@
   return DB << NameStr;
 }
 
-const PartialDiagnostic&clang::operator<<(const PartialDiagnostic &PD,
-  

[clang-tools-extra] 82a7182 - [clangd] Disable extract variable for RHS of assignments

2020-10-14 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2020-10-14T14:22:47+02:00
New Revision: 82a71822a54d76c62bf730d8c0e8e86d68c60159

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

LOG: [clangd] Disable extract variable for RHS of assignments

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
clang-tools-extra/clangd/unittests/TweakTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
index 8b668be5f2f9..8feef4e84722 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
@@ -382,17 +382,27 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
   if (BinOp.parse(*N) && BinaryOperator::isAssignmentOp(BinOp.Kind))
 return false;
 
+  const SelectionTree::Node &OuterImplicit = N->outerImplicit();
+  const auto *Parent = OuterImplicit.Parent;
+  if (!Parent)
+return false;
   // We don't want to extract expressions used as statements, that would leave
   // a `dummy;` around that has no effect.
   // Unfortunately because the AST doesn't have ExprStmt, we have to check in
   // this roundabout way.
-  const SelectionTree::Node &OuterImplicit = N->outerImplicit();
-  if (!OuterImplicit.Parent ||
-  childExprIsStmt(OuterImplicit.Parent->ASTNode.get(),
+  if (childExprIsStmt(Parent->ASTNode.get(),
   OuterImplicit.ASTNode.get()))
 return false;
 
-  // FIXME: ban extracting the RHS of an assignment: `a = [[foo()]]`
+  // Disable extraction of full RHS on assignment operations, e.g:
+  // auto x = [[RHS_EXPR]];
+  // This would just result in duplicating the code.
+  if (const auto *BO = Parent->ASTNode.get()) {
+if (BO->isAssignmentOp() &&
+BO->getRHS() == OuterImplicit.ASTNode.get())
+  return false;
+  }
+
   return true;
 }
 

diff  --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp 
b/clang-tools-extra/clangd/unittests/TweakTests.cpp
index f64d42a7eed7..718b84d03990 100644
--- a/clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -215,26 +215,26 @@ TEST_F(ExtractVariableTest, Test) {
 int x = [[1]], y = [[a + 1]], a = [[1]], z = a + 1;
   // if without else
   if([[1]])
-a = [[1]];
+a = [[1]] + 1;
   // if with else
   if(a < [[3]])
 if(a == [[4]])
-  a = [[5]];
+  a = [[5]] + 1;
 else
-  a = [[5]];
+  a = [[5]] + 1;
   else if (a < [[4]])
-a = [[4]];
+a = [[4]] + 1;
   else
-a = [[5]];
+a = [[5]] + 1;
   // for loop
-  for(a = [[1]]; a > 3]] + [[4; a++)
-a = [[2]];
+  for(a = [[1]] + 1; a > 3]] + [[4; a++)
+a = [[2]] + 1;
   // while
   while(a < [[1]])
-a = [[1]];
+a = [[1]] + 1;
   // do while
   do
-a = [[1]];
+a = [[1]] + 1;
   while(a < [[3]]);
 }
   )cpp";
@@ -291,6 +291,7 @@ TEST_F(ExtractVariableTest, Test) {
   xyz([[a *= 5]]);
   // Variable DeclRefExpr
   a = [[b]];
+  a = [[xyz()]];
   // statement expression
   [[xyz()]];
   while (a)
@@ -373,10 +374,10 @@ TEST_F(ExtractVariableTest, Test) {
  })cpp"},
   // attribute testing
   {R"cpp(void f(int a) {
-[ [gsl::suppress("type")] ] for (;;) a = [[1]];
+[ [gsl::suppress("type")] ] for (;;) a = [[1]] + 1;
  })cpp",
R"cpp(void f(int a) {
-auto dummy = 1; [ [gsl::suppress("type")] ] for (;;) a = 
dummy;
+auto dummy = 1; [ [gsl::suppress("type")] ] for (;;) a = 
dummy + 1;
  })cpp"},
   // MemberExpr
   {R"cpp(class T {



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


[PATCH] D89307: [clangd] Disable extract variable for RHS of assignments

2020-10-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG82a71822a54d: [clangd] Disable extract variable for RHS of 
assignments (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89307

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp


Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -215,26 +215,26 @@
 int x = [[1]], y = [[a + 1]], a = [[1]], z = a + 1;
   // if without else
   if([[1]])
-a = [[1]];
+a = [[1]] + 1;
   // if with else
   if(a < [[3]])
 if(a == [[4]])
-  a = [[5]];
+  a = [[5]] + 1;
 else
-  a = [[5]];
+  a = [[5]] + 1;
   else if (a < [[4]])
-a = [[4]];
+a = [[4]] + 1;
   else
-a = [[5]];
+a = [[5]] + 1;
   // for loop
-  for(a = [[1]]; a > 3]] + [[4; a++)
-a = [[2]];
+  for(a = [[1]] + 1; a > 3]] + [[4; a++)
+a = [[2]] + 1;
   // while
   while(a < [[1]])
-a = [[1]];
+a = [[1]] + 1;
   // do while
   do
-a = [[1]];
+a = [[1]] + 1;
   while(a < [[3]]);
 }
   )cpp";
@@ -291,6 +291,7 @@
   xyz([[a *= 5]]);
   // Variable DeclRefExpr
   a = [[b]];
+  a = [[xyz()]];
   // statement expression
   [[xyz()]];
   while (a)
@@ -373,10 +374,10 @@
  })cpp"},
   // attribute testing
   {R"cpp(void f(int a) {
-[ [gsl::suppress("type")] ] for (;;) a = [[1]];
+[ [gsl::suppress("type")] ] for (;;) a = [[1]] + 1;
  })cpp",
R"cpp(void f(int a) {
-auto dummy = 1; [ [gsl::suppress("type")] ] for (;;) a = 
dummy;
+auto dummy = 1; [ [gsl::suppress("type")] ] for (;;) a = 
dummy + 1;
  })cpp"},
   // MemberExpr
   {R"cpp(class T {
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractVariable.cpp
@@ -382,17 +382,27 @@
   if (BinOp.parse(*N) && BinaryOperator::isAssignmentOp(BinOp.Kind))
 return false;
 
+  const SelectionTree::Node &OuterImplicit = N->outerImplicit();
+  const auto *Parent = OuterImplicit.Parent;
+  if (!Parent)
+return false;
   // We don't want to extract expressions used as statements, that would leave
   // a `dummy;` around that has no effect.
   // Unfortunately because the AST doesn't have ExprStmt, we have to check in
   // this roundabout way.
-  const SelectionTree::Node &OuterImplicit = N->outerImplicit();
-  if (!OuterImplicit.Parent ||
-  childExprIsStmt(OuterImplicit.Parent->ASTNode.get(),
+  if (childExprIsStmt(Parent->ASTNode.get(),
   OuterImplicit.ASTNode.get()))
 return false;
 
-  // FIXME: ban extracting the RHS of an assignment: `a = [[foo()]]`
+  // Disable extraction of full RHS on assignment operations, e.g:
+  // auto x = [[RHS_EXPR]];
+  // This would just result in duplicating the code.
+  if (const auto *BO = Parent->ASTNode.get()) {
+if (BO->isAssignmentOp() &&
+BO->getRHS() == OuterImplicit.ASTNode.get())
+  return false;
+  }
+
   return true;
 }
 


Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -215,26 +215,26 @@
 int x = [[1]], y = [[a + 1]], a = [[1]], z = a + 1;
   // if without else
   if([[1]])
-a = [[1]];
+a = [[1]] + 1;
   // if with else
   if(a < [[3]])
 if(a == [[4]])
-  a = [[5]];
+  a = [[5]] + 1;
 else
-  a = [[5]];
+  a = [[5]] + 1;
   else if (a < [[4]])
-a = [[4]];
+a = [[4]] + 1;
   else
-a = [[5]];
+a = [[5]] + 1;
   // for loop
-  for(a = [[1]]; a > 3]] + [[4; a++)
-a = [[2]];
+  for(a = [[1]] + 1; a > 3]] + [[4; a++)
+a = [[2]] + 1;
   // while
   while(a < [[1]])
-a = [[1]];
+a = [[1]] + 1;
   // do while
   do
-a = [[1]];
+a = [[1]] + 1;
   while(a < [[3]]);
 }
   )cpp";
@@ -291,6 +291,7 @@
   xyz([[a *= 5]]);
   // Variable DeclRefExpr
   a = [[b]];
+  a = [[xyz()]];
   // statement expression
 

[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

what if users rely on the predefined macros associated with the extension e.g. 
cl_khr_srgb_image_writes to enable/disable certain code?

What's the issue with these extensions not removed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89212: PR47663: Warn if an entity becomes weak after its first use.

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

LGTM aside from some very small nits (feel free to ignore any that don't make 
sense to you).




Comment at: clang/lib/AST/DeclBase.cpp:622
 
+AvailabilityResult AvailabilityAttr::getAvailability(ASTContext &C) const {
+  return CheckAvailability(C, this, nullptr, VersionTuple());

This is just novel enough that I'd appreciate a comment about the declaration 
being in Attr.td so it's more obvious where to find this.



Comment at: clang/lib/Sema/SemaDecl.cpp:6431
+  // be null.
+  auto *VD = dyn_cast(&ND);
+  if (VD && VD->isUsed(false) && VD->isWeak() &&

Can the pointers here all be marked `const` or does that cause issues?



Comment at: clang/lib/Sema/SemaDecl.cpp:6435-6436
+Attr *WeakA = nullptr;
+for (Attr *A : VD->getAttrs()) {
+  if (!isa(A))
+continue;

Ah, it's too bad that `Decl::specific_attrs()` doesn't accept a pack of 
attributes...



Comment at: clang/lib/Sema/SemaDecl.cpp:18288
 
-  if (PrevDecl) {
-PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, 
AttributeCommonInfo::AS_Pragma));
+  if (NamedDecl *PrevDecl =
+  LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName)) {

Same request for `const` here as above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89212

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


[PATCH] D89277: [clangd] Add $/dumpMemoryTree LSP extension

2020-10-14 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

(sorry out today and haven't looked at code yet)

If it's a custom method, I think it should return the data as a json structure 
- the client already has to have custom support to invoke it, displaying the 
result isn't much extra work.

And I would really love to add a tree view to vscode, I think it wouldn't be 
hard (vs call hierarchy: no laziness and no direction-flipping) and could be 
reused for an AST viewer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89277

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


[PATCH] D78658: [clang][Frontend] Add missing error handling

2020-10-14 Thread LemonBoy via Phabricator via cfe-commits
LemonBoy updated this revision to Diff 298133.

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

https://reviews.llvm.org/D78658

Files:
  clang/lib/Frontend/ASTUnit.cpp
  clang/unittests/Frontend/ASTUnitTest.cpp

Index: clang/unittests/Frontend/ASTUnitTest.cpp
===
--- clang/unittests/Frontend/ASTUnitTest.cpp
+++ clang/unittests/Frontend/ASTUnitTest.cpp
@@ -150,4 +150,28 @@
   &File->getFileEntry()));
 }
 
+TEST_F(ASTUnitTest, LoadFromCommandLineEarlyError) {
+  EXPECT_FALSE(
+  llvm::sys::fs::createTemporaryFile("ast-unit", "c", FD, InputFileName));
+  input_file = std::make_unique(InputFileName, FD);
+  input_file->os() << "";
+
+  const char *Args[] = {"clang", "-target", "foobar", InputFileName.c_str()};
+
+  auto Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
+  auto PCHContainerOps = std::make_shared();
+  std::unique_ptr ErrUnit;
+
+  ASTUnit *AST = ASTUnit::LoadFromCommandLine(
+  &Args[0], &Args[4], PCHContainerOps, Diags, "", false,
+  CaptureDiagsKind::All, None, true, 0, TU_Complete, false, false, false,
+  SkipFunctionBodiesScope::None, false, true, false, false, None, &ErrUnit,
+  nullptr);
+
+  ASSERT_EQ(AST, nullptr);
+  ASSERT_NE(ErrUnit, nullptr);
+  ASSERT_TRUE(Diags->hasErrorOccurred());
+  ASSERT_NE(ErrUnit->stored_diag_size(), 0U);
+}
+
 } // anonymous namespace
Index: clang/lib/Frontend/ASTUnit.cpp
===
--- clang/lib/Frontend/ASTUnit.cpp
+++ clang/lib/Frontend/ASTUnit.cpp
@@ -69,6 +69,7 @@
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringMap.h"
@@ -1118,6 +1119,19 @@
   std::unique_ptr Clang(
   new CompilerInstance(std::move(PCHContainerOps)));
 
+  // Clean up on error, disengage it if the function returns successfully.
+  auto CleanOnError = llvm::make_scope_exit([&]() {
+// Remove the overridden buffer we used for the preamble.
+SavedMainFileBuffer = nullptr;
+
+// Keep the ownership of the data in the ASTUnit because the client may
+// want to see the diagnostics.
+transferASTDataFromCompilerInstance(*Clang);
+FailedParseDiagnostics.swap(StoredDiagnostics);
+StoredDiagnostics.clear();
+NumStoredDiagnosticsFromDriver = 0;
+  });
+
   // Ensure that Clang has a FileManager with the right VFS, which may have
   // changed above in AddImplicitPreamble.  If VFS is nullptr, rely on
   // createFileManager to create one.
@@ -1200,7 +1214,7 @@
 ActCleanup(Act.get());
 
   if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
-goto error;
+return true;
 
   if (SavedMainFileBuffer)
 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
@@ -1210,7 +1224,7 @@
 
   if (llvm::Error Err = Act->Execute()) {
 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
-goto error;
+return true;
   }
 
   transferASTDataFromCompilerInstance(*Clang);
@@ -1219,19 +1233,9 @@
 
   FailedParseDiagnostics.clear();
 
-  return false;
+  CleanOnError.release();
 
-error:
-  // Remove the overridden buffer we used for the preamble.
-  SavedMainFileBuffer = nullptr;
-
-  // Keep the ownership of the data in the ASTUnit because the client may
-  // want to see the diagnostics.
-  transferASTDataFromCompilerInstance(*Clang);
-  FailedParseDiagnostics.swap(StoredDiagnostics);
-  StoredDiagnostics.clear();
-  NumStoredDiagnosticsFromDriver = 0;
-  return true;
+  return false;
 }
 
 static std::pair
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e6b4179 - Fix a broken build for gcc <= 7.1

2020-10-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2020-10-14T15:14:59+02:00
New Revision: e6b4179c5d282905a8ad17c57153b991c42d1126

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

LOG: Fix a broken build for gcc <= 7.1

we need add a "this->" inside the lambda body to workaround it. Rewrite
it to normal for-range loop.

Added: 


Modified: 
clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp 
b/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
index 82ef26e18369..886c8ee551a0 100644
--- a/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
+++ b/clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp
@@ -27,7 +27,6 @@
 #include "clang/Tooling/Refactoring.h"
 #include "clang/Tooling/Refactoring/Rename/USRFinder.h"
 #include "clang/Tooling/Tooling.h"
-#include "llvm/ADT/STLExtras.h"
 
 #include 
 #include 
@@ -115,8 +114,8 @@ class AdditionalUSRFinder : public 
RecursiveASTVisitor {
   addUSRsOfCtorDtors(Specialization);
 SmallVector PartialSpecs;
 TemplateDecl->getPartialSpecializations(PartialSpecs);
-llvm::for_each(PartialSpecs,
-   [&](const auto *Spec) { addUSRsOfCtorDtors(Spec); });
+for (const auto *Spec : PartialSpecs)
+  addUSRsOfCtorDtors(Spec);
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());
   }
 



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


[PATCH] D89220: [clang-rename] Simplify the code of handling class paritial specializations, NFC.

2020-10-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Tooling/Refactoring/Rename/USRFindingAction.cpp:119
+llvm::for_each(PartialSpecs,
+   [&](const auto *Spec) { addUSRsOfCtorDtors(Spec); });
 addUSRsOfCtorDtors(TemplateDecl->getTemplatedDecl());

danilaml wrote:
> Btw, this breaks on GCC <= 7.1, due to 
> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67274
> Workaround is to use `this->`.
oh, thanks for spotting it!

Fixed in e6b4179c5d282905a8ad17c57153b991c42d1126, instead of adding `this->`, 
I reverted it to the for-range loop. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89220

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added a comment.

In D89372#2329939 , @yaxunl wrote:

> what if users rely on the predefined macros associated with the extension 
> e.g. cl_khr_srgb_image_writes to enable/disable certain code?
>
> What's the issue with these extensions not removed?

I meant to add a link to the RFC that highlighted the issue: 
http://lists.llvm.org/pipermail/cfe-dev/2020-September/066911.html

In a nutshell, those extensions I'm removing are not language extensions but 
api extensions. I can't think of the usefulness of these macros -- if the host 
doesn't support the extensions, the kernels relying on those cannot be executed 
(i.e. it makes no sense). @Anastasia also highlights in her comment that having 
these increases the complexity and maintenance burden in the ecosystem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Yes, this is a group of extensions that doesn't seem to change anything in the 
kernel language. So if the macro is available I don't understand how it can be 
used to do anything different in the kernel code because it just doesn't modify 
anything in the kernel code.

FYI I have attempted to clarify the extensions with Khronos  
https://github.com/KhronosGroup/OpenCL-Docs/issues/82 but it didn't go very far 
unfortunately. I presume this is not important enough and some extensions are 
not even described at all or deprecated. If this is the case they should not 
hold us back.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89380: [clang-tidy] Fix for cppcoreguidelines-prefer-member-initializer to handle classes declared in macros

2020-10-14 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

Thanks for the fix! However, I'm not sure it's possible to correctly rewrite 
code in all cases where macros are involved. See a couple of motivating 
examples in the comment.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp:492
+
+#define MACRO1 struct InMacro1 { int i; InMacro1() { i = 0; } };
+// CHECK-MESSAGES: :[[@LINE-1]]:54: warning: 'i' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]

Could you add tests where the field name comes from a macro argument and from 
token pasting? Something along the lines of:

```
#define MACRO4(field) struct InMacro1 { int field; InMacro1() { field = 0; } }

MACRO4(q);

#define MACRO5(X) X

MACRO5(struct InMacro1 { int field; InMacro1() { field = 0; } });

#define MACRO6(field) struct InMacro1 { int qqq ## field; InMacro1() { qqq ## 
field = 0; } }

MACRO6(q);
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89380

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


[PATCH] D89380: [clang-tidy] Fix for cppcoreguidelines-prefer-member-initializer to handle classes declared in macros

2020-10-14 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh requested changes to this revision.
alexfh added inline comments.
This revision now requires changes to proceed.



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp:170
+  auto Diag =
+diag(BeginLoc, "%0 should be initialized in an in-class"
+   " default member initializer")

Looks like clang-format is not happy with a number of places in the file. Could 
you git clang-format the patch? (Or just clang-format the whole file - maybe in 
a separate commit - if you don't have the git integration handy.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89380

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


[clang] b21ad3b - Fix `-Wparentheses` warnings. NFC.

2020-10-14 Thread Michael Liao via cfe-commits

Author: Michael Liao
Date: 2020-10-14T10:11:19-04:00
New Revision: b21ad3b66bce942ee6e0f5b1fcfdea31928005a7

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

LOG: Fix `-Wparentheses` warnings. NFC.

Added: 


Modified: 
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index a02db2293bcc..0407d5bb7f6c 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -6384,10 +6384,10 @@ ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, 
SourceLocation LParenLoc,
   if (Context.isDependenceAllowed() &&
   (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) 
{
 assert(!getLangOpts().CPlusPlus);
-assert(Fn->containsErrors() ||
-   llvm::any_of(ArgExprs,
-[](clang::Expr *E) { return E->containsErrors(); }) &&
-   "should only occur in error-recovery path.");
+assert((Fn->containsErrors() ||
+llvm::any_of(ArgExprs,
+ [](clang::Expr *E) { return E->containsErrors(); })) 
&&
+   "should only occur in error-recovery path.");
 QualType ReturnType =
 llvm::isa_and_nonnull(NDecl)
 ? dyn_cast(NDecl)->getCallResultType()



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


[PATCH] D89348: clang/Basic: Replace ContentCache::getBuffer with Optional semantics

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 298144.
dexonsmith added a comment.

Cleaned up the (fixed) `Invalid` logic to reduce the size of the diff and use a 
consistent pattern. Thanks for you patience with the false start; I think this 
is ready now.


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

https://reviews.llvm.org/D89348

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang/include/clang/Basic/SourceManager.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2002,9 +2002,9 @@
 // We add one to the size so that we capture the trailing NULL
 // that is required by llvm::MemoryBuffer::getMemBuffer (on
 // the reader side).
-const llvm::MemoryBuffer *Buffer =
-Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
-StringRef Name = Buffer->getBufferIdentifier();
+llvm::Optional Buffer =
+Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
+StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
   StringRef(Name.data(), Name.size() + 1));
 EmitBlob = true;
@@ -2016,8 +2016,10 @@
   if (EmitBlob) {
 // Include the implicit terminating null character in the on-disk buffer
 // if we're writing it uncompressed.
-const llvm::MemoryBuffer *Buffer =
-Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
+llvm::Optional Buffer =
+Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
+if (!Buffer)
+  Buffer = llvm::MemoryBufferRef("<<>>", "");
 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
  SLocBufferBlobAbbrv);
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -118,18 +118,25 @@
   return InvalidBOM;
 }
 
-const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
-  FileManager &FM,
-  SourceLocation Loc,
-  bool *Invalid) const {
+llvm::Optional
+ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
+  SourceLocation Loc) const {
+  if (auto *B = getBufferPointer(Diag, FM, Loc))
+return B->getMemBufferRef();
+  return None;
+}
+
+const llvm::MemoryBuffer *
+ContentCache::getBufferPointer(DiagnosticsEngine &Diag, FileManager &FM,
+   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
-  if (Buffer.getPointer() || !ContentsEntry) {
-if (Invalid)
-  *Invalid = isBufferInvalid();
-
-return Buffer.getPointer();
-  }
+  if (isBufferInvalid())
+return nullptr;
+  if (auto *B = Buffer.getPointer())
+return B;
+  if (!ContentsEntry)
+return nullptr;
 
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
@@ -138,13 +145,6 @@
   // miserably on large source files.
   if ((uint64_t)ContentsEntry->getSize() >=
   std::numeric_limits::max()) {
-// We can't make a memory buffer of the required size, so just make a small
-// one. We should never hit a situation where we've already parsed to a
-// later offset of the file, so it shouldn't matter that the buffer is
-// smaller than the file.
-Buffer.setPointer(
-llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
-.release());
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_file_too_large,
 ContentsEntry->getName());
@@ -153,8 +153,7 @@
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-if (Invalid) *Invalid = true;
-return Buffer.getPointer();
+return nullptr;
   }
 
   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
@@ -164,20 +163,7 @@
   // exists. Most likely, we were using a stat cache with an invalid entry but
   // the file could also have been removed during processing. Since we can't
   // really deal with this situation, just create an empty buffer.
-  //
-  // FIXME: This is definitely not ideal, but our immediate clients can't
-  // currently handle returning a null ent

[PATCH] D89348: clang/Basic: Replace ContentCache::getBuffer with Optional semantics

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 298145.
dexonsmith added a comment.

Hah, and now I notice while working on a follow-up that 
`SourceManager::getBufferOrNone` was missing a `const`-qualifier (the use in 
this patch didn't need it). Fixed that too.


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

https://reviews.llvm.org/D89348

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang/include/clang/Basic/SourceManager.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Serialization/ASTWriter.cpp

Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2002,9 +2002,9 @@
 // We add one to the size so that we capture the trailing NULL
 // that is required by llvm::MemoryBuffer::getMemBuffer (on
 // the reader side).
-const llvm::MemoryBuffer *Buffer =
-Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
-StringRef Name = Buffer->getBufferIdentifier();
+llvm::Optional Buffer =
+Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
+StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
   StringRef(Name.data(), Name.size() + 1));
 EmitBlob = true;
@@ -2016,8 +2016,10 @@
   if (EmitBlob) {
 // Include the implicit terminating null character in the on-disk buffer
 // if we're writing it uncompressed.
-const llvm::MemoryBuffer *Buffer =
-Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
+llvm::Optional Buffer =
+Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
+if (!Buffer)
+  Buffer = llvm::MemoryBufferRef("<<>>", "");
 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
  SLocBufferBlobAbbrv);
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -118,18 +118,25 @@
   return InvalidBOM;
 }
 
-const llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag,
-  FileManager &FM,
-  SourceLocation Loc,
-  bool *Invalid) const {
+llvm::Optional
+ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, FileManager &FM,
+  SourceLocation Loc) const {
+  if (auto *B = getBufferPointer(Diag, FM, Loc))
+return B->getMemBufferRef();
+  return None;
+}
+
+const llvm::MemoryBuffer *
+ContentCache::getBufferPointer(DiagnosticsEngine &Diag, FileManager &FM,
+   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
-  if (Buffer.getPointer() || !ContentsEntry) {
-if (Invalid)
-  *Invalid = isBufferInvalid();
-
-return Buffer.getPointer();
-  }
+  if (isBufferInvalid())
+return nullptr;
+  if (auto *B = Buffer.getPointer())
+return B;
+  if (!ContentsEntry)
+return nullptr;
 
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
@@ -138,13 +145,6 @@
   // miserably on large source files.
   if ((uint64_t)ContentsEntry->getSize() >=
   std::numeric_limits::max()) {
-// We can't make a memory buffer of the required size, so just make a small
-// one. We should never hit a situation where we've already parsed to a
-// later offset of the file, so it shouldn't matter that the buffer is
-// smaller than the file.
-Buffer.setPointer(
-llvm::MemoryBuffer::getMemBuffer("", ContentsEntry->getName())
-.release());
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_file_too_large,
 ContentsEntry->getName());
@@ -153,8 +153,7 @@
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-if (Invalid) *Invalid = true;
-return Buffer.getPointer();
+return nullptr;
   }
 
   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
@@ -164,20 +163,7 @@
   // exists. Most likely, we were using a stat cache with an invalid entry but
   // the file could also have been removed during processing. Since we can't
   // really deal with this situation, just create an empty buffer.
-  //
-  // FIXME: This is definitely not ideal, but our immediate clients can't
-  // currently handle returning a null

[PATCH] D89143: [OpenCL][Docs] Improved description of the supported language functionality.

2020-10-14 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov accepted this revision.
azabaznov added a comment.
This revision is now accepted and ready to land.

Looks good to me, thanks for the note.


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

https://reviews.llvm.org/D89143

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


[PATCH] D89394: clang/Basic: Stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Update `Basic` to stop relying on a `MemoryBuffer*`, using the
`MemoryBufferRef` from `getBufferOrNone` or `getBufferOrFake` instead of
`getBuffer`.


https://reviews.llvm.org/D89394

Files:
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Basic/SourceLocation.cpp
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -1228,12 +1228,11 @@
 /// this is significantly cheaper to compute than the line number.
 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
 bool *Invalid) const {
-  bool MyInvalid = false;
-  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
+  llvm::Optional MemBuf = getBufferOrNone(FID);
   if (Invalid)
-*Invalid = MyInvalid;
+*Invalid = !MemBuf;
 
-  if (MyInvalid)
+  if (!MemBuf)
 return 1;
 
   // It is okay to request a position just past the end of the buffer.
@@ -1509,7 +1508,10 @@
bool *Invalid) const {
   if (isInvalid(Loc, Invalid)) return "";
 
-  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
+  auto B = getBufferOrNone(getFileID(Loc));
+  if (Invalid)
+*Invalid = !B;
+  return B ? B->getBufferIdentifier() : "";
 }
 
 /// getPresumedLoc - This method returns the "presumed" location of a
@@ -2047,8 +2049,8 @@
   // If we arrived here, the location is either in a built-ins buffer or
   // associated with global inline asm. PR5662 and PR22576 are examples.
 
-  StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
-  StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
+  StringRef LB = getBufferOrFake(LOffs.first)->getBufferIdentifier();
+  StringRef RB = getBufferOrFake(ROffs.first)->getBufferIdentifier();
   bool LIsBuiltins = LB == "";
   bool RIsBuiltins = RB == "";
   // Sort built-in before non-built-in.
Index: clang/lib/Basic/SourceLocation.cpp
===
--- clang/lib/Basic/SourceLocation.cpp
+++ clang/lib/Basic/SourceLocation.cpp
@@ -245,7 +245,7 @@
 
 StringRef FullSourceLoc::getBufferData(bool *Invalid) const {
   assert(isValid());
-  return SrcMgr->getBuffer(SrcMgr->getFileID(*this), Invalid)->getBuffer();
+  return SrcMgr->getBufferData(SrcMgr->getFileID(*this), Invalid);
 }
 
 std::pair FullSourceLoc::getDecomposedLoc() const {
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -265,7 +265,9 @@
   PrintedOuterHeading = true;
 
   llvm::errs() << "File " << &File << " : " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
+   << ">: "
+   << SrcMgr.getBufferOrFake(ID)->getBufferIdentifier();
+
   if (F.second.Parent) {
 std::pair Decomp =
 SrcMgr.getDecomposedIncludedLoc(ID);


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -1228,12 +1228,11 @@
 /// this is significantly cheaper to compute than the line number.
 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
 bool *Invalid) const {
-  bool MyInvalid = false;
-  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
+  llvm::Optional MemBuf = getBufferOrNone(FID);
   if (Invalid)
-*Invalid = MyInvalid;
+*Invalid = !MemBuf;
 
-  if (MyInvalid)
+  if (!MemBuf)
 return 1;
 
   // It is okay to request a position just past the end of the buffer.
@@ -1509,7 +1508,10 @@
bool *Invalid) const {
   if (isInvalid(Loc, Invalid)) return "";
 
-  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
+  auto B = getBufferOrNone(getFileID(Loc));
+  if (Invalid)
+*Invalid = !B;
+  return B ? B->getBufferIdentifier() : "";
 }
 
 /// getPresumedLoc - This method returns the "presumed" location of a
@@ -2047,8 +2049,8 @@
   // If we arrived here, the location is either in a built-ins buffer or
   // associated with global inline asm. PR5662 and PR22576 are examples.
 
-  StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
-  StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
+  StringRef LB = getBufferOrFake(LOffs.first)->getBufferIdentifier();
+  StringRef RB = getBufferOrFake(ROffs.first)->getBufferIdentifier();
   bool LIsBuiltins = LB == "";
   bool RIsBuiltins = RB == "";
   // Sort built-in before non-built-in.
Index: clang/lib/Basic/SourceLocation.cpp
==

[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov requested changes to this revision.
azabaznov added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:74
 OPENCLEXT_INTERNAL(cl_khr_mipmap_image_writes, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_srgb_image_writes, 200, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_subgroups, 200, ~0U)

cl_khr_srgb_image_writes - Extension allowing writes to sRGB images from a 
kernel. This extension enables write_imagef built-in function as it described 
[[ 
https://www.khronos.org/registry/OpenCL/specs/2.2/html/OpenCL_Ext.html#cl_khr_srgb_image_writes
 | here]]. So I think we shouldn't remove it. Do I miss something?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89394: clang/Basic: Stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 298152.

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

https://reviews.llvm.org/D89394

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


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -1228,12 +1228,11 @@
 /// this is significantly cheaper to compute than the line number.
 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
 bool *Invalid) const {
-  bool MyInvalid = false;
-  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
+  llvm::Optional MemBuf = getBufferOrNone(FID);
   if (Invalid)
-*Invalid = MyInvalid;
+*Invalid = !MemBuf;
 
-  if (MyInvalid)
+  if (!MemBuf)
 return 1;
 
   // It is okay to request a position just past the end of the buffer.
@@ -1509,7 +1508,10 @@
bool *Invalid) const {
   if (isInvalid(Loc, Invalid)) return "";
 
-  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
+  auto B = getBufferOrNone(getFileID(Loc));
+  if (Invalid)
+*Invalid = !B;
+  return B ? B->getBufferIdentifier() : "";
 }
 
 /// getPresumedLoc - This method returns the "presumed" location of a
@@ -2047,8 +2049,8 @@
   // If we arrived here, the location is either in a built-ins buffer or
   // associated with global inline asm. PR5662 and PR22576 are examples.
 
-  StringRef LB = getBuffer(LOffs.first)->getBufferIdentifier();
-  StringRef RB = getBuffer(ROffs.first)->getBufferIdentifier();
+  StringRef LB = getBufferOrFake(LOffs.first).getBufferIdentifier();
+  StringRef RB = getBufferOrFake(ROffs.first).getBufferIdentifier();
   bool LIsBuiltins = LB == "";
   bool RIsBuiltins = RB == "";
   // Sort built-in before non-built-in.
Index: clang/lib/Basic/SourceLocation.cpp
===
--- clang/lib/Basic/SourceLocation.cpp
+++ clang/lib/Basic/SourceLocation.cpp
@@ -245,7 +245,7 @@
 
 StringRef FullSourceLoc::getBufferData(bool *Invalid) const {
   assert(isValid());
-  return SrcMgr->getBuffer(SrcMgr->getFileID(*this), Invalid)->getBuffer();
+  return SrcMgr->getBufferData(SrcMgr->getFileID(*this), Invalid);
 }
 
 std::pair FullSourceLoc::getDecomposedLoc() const {
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -265,7 +265,8 @@
   PrintedOuterHeading = true;
 
   llvm::errs() << "File " << &File << " : " << SrcMgr.getBuffer(ID)->getBufferIdentifier();
+   << ">: " << 
SrcMgr.getBufferOrFake(ID).getBufferIdentifier();
+
   if (F.second.Parent) {
 std::pair Decomp =
 SrcMgr.getDecomposedIncludedLoc(ID);
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -981,6 +981,17 @@
 Diag, getFileManager(), Loc);
   }
 
+  /// Return the buffer for the specified FileID.
+  ///
+  /// If there is an error opening this buffer the first time, this
+  /// manufactures a temporary buffer and returns it.
+  llvm::MemoryBufferRef
+  getBufferOrFake(FileID FID, SourceLocation Loc = SourceLocation()) const {
+if (auto B = getBufferOrNone(FID, Loc))
+  return *B;
+return getFakeBufferForRecovery()->getMemBufferRef();
+  }
+
   /// Return the buffer for the specified FileID.
   ///
   /// If there is an error opening this buffer the first time, this


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -1228,12 +1228,11 @@
 /// this is significantly cheaper to compute than the line number.
 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
 bool *Invalid) const {
-  bool MyInvalid = false;
-  const llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid);
+  llvm::Optional MemBuf = getBufferOrNone(FID);
   if (Invalid)
-*Invalid = MyInvalid;
+*Invalid = !MemBuf;
 
-  if (MyInvalid)
+  if (!MemBuf)
 return 1;
 
   // It is okay to request a position just past the end of the buffer.
@@ -1509,7 +1508,10 @@
bool *Invalid) const {
   if (isInvalid(Loc, Invalid)) return "";
 
-  return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier();
+  auto B = getBufferOrNone(getFileID(Loc));
+  if (Invalid)
+*Invalid = !B;
+  return B ? B->getBufferIdentifier() : "";
 }
 
 /// getPresumedLoc - This method returns the "presumed" location of a
@@ -20

[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

With this change, clang basically will have no knowledge about the removed 
extensions, i.e., it will not know which extension is supported in which 
version of OpenCL and have no way to enable/disable those extensions. There 
will be no way to define corresponding macros in clang.

Basically the responsibility of defining those macros will be shifted to OpenCL 
runtime for JIT and shifted to users for offline compilation. They need to have 
knowledge about which extensions are supported in which version of OpenCL and 
which cpu/platform supports them. I am not sure whether this is the direction 
we want to move to.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D88106: [SyntaxTree] Provide iterator-like functions for Lists

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 298156.
eduucaldas marked an inline comment as done.
eduucaldas added a comment.

- Make `ElementAndDelimiterIterator` templated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88106

Files:
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -9,6 +9,7 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Tooling/Syntax/Nodes.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Casting.h"
 #include 
@@ -311,91 +312,112 @@
   }
 }
 
-std::vector>
-syntax::List::getElementsAsNodesAndDelimiters() {
-  if (!getFirstChild())
-return {};
-
-  std::vector> Children;
-  syntax::Node *ElementWithoutDelimiter = nullptr;
-  for (auto *C = getFirstChild(); C; C = C->getNextSibling()) {
-switch (C->getRole()) {
-case syntax::NodeRole::ListElement: {
-  if (ElementWithoutDelimiter) {
-Children.push_back({ElementWithoutDelimiter, nullptr});
-  }
-  ElementWithoutDelimiter = C;
-  break;
-}
-case syntax::NodeRole::ListDelimiter: {
-  Children.push_back({ElementWithoutDelimiter, cast(C)});
-  ElementWithoutDelimiter = nullptr;
-  break;
-}
-default:
-  llvm_unreachable(
-  "A list can have only elements and delimiters as children.");
-}
+syntax::List::ElementAndDelimiter
+syntax::List::getWithDelimiter(syntax::Node *Element) {
+  assert(Element && Element->getRole() == syntax::NodeRole::ListElement);
+  auto *Next = Element->getNextSibling();
+  if (!Next)
+return {Element, nullptr};
+  switch (Next->getRole()) {
+  case syntax::NodeRole::ListElement:
+return {Element, nullptr};
+  case syntax::NodeRole::ListDelimiter:
+return {Element, cast(Next)};
+  default:
+llvm_unreachable(
+"A list can have only elements and delimiters as children.");
   }
+}
 
-  switch (getTerminationKind()) {
-  case syntax::List::TerminationKind::Separated: {
-Children.push_back({ElementWithoutDelimiter, nullptr});
-break;
-  }
-  case syntax::List::TerminationKind::Terminated:
-  case syntax::List::TerminationKind::MaybeTerminated: {
-if (ElementWithoutDelimiter) {
-  Children.push_back({ElementWithoutDelimiter, nullptr});
+llvm::Optional>
+syntax::List::getElementAndDelimiterAfterDelimiter(syntax::Leaf *Delimiter) {
+  assert(Delimiter && Delimiter->getRole() == syntax::NodeRole::ListDelimiter);
+  auto *List = cast(Delimiter->getParent());
+  auto *Next = Delimiter->getNextSibling();
+  if (!Next) {
+switch (List->getTerminationKind()) {
+// List is separated and ends with delimiter
+// => missing last ElementAndDelimiter.
+case syntax::List::TerminationKind::Separated:
+  return llvm::Optional>(
+  {nullptr, nullptr});
+case syntax::List::TerminationKind::Terminated:
+case syntax::List::TerminationKind::MaybeTerminated:
+  return None;
 }
-break;
   }
+  switch (Next->getRole()) {
+  case syntax::NodeRole::ListElement:
+return getWithDelimiter(Next);
+
+  // Consecutive Delimiters => missing Element
+  case syntax::NodeRole::ListDelimiter:
+return llvm::Optional>(
+{nullptr, cast(Next)});
+  default:
+llvm_unreachable(
+"A list can have only elements and delimiters as children.");
   }
-
-  return Children;
 }
 
-// Almost the same implementation of `getElementsAsNodesAndDelimiters` but
-// ignoring delimiters
-std::vector syntax::List::getElementsAsNodes() {
-  if (!getFirstChild())
-return {};
+llvm::Optional>
+syntax::List::getElementAndDelimiterAfterElement(syntax::Node *Element) {
+  assert(Element && Element->getRole() == syntax::NodeRole::ListElement);
+  auto *Next = Element->getNextSibling();
+  if (!Next)
+// This was the last element of the list.
+return None;
+
+  switch (Next->getRole()) {
+  case syntax::NodeRole::ListElement:
+// We have something of the form "a b ..." => 'b' starts the next
+// `ElementAndDelimiter`.
+return getWithDelimiter(Next);
+
+  case syntax::NodeRole::ListDelimiter:
+// We have something of the form "a , ..." => whatever comes after the comma
+// starts the next `ElementAndDelimiter`.
+return getElementAndDelimiterAfterDelimiter(cast(Next));
 
-  std::vector Children;
-  syntax::Node *ElementWithoutDelimiter = nullptr;
-  for (auto *C = getFirstChild(); C; C = C->getNextSibling()) {
-switch (C->getRole()) {
-case syntax::NodeRole::ListElement: {
-  if (ElementWithoutDelimiter) {
-Children.push_back(ElementWithoutDelimiter);
-  }
-  ElementWithoutDelimiter = C;
-  break;
-}
-case syntax::N

[PATCH] D88106: [SyntaxTree] Provide iterator-like functions for Lists

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added a comment.

Haven't yet implemented `BeforeBegin`, waiting for a heads up on the patch as 
is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88106

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


[PATCH] D88106: [SyntaxTree] Provide iterator-like functions for Lists

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tree.h:269
+  return EDI == Other.EDI;
+}
+

gribozavr2 wrote:
> Please also define `operator!=`.
this is defined by the `iterato_facade_base`, take a look at the comments in 
this class template



Comment at: clang/lib/Tooling/Syntax/Tree.cpp:405
 
   return Children;
 }

gribozavr2 wrote:
> Ditto?
Here we could do `std::transform(getBegin(), getEnd(), 
std::back_inserter(result), [](ElementAndDelimiter ED){return ED.element;})`. 
Is that more idiomatic?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88106

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


[PATCH] D88106: [SyntaxTree] Provide iterator-like functions for Lists

2020-10-14 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Tree.h:241-242
   /// "a; b; c"  <=> [("a" , ";"), ("b" , ";" ), ("c" , null)]
+  template 
+  class ElementAndDelimiterIterator
+  : public llvm::iterator_facade_base<

Since we're gonna provide strongly-typed iterators, I make the Iterator a class 
template.

I keep the base functions as they were, `getElementAndDelimiterAfter...`, but I 
cast their result using `castToElementType`.

Another option would be to make the base functions also templated and not 
perform any casting.

We'll use `castToElementType` to provide the strongly-typed iterators as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88106

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


[PATCH] D89398: Lexer: Update the Lexer to use MemoryBufferRef, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added subscribers: usaxena95, ributzka, kadircet.
dexonsmith requested review of this revision.

Update `Lexer` / `Lexer::Lexer` to use `MemoryBufferRef` instead of
`MemoryBuffer*`. Callers that were acquiring a `MemoryBuffer*` via
`SourceManager::getBuffer` were updated, such that if they checked
`Invalid` they use `getBufferOrNone` and otherwise `getBufferOrFake`.


https://reviews.llvm.org/D89398

Files:
  clang-tools-extra/clangd/Format.cpp
  clang/include/clang/Lex/Lexer.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Frontend/Rewrite/InclusionRewriter.cpp
  clang/lib/Frontend/Rewrite/RewriteMacros.cpp
  clang/lib/Frontend/VerifyDiagnosticConsumer.cpp
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/PPLexerChange.cpp
  clang/lib/Rewrite/HTMLRewrite.cpp
  clang/lib/Rewrite/TokenRewriter.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp

Index: clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
+++ clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
@@ -43,7 +43,7 @@
 GetOffsetAfterSequence) {
   SourceManagerForFile VirtualSM(FileName, Code);
   SourceManager &SM = VirtualSM.get();
-  Lexer Lex(SM.getMainFileID(), SM.getBuffer(SM.getMainFileID()), SM,
+  Lexer Lex(SM.getMainFileID(), SM.getBufferOrFake(SM.getMainFileID()), SM,
 createLangOpts());
   Token Tok;
   // Get the first token.
Index: clang/lib/Rewrite/TokenRewriter.cpp
===
--- clang/lib/Rewrite/TokenRewriter.cpp
+++ clang/lib/Rewrite/TokenRewriter.cpp
@@ -28,7 +28,7 @@
   ScratchBuf.reset(new ScratchBuffer(SM));
 
   // Create a lexer to lex all the tokens of the main file in raw mode.
-  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
+  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
   Lexer RawLex(FID, FromFile, SM, LangOpts);
 
   // Return all comments and whitespace as tokens.
Index: clang/lib/Rewrite/HTMLRewrite.cpp
===
--- clang/lib/Rewrite/HTMLRewrite.cpp
+++ clang/lib/Rewrite/HTMLRewrite.cpp
@@ -445,7 +445,7 @@
   RewriteBuffer &RB = R.getEditBuffer(FID);
 
   const SourceManager &SM = PP.getSourceManager();
-  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
+  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
   Lexer L(FID, FromFile, SM, PP.getLangOpts());
   const char *BufferStart = L.getBuffer().data();
 
@@ -536,7 +536,7 @@
   const SourceManager &SM = PP.getSourceManager();
   std::vector TokenStream;
 
-  const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
+  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
   Lexer L(FID, FromFile, SM, PP.getLangOpts());
 
   // Lex all the tokens in raw mode, to avoid entering #includes or expanding
Index: clang/lib/Lex/PPLexerChange.cpp
===
--- clang/lib/Lex/PPLexerChange.cpp
+++ clang/lib/Lex/PPLexerChange.cpp
@@ -11,16 +11,16 @@
 //
 //===--===//
 
-#include "clang/Lex/Preprocessor.h"
-#include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/MacroInfo.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/FileSystem.h"
-#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/MemoryBufferRef.h"
 #include "llvm/Support/Path.h"
 using namespace clang;
 
@@ -73,10 +73,9 @@
 MaxIncludeStackDepth = IncludeMacroStack.size();
 
   // Get the MemoryBuffer for this FID, if it fails, we fail.
-  bool Invalid = false;
-  const llvm::MemoryBuffer *InputFile =
-getSourceManager().getBuffer(FID, Loc, &Invalid);
-  if (Invalid) {
+  llvm::Optional InputFile =
+  getSourceManager().getBufferOrNone(FID, Loc);
+  if (!InputFile) {
 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
 Diag(Loc, diag::err_pp_error_opening_file)
 << std::string(SourceMgr.getBufferName(FileStart)) << "";
@@ -90,7 +89,7 @@
 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
   }
 
-  EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
+  EnterSourceFileWithLexer(new Lexer(FID, *InputFile, *this), CurDir);
   return false;
 }
 
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -13,7 +13,9 @@
 #include "clang/Lex/Lexer.h"
 #include "UnicodeCharSets.h"
 #include "clang/Basic/CharInfo.h"
+#include "clang/Ba

[PATCH] D88737: [AIX] Turn -fdata-sections on by default in Clang

2020-10-14 Thread Jason Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf85bcc21ddad: [AIX] Turn -fdata-sections on by default in 
Clang (authored by jasonliu).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D88737?vs=296965&id=298160#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88737

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/aix-data-sections.c
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
  lld/Common/TargetOptionsCommandFlags.cpp
  llvm/include/llvm/ADT/Triple.h
  llvm/include/llvm/CodeGen/CommandFlags.h
  llvm/lib/CodeGen/CommandFlags.cpp
  llvm/test/CodeGen/PowerPC/aix-alias.ll
  llvm/test/CodeGen/PowerPC/aix-bytestring.ll
  llvm/test/CodeGen/PowerPC/aix-extern-weak.ll
  llvm/test/CodeGen/PowerPC/aix-extern.ll
  llvm/test/CodeGen/PowerPC/aix-ignore-xcoff-visibility.ll
  llvm/test/CodeGen/PowerPC/aix-overflow-toc.py
  llvm/test/CodeGen/PowerPC/aix-readonly-with-relocation.ll
  llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll
  llvm/test/CodeGen/PowerPC/aix-return55.ll
  llvm/test/CodeGen/PowerPC/aix-weak.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-data-sections.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-data.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-lower-comm.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-mergeable-const.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-mergeable-str.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-reloc.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-rodata.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-symbol-rename.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-used.ll
  llvm/test/CodeGen/PowerPC/aix-xcoff-visibility.ll
  llvm/tools/gold/gold-plugin.cpp
  llvm/tools/llc/llc.cpp
  llvm/tools/lli/lli.cpp
  llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
  llvm/tools/llvm-lto/llvm-lto.cpp
  llvm/tools/llvm-lto2/llvm-lto2.cpp
  llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
  llvm/tools/lto/lto.cpp
  llvm/tools/opt/opt.cpp

Index: llvm/tools/opt/opt.cpp
===
--- llvm/tools/opt/opt.cpp
+++ llvm/tools/opt/opt.cpp
@@ -698,7 +698,8 @@
   Triple ModuleTriple(M->getTargetTriple());
   std::string CPUStr, FeaturesStr;
   TargetMachine *Machine = nullptr;
-  const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  const TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
 
   if (ModuleTriple.getArch()) {
 CPUStr = codegen::getCPUStr();
Index: llvm/tools/lto/lto.cpp
===
--- llvm/tools/lto/lto.cpp
+++ llvm/tools/lto/lto.cpp
@@ -218,7 +218,8 @@
 
 lto_module_t lto_module_create(const char* path) {
   lto_initialize();
-  llvm::TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  llvm::TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(Triple());
   ErrorOr> M =
   LTOModule::createFromFile(*LTOContext, StringRef(path), Options);
   if (!M)
@@ -228,7 +229,8 @@
 
 lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) {
   lto_initialize();
-  llvm::TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  llvm::TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(Triple());
   ErrorOr> M = LTOModule::createFromOpenFile(
   *LTOContext, fd, StringRef(path), size, Options);
   if (!M)
@@ -241,7 +243,8 @@
  size_t map_size,
  off_t offset) {
   lto_initialize();
-  llvm::TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  llvm::TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(Triple());
   ErrorOr> M = LTOModule::createFromOpenFileSlice(
   *LTOContext, fd, StringRef(path), map_size, offset, Options);
   if (!M)
@@ -251,7 +254,8 @@
 
 lto_module_t lto_module_create_from_memory(const void* mem, size_t length) {
   lto_initialize();
-  llvm::TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  llvm::TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(Triple());
   ErrorOr> M =
   LTOModule::createFromBuffer(*LTOContext, mem, length, Options);
   if (!M)
@@ -263,7 +267,8 @@
  size_t length,
  const char *path) {
   lto_initialize();
-  llvm::TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  llvm::TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(Triple());
   ErrorOr> M = LTOModule::createFromBuffer(
   *LTOContext, mem, length, Options, StringRef(path));
   if (!M)
@@ -274,7 +279,8 @@
 lto_module_t lto_module_create_in_local_context(const void *mem, size_t length,
  

[clang] f85bcc2 - [AIX] Turn -fdata-sections on by default in Clang

2020-10-14 Thread via cfe-commits

Author: jasonliu
Date: 2020-10-14T15:58:31Z
New Revision: f85bcc21ddadd07f38e1db7aa286ff985bd0eb10

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

LOG: [AIX] Turn -fdata-sections on by default in Clang

Summary:

This patch does the following:
1. Make InitTargetOptionsFromCodeGenFlags() accepts Triple as a
 parameter, because some options' default value is triple dependant.
2. DataSections is turned on by default on AIX for llc.
3. Test cases change accordingly because of the default behaviour change.
4. Clang Driver passes in -fdata-sections by default on AIX.

Reviewed By: MaskRay, DiggerLin

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

Added: 
clang/test/Driver/aix-data-sections.c

Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
lld/Common/TargetOptionsCommandFlags.cpp
llvm/include/llvm/ADT/Triple.h
llvm/include/llvm/CodeGen/CommandFlags.h
llvm/lib/CodeGen/CommandFlags.cpp
llvm/test/CodeGen/PowerPC/aix-alias.ll
llvm/test/CodeGen/PowerPC/aix-bytestring.ll
llvm/test/CodeGen/PowerPC/aix-extern-weak.ll
llvm/test/CodeGen/PowerPC/aix-extern.ll
llvm/test/CodeGen/PowerPC/aix-ignore-xcoff-visibility.ll
llvm/test/CodeGen/PowerPC/aix-overflow-toc.py
llvm/test/CodeGen/PowerPC/aix-readonly-with-relocation.ll
llvm/test/CodeGen/PowerPC/aix-reference-func-addr-const.ll
llvm/test/CodeGen/PowerPC/aix-return55.ll
llvm/test/CodeGen/PowerPC/aix-weak.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-data-sections.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-data.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-lower-comm.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-mergeable-const.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-mergeable-str.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-reloc.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-rodata.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-symbol-rename.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-used.ll
llvm/test/CodeGen/PowerPC/aix-xcoff-visibility.ll
llvm/tools/gold/gold-plugin.cpp
llvm/tools/llc/llc.cpp
llvm/tools/lli/lli.cpp
llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
llvm/tools/llvm-lto/llvm-lto.cpp
llvm/tools/llvm-lto2/llvm-lto2.cpp
llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
llvm/tools/lto/lto.cpp
llvm/tools/opt/opt.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 34a36932c383..d16de8928ec1 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4910,8 +4910,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 }
   }
 
+  bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
-   UseSeparateSections)) {
+   UseSeparateSections || HasDefaultDataSections)) {
 CmdArgs.push_back("-fdata-sections");
   }
 

diff  --git a/clang/test/Driver/aix-data-sections.c 
b/clang/test/Driver/aix-data-sections.c
new file mode 100644
index ..9fa021cc48ee
--- /dev/null
+++ b/clang/test/Driver/aix-data-sections.c
@@ -0,0 +1,7 @@
+// Verify -fdata-sections is the default for AIX
+
+// RUN: %clang -### -target powerpc-ibm-aix7.1.0.0 %s -c -o %t.o 2>&1 \
+// RUN:   | FileCheck %s
+// RUN: %clang -### -target powerpc64-ibm-aix7.1.0.0 %s -c -o %t.o 2>&1 \
+// RUN:   | FileCheck %s
+// CHECK: "-fdata-sections"

diff  --git a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp 
b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
index aefb761cd70c..d57515b1ac13 100644
--- a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -102,7 +102,8 @@ static std::string OptLLVM(const std::string &IR, 
CodeGenOpt::Level OLvl) {
 ErrorAndExit("Could not parse IR");
 
   Triple ModuleTriple(M->getTargetTriple());
-  const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
+  const TargetOptions Options =
+  codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
   std::string E;
   const Target *TheTarget =
   TargetRegistry::lookupTarget(codegen::getMArch(), ModuleTriple, E);
@@ -165,7 +166,10 @@ static void CreateAndRunJITFunc(const std::string &IR, 
CodeGenOpt::Level OLvl) {
   builder.setEngineKind(EngineKind::JIT);
   builder.setMCJITMemoryManager(std::make_unique());
   builder.setOptLevel(OLvl);
-  builder.setTargetOptions(codegen::InitTargetOptionsFromCodeGenFlags());
+
+  Triple ModuleTriple(M->getTargetTriple());
+  builder.setTargetOptions(
+  codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple));
 
   std::unique_ptr EE(builder.create());
   if (!EE)

diff  --g

[PATCH] D89277: [clangd] Add $/dumpMemoryTree LSP extension

2020-10-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

In D89277#2329947 , @sammccall wrote:

> (sorry out today and haven't looked at code yet)

no worries it is a prototype, I wouldn't spend time looking at the 
implementation until we agree on the interaction :D
OTHO, checking out the lit test for output would probably be useful.

> If it's a custom method, I think it should return the data as a json 
> structure - the client already has to have custom support to invoke it, 
> displaying the result isn't much extra work.

SGTM. WDYT about a json object in the form of:

  interface MemoryTreeNode {
name: string;
totalSize: int;
children?: Node[];
  };



> And I would really love to add a tree view to vscode, I think it wouldn't be 
> hard (vs call hierarchy: no laziness and no direction-flipping) and could be 
> reused for an AST viewer.

right, vscode already has APIs for it, 
https://code.visualstudio.com/api/extension-guides/tree-view.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89277

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


[PATCH] D86119: [OPENMP50]Allow overlapping mapping in target constrcuts.

2020-10-14 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

Thanks for working on this.  Sorry to take so long to review.  Before I try to 
digest the code, I have a few high-level questions.

Based on the test suite changes, `TARGET_PARAM` is disappearing from many 
cases.  Can you explain a bit how that supports overlapping and reordering?

Have you considered issue 2337 for the OpenMP spec and how your implementation 
handles the ambiguous cases cited there?




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:7283
+llvm::find(MotionModifiers, OMPC_MOTION_MODIFIER_present) !=
+MotionModifiers.end())
   Bits |= OMP_MAP_PRESENT;

Unrelated change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86119

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


[clang-tools-extra] fc2fb60 - [clangd] clang-format TweakTests, NFC

2020-10-14 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2020-10-14T18:14:27+02:00
New Revision: fc2fb60bab75955cea341907b252cc1c760481a8

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

LOG: [clangd] clang-format TweakTests, NFC

Added: 


Modified: 
clang-tools-extra/clangd/unittests/TweakTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp 
b/clang-tools-extra/clangd/unittests/TweakTests.cpp
index 718b84d03990..8488c423dcdd 100644
--- a/clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -305,138 +305,137 @@ TEST_F(ExtractVariableTest, Test) {
   EXPECT_UNAVAILABLE(UnavailableCases);
 
   // vector of pairs of input and output strings
-  const std::vector>
-  InputOutputs = {
-  // extraction from variable declaration/assignment
-  {R"cpp(void varDecl() {
+  const std::vector> InputOutputs = {
+  // extraction from variable declaration/assignment
+  {R"cpp(void varDecl() {
int a = 5 * (4 + (3 [[- 1)]]);
  })cpp",
-   R"cpp(void varDecl() {
+   R"cpp(void varDecl() {
auto dummy = (3 - 1); int a = 5 * (4 + dummy);
  })cpp"},
-  // FIXME: extraction from switch case
-  /*{R"cpp(void f(int a) {
-   if(1)
- while(a < 1)
-   switch (1) {
-   case 1:
- a = [[1 + 2]];
- break;
-   default:
- break;
-   }
- })cpp",
-   R"cpp(void f(int a) {
-   auto dummy = 1 + 2; if(1)
- while(a < 1)
-   switch (1) {
-   case 1:
- a = dummy;
- break;
-   default:
- break;
-   }
- })cpp"},*/
-  // Macros
-  {R"cpp(#define PLUS(x) x++
+  // FIXME: extraction from switch case
+  /*{R"cpp(void f(int a) {
+   if(1)
+ while(a < 1)
+   switch (1) {
+   case 1:
+ a = [[1 + 2]];
+ break;
+   default:
+ break;
+   }
+ })cpp",
+   R"cpp(void f(int a) {
+   auto dummy = 1 + 2; if(1)
+ while(a < 1)
+   switch (1) {
+   case 1:
+ a = dummy;
+ break;
+   default:
+ break;
+   }
+ })cpp"},*/
+  // Macros
+  {R"cpp(#define PLUS(x) x++
  void f(int a) {
int y = PLUS([[1+a]]);
  })cpp",
-   /*FIXME: It should be extracted like this.
-R"cpp(#define PLUS(x) x++
-  void f(int a) {
-auto dummy = 1+a; int y = PLUS(dummy);
-  })cpp"},*/
-   R"cpp(#define PLUS(x) x++
+   /*FIXME: It should be extracted like this.
+R"cpp(#define PLUS(x) x++
+  void f(int a) {
+auto dummy = 1+a; int y = PLUS(dummy);
+  })cpp"},*/
+   R"cpp(#define PLUS(x) x++
  void f(int a) {
auto dummy = PLUS(1+a); int y = dummy;
  })cpp"},
-  // ensure InsertionPoint isn't inside a macro
-  {R"cpp(#define LOOP(x) while (1) {a = x;}
+  // ensure InsertionPoint isn't inside a macro
+  {R"cpp(#define LOOP(x) while (1) {a = x;}
  void f(int a) {
if(1)
 LOOP(5 + [[3]])
  })cpp",
-R"cpp(#define LOOP(x) while (1) {a = x;}
+   R"cpp(#define LOOP(x) while (1) {a = x;}
  void f(int a) {
auto dummy = 3; if(1)
 LOOP(5 + dummy)
  })cpp"},
-  {R"cpp(#define LOOP(x) do {x;} while(1);
+  {R"cpp(#define LOOP(x) do {x;} while(1);
  void f(int a) {
if(1)
 LOOP(5 + [[3]])
  })cpp",
-   R"cpp(#define LOOP(x) do {x;} while(1);
+   R"cpp(#define LOOP(x) do {x;} while(1);
  void f(int a) {
auto dummy = 3; if(1)
 LOOP(5 + dummy)
  })cpp"},
-  // attribute testing
-  {R"cpp(void f(int a) {
+  // attribute testing
+  {R"cpp(void f(int a) {
 

[PATCH] D86119: [OPENMP50]Allow overlapping mapping in target constrcuts.

2020-10-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D86119#2330310 , @jdenny wrote:

> Thanks for working on this.  Sorry to take so long to review.  Before I try 
> to digest the code, I have a few high-level questions.
>
> Based on the test suite changes, `TARGET_PARAM` is disappearing from many 
> cases.  Can you explain a bit how that supports overlapping and reordering?

`TARGET_PARAM` is used only for marking the data that should be passed to the 
kernel function as an argument. We just generate it in many cases but the 
runtime actually does not use them. Thу patch relies on this thing, otherwise, 
we may pass an incorrect number of arguments to the kernel functions.

> Have you considered issue 2337 for the OpenMP spec and how your 
> implementation handles the ambiguous cases cited there?

Can you provide the details about this issue?




Comment at: clang/lib/CodeGen/CGOpenMPRuntime.cpp:7283
+llvm::find(MotionModifiers, OMPC_MOTION_MODIFIER_present) !=
+MotionModifiers.end())
   Bits |= OMP_MAP_PRESENT;

jdenny wrote:
> Unrelated change?
Well, in general, yes, I just tried to simplify the code, can commit it as a 
separate NFC.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86119

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D89372#2330217 , @yaxunl wrote:

> With this change, clang basically will have no knowledge about the removed 
> extensions, i.e., it will not know which extension is supported in which 
> version of OpenCL and have no way to enable/disable those extensions. There 
> will be no way to define corresponding macros in clang.
>
> Basically the responsibility of defining those macros will be shifted to 
> OpenCL runtime for JIT and shifted to users for offline compilation. They 
> need to have knowledge about which extensions are supported in which version 
> of OpenCL and which cpu/platform supports them. I am not sure whether this is 
> the direction we want to move to.

But why do you think anyone would need to use those macros in OpenCL C?

Let's take `cl_khr_icd` as an exmaple: 
https://www.khronos.org/registry/OpenCL//sdk/2.2/docs/man/html/cl_khr_icd.html

`cl_khr_icd - Extension through which the Khronos OpenCL installable client 
driver loader (ICD Loader) may expose multiple separate vendor installable 
client drivers (Vendor ICDs) for OpenCL.`

Why would anyone need any macro while compiling OpenCL C code for this 
functionality. It is dialing with the driver loader that runs on the host 
before compiling anything.

I believe that the addition of such extensions into the kernel language are 
accidental and we should trying to improve this. There is no need to have 
something that isn't needed. We have neough code and complexity to maintain 
that is useful. Let's try to simplify by at lesst removing what is not needed.

On a separate note the extensions that need macro definition and don't require 
the functionality in the clang parsing also doesn't have to be in the clang 
source code. I have mentioned it in my RFC as well: 
http://lists.llvm.org/pipermail/cfe-dev/2020-September/066911.html


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[clang] b967b9a - [CodeGen] Move x86 specific ms intrinsic tests into x86 target subfolder. NFCI.

2020-10-14 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-10-14T17:37:26+01:00
New Revision: b967b9a7116babdf8aafacdcb4aae3a33d57aaa0

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

LOG: [CodeGen] Move x86 specific ms intrinsic tests into x86 target subfolder. 
NFCI.

Added: 
clang/test/CodeGen/X86/ms-x86-intrinsics.c

Modified: 


Removed: 
clang/test/CodeGen/ms-x86-intrinsics.c



diff  --git a/clang/test/CodeGen/ms-x86-intrinsics.c 
b/clang/test/CodeGen/X86/ms-x86-intrinsics.c
similarity index 100%
rename from clang/test/CodeGen/ms-x86-intrinsics.c
rename to clang/test/CodeGen/X86/ms-x86-intrinsics.c



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


[PATCH] D89362: [MS] Apply `inreg` to AArch64 sret parms on instance methods

2020-10-14 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added inline comments.



Comment at: clang/lib/CodeGen/MicrosoftCXXABI.cpp:1108
+  bool isTrivialForABI =
+  RD->canPassInRegisters() && !(isAArch64 && !isCXX14Aggregate(RD));
   bool isIndirectReturn =

efriedma wrote:
> isTrivialForABI is only used if isAArch64 is true, so it shouldn't use 
> isTrivialForABI as part of its computation, I think?
I see. I think we ended up with this tortured condition because I gave review 
feedback that it would be good to avoid checking `isCXX14Aggregate` (formerly 
`hasMicrosoftABIRestritions`) for non-aarch64 targets. I'll take another shot 
at simplifying things.



Comment at: clang/lib/CodeGen/MicrosoftCXXABI.cpp:1110
   bool isIndirectReturn =
-  isAArch64 ? (!RD->canPassInRegisters() ||
-   IsSizeGreaterThan128(RD))
-: !RD->isPOD();
+  isAArch64 ? (!isTrivialForABI || IsSizeGreaterThan128(RD)) : 
!RD->isPOD();
   bool isInstanceMethod = FI.isInstanceMethod();

efriedma wrote:
> I suspect that the IsSizeGreaterThan128() check shouldn't be here.  Can we 
> rely on the C ABI rules for that?
> 
> For non-AArch64, is it really correct to use isPOD()?  That varies based on 
> the language version, no?
I think you are right, we can remove the size check here, it's already part of 
what feeds into `RD->canPassInRegisters`. There is an earlier size check here:
https://github.com/llvm/llvm-project/blob/master/clang/lib/Sema/SemaDeclCXX.cpp#L6441

I agree `isPOD` is vague, but the comments on the implementation do say this:
  /// Note that this is the C++ TR1 definition of POD.
So, I think it doesn't vary in practice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89362

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


[PATCH] D89366: [WebAssembly] v128.load{8, 16, 32, 64}_lane instructions

2020-10-14 Thread Thomas Lively via Phabricator via cfe-commits
tlively added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsWebAssembly.def:180
+TARGET_BUILTIN(__builtin_wasm_load32_lane, "V4iIii*", "nU", "simd128")
+TARGET_BUILTIN(__builtin_wasm_load64_lane, "V2LLiIiLLi*", "nU", "simd128")
+TARGET_BUILTIN(__builtin_wasm_store8_lane, "vV16ScIiSc*", "n", "simd128")

aheejin wrote:
> `U` in the third argument [[ 
> https://github.com/llvm/llvm-project/blob/72732acade77d5ee55a818e2da77a2c5b7033ccb/clang/include/clang/Basic/Builtins.def#L75
>  | means ]] pure. Can we say loads are pure? (The same for existing 
> `__builtin_wasm_load32_zero` and `__builtin_wasm_load64_zero`)
Yes, this is the difference between "pure" and "const." 

https://github.com/llvm/llvm-project/blob/master/clang/include/clang/Basic/Builtins.h#L97-L106


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89366

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


[PATCH] D89366: [WebAssembly] v128.load{8, 16, 32, 64}_lane instructions

2020-10-14 Thread Thomas Lively via Phabricator via cfe-commits
tlively planned changes to this revision.
tlively added inline comments.



Comment at: llvm/test/CodeGen/WebAssembly/simd-load-lane-offset.ll:4
+
+; Test SIMD v128.load{8,16,32,64}_lane instructions. TODO: Use the offset 
field.
+

aheejin wrote:
> Maybe add a comment on which patterns are currently supported and unsupported 
> among this file?
Will do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89366

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


[PATCH] D89402: clang/Lex: Stop using SourceManager::getBuffer

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Update clang/lib/Lex to stop relying on a `MemoryBuffer*`, using the
`MemoryBufferRef` from `getBufferOrNone` since both locations had logic
for checking validity of the buffer. There's potentially a functionality
change, since the logic was wrong (it checked for `nullptr`, which was
never returned by the old API), but if that was reachable the new
behaviour should be better.


https://reviews.llvm.org/D89402

Files:
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Lex/PPDirectives.cpp


Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -379,7 +379,8 @@
 
   std::pair HashFileOffset =
   SourceMgr.getDecomposedLoc(HashLoc);
-  const llvm::MemoryBuffer *Buf = SourceMgr.getBuffer(HashFileOffset.first);
+  Optional Buf =
+  SourceMgr.getBufferOrNone(HashFileOffset.first);
   if (!Buf)
 return None;
   auto It =
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -3004,7 +3004,7 @@
   }
 
   assert(Target && "Missing target information");
-  const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
+  llvm::Optional Buffer = SourceMgr.getBufferOrNone(ID);
   if (!Buffer)
 return ParsedModuleMap[File] = true;
   assert((!Offset || *Offset <= Buffer->getBufferSize()) &&


Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -379,7 +379,8 @@
 
   std::pair HashFileOffset =
   SourceMgr.getDecomposedLoc(HashLoc);
-  const llvm::MemoryBuffer *Buf = SourceMgr.getBuffer(HashFileOffset.first);
+  Optional Buf =
+  SourceMgr.getBufferOrNone(HashFileOffset.first);
   if (!Buf)
 return None;
   auto It =
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -3004,7 +3004,7 @@
   }
 
   assert(Target && "Missing target information");
-  const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
+  llvm::Optional Buffer = SourceMgr.getBufferOrNone(ID);
   if (!Buffer)
 return ParsedModuleMap[File] = true;
   assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89025: [RISCV] Add -mtune support

2020-10-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/riscv-cpus.c:91
+// MTUNE-E31-MCPU-E76: "-target-feature" "+a"
+// MTUNE-E31-MCPU-E76-NOT: "-target-feature" "+f"
+// MTUNE-E31-MCPU-E76: "-target-feature" "+c"

A NOT pattern depends on the feature order and thus a bit unreliable. 
Please use -SAME whenever appropriate


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

https://reviews.llvm.org/D89025

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Marco Antognini via Phabricator via cfe-commits
mantognini added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:74
 OPENCLEXT_INTERNAL(cl_khr_mipmap_image_writes, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_srgb_image_writes, 200, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_subgroups, 200, ~0U)

azabaznov wrote:
> cl_khr_srgb_image_writes - Extension allowing writes to sRGB images from a 
> kernel. This extension enables write_imagef built-in function as it described 
> [[ 
> https://www.khronos.org/registry/OpenCL/specs/2.2/html/OpenCL_Ext.html#cl_khr_srgb_image_writes
>  | here]]. So I think we shouldn't remove it. Do I miss something?
On second reading, this one is slightly ambiguous. On the language side, the 
extension doesn't add an overload; it only specifies that existing overload can 
be used with a different kind of image. On the API side, it does extend the set 
of features. But at the same time if the extended API is not supported, it's 
not possible to create an image in the first place and therefore impossible to 
call write_imagef. So I question the usefulness of such macro on the device 
side. Does this argument convince you it should be removed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89405: [CodeGen][X86] Emit fshl/fshr ir intrinsics for shiftleft128/shiftright128 ms intrinsics

2020-10-14 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon created this revision.
RKSimon added reviewers: craig.topper, spatel, rnk, thakis.
Herald added a subscriber: pengfei.
Herald added a project: clang.
RKSimon requested review of this revision.

Now that funnel shift handling is pretty good, we can use the intrinsics 
directly and avoid a lot of zext/trunc issues.

https://godbolt.org/z/YqhnnM


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89405

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/X86/ms-x86-intrinsics.c


Index: clang/test/CodeGen/X86/ms-x86-intrinsics.c
===
--- clang/test/CodeGen/X86/ms-x86-intrinsics.c
+++ clang/test/CodeGen/X86/ms-x86-intrinsics.c
@@ -144,14 +144,8 @@
   return __shiftleft128(l, h, d);
 }
 // CHECK-X64-LABEL: define dso_local i64 @test__shiftleft128(i64 %l, i64 %h, 
i8 %d)
-// CHECK-X64:  = zext i64 %{{.*}} to i128
-// CHECK-X64: = shl nuw i128 %{{.*}}, 64
-// CHECK-X64: = zext i64 %{{.*}} to i128
-// CHECK-X64: = or i128 %
-// CHECK-X64: = and i8 %{{.*}}, 63
-// CHECK-X64: = shl i128 %
-// CHECK-X64: = lshr i128 %
-// CHECK-X64: = trunc i128 %
+// CHECK-X64: = zext i8 %{{.*}} to i64
+// CHECK-X64: = tail call i64 @llvm.fshl.i64(i64 %h, i64 %l, i64 %{{.*}})
 // CHECK-X64:  ret i64 %
 
 unsigned __int64 test__shiftright128(unsigned __int64 l, unsigned __int64 h,
@@ -159,13 +153,8 @@
   return __shiftright128(l, h, d);
 }
 // CHECK-X64-LABEL: define dso_local i64 @test__shiftright128(i64 %l, i64 %h, 
i8 %d)
-// CHECK-X64:  = zext i64 %{{.*}} to i128
-// CHECK-X64: = shl nuw i128 %{{.*}}, 64
-// CHECK-X64: = zext i64 %{{.*}} to i128
-// CHECK-X64: = or i128 %
-// CHECK-X64: = and i8 %{{.*}}, 63
-// CHECK-X64: = lshr i128 %
-// CHECK-X64: = trunc i128 %
+// CHECK-X64: = zext i8 %{{.*}} to i64
+// CHECK-X64: = tail call i64 @llvm.fshr.i64(i64 %h, i64 %l, i64 %{{.*}})
 // CHECK-X64:  ret i64 %
 
 #endif // defined(__x86_64__)
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -13926,25 +13926,15 @@
   }
   case X86::BI__shiftleft128:
   case X86::BI__shiftright128: {
-// FIXME: Once fshl/fshr no longer add an unneeded and and cmov, do this:
-// llvm::Function *F = CGM.getIntrinsic(
-//   BuiltinID == X86::BI__shiftleft128 ? Intrinsic::fshl : 
Intrinsic::fshr,
-//   Int64Ty);
-// Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
-// return Builder.CreateCall(F, Ops);
-llvm::Type *Int128Ty = Builder.getInt128Ty();
-Value *HighPart128 =
-Builder.CreateShl(Builder.CreateZExt(Ops[1], Int128Ty), 64);
-Value *LowPart128 = Builder.CreateZExt(Ops[0], Int128Ty);
-Value *Val = Builder.CreateOr(HighPart128, LowPart128);
-Value *Amt = Builder.CreateAnd(Builder.CreateZExt(Ops[2], Int128Ty),
-   llvm::ConstantInt::get(Int128Ty, 0x3f));
-Value *Res;
-if (BuiltinID == X86::BI__shiftleft128)
-  Res = Builder.CreateLShr(Builder.CreateShl(Val, Amt), 64);
-else
-  Res = Builder.CreateLShr(Val, Amt);
-return Builder.CreateTrunc(Res, Int64Ty);
+llvm::Function *F = CGM.getIntrinsic(
+BuiltinID == X86::BI__shiftleft128 ? Intrinsic::fshl : Intrinsic::fshr,
+Int64Ty);
+// Flip low/high ops and zero-extend amount to matching type.
+// shiftleft128(Low, High, Amt) -> fshl(High, Low, Amt)
+// shiftright128(Low, High, Amt) -> fshr(High, Low, Amt)
+std::swap(Ops[0], Ops[1]);
+Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
+return Builder.CreateCall(F, Ops);
   }
   case X86::BI_ReadWriteBarrier:
   case X86::BI_ReadBarrier:


Index: clang/test/CodeGen/X86/ms-x86-intrinsics.c
===
--- clang/test/CodeGen/X86/ms-x86-intrinsics.c
+++ clang/test/CodeGen/X86/ms-x86-intrinsics.c
@@ -144,14 +144,8 @@
   return __shiftleft128(l, h, d);
 }
 // CHECK-X64-LABEL: define dso_local i64 @test__shiftleft128(i64 %l, i64 %h, i8 %d)
-// CHECK-X64:  = zext i64 %{{.*}} to i128
-// CHECK-X64: = shl nuw i128 %{{.*}}, 64
-// CHECK-X64: = zext i64 %{{.*}} to i128
-// CHECK-X64: = or i128 %
-// CHECK-X64: = and i8 %{{.*}}, 63
-// CHECK-X64: = shl i128 %
-// CHECK-X64: = lshr i128 %
-// CHECK-X64: = trunc i128 %
+// CHECK-X64: = zext i8 %{{.*}} to i64
+// CHECK-X64: = tail call i64 @llvm.fshl.i64(i64 %h, i64 %l, i64 %{{.*}})
 // CHECK-X64:  ret i64 %
 
 unsigned __int64 test__shiftright128(unsigned __int64 l, unsigned __int64 h,
@@ -159,13 +153,8 @@
   return __shiftright128(l, h, d);
 }
 // CHECK-X64-LABEL: define dso_local i64 @test__shiftright128(i64 %l, i64 %h, i8 %d)
-// CHECK-X64:  = zext i64 %{{.*}} to i128
-// CHECK-X64: = shl nuw i128 %{{.*}}, 64
-// CHECK-X64: = zext i64 %{{.*}} to i128
-// CHECK-X64: = or i128 %
-// CHECK-X64: = and i8 %{{.*}}, 63
-// CHECK-X64: = lshr i128 %
-// CHECK-X64: = trunc i128 %
+// CHECK-X64: = zext i8 %{{.*}} t

[PATCH] D89210: [Sema, CodeGen] Implement [[likely]] and [[unlikely]] in SwitchStmt

2020-10-14 Thread Mark de Wever via Phabricator via cfe-commits
Mordante marked 8 inline comments as done.
Mordante added a comment.

In D89210#2328378 , @aaron.ballman 
wrote:

> Thank you for the continued work on this feature! I'd like to better 
> understand the behavior of fallthrough labels because I think there are two 
> conceptual models we could follow. When a label falls through to another 
> label, should both labels be treated as having the same likelihood or should 
> they be treated as distinct cases? e.g.,
>
>   switch (something) {
>   case 1:
> ...
>   [[likely]] case 2:
> ...
> break;
>   case 3:
> ...

The likelihood is not affected by falling though, so all cases are distinct. 
This due to the standard's wording "A path of execution includes a label if and 
only if it contains a jump to that label." 
(http://eel.is/c++draft/dcl.attr.likelihood#2). The falling through would 
affect cases where the likelihood isn't on the labels, like:

  switch (something) {
   case 1: 
   case 2: [[likely]];
  }

I understood from our earlier conversations we didn't want to support that 
option, due to:

  switch (something) {
   case 1:
  if(foo()) break;
  // Falling through depends on the return value of foo()
  // is this still the path of execution of 'case 1'?
   case 2: [[likely]];
  }

Here we get to the cases where it might confuse the user what the affect of 
their attribute is. If we were to implement that not all cases are distinct. 
Implementing that would require flow analyzes.

I still have some more WIP patches regarding the likelihood. After they are 
landed I still intend to start a conversation with other compiler vendors to 
see whether we can agree on best practices regarding the likelihood attributes. 
Depending on the outcome of that conversation I might change the implementation 
in Clang.

> Should case 1 be considered likely because it falls through to case 2? From 
> the patch, it looks like your answer is "yes", they should both be likely, 
> but should that hold true even if case 1 does a lot of work and is not 
> actually all that likely? Or is the user expected to write `[[unlikely]] case 
> 1:` in that situation? We don't seem to have a test case for a situation 
> where fallthrough says something like that:
>
>   switch (something) {
>   [[likely]] case 0:
> ...
> // Note the fallthrough
>   [[unlikely]] case 1:
> ...
>   }

In this case the user can use `[[unlikely]]`. If the user omits an attribute on 
`case 1` the label is considered neutral. Since `case 0` is positive, so it'll 
be the more likely path of execution.




Comment at: clang/include/clang/Basic/AttrDocs.td:1729-1731
+* all values with the ``likely`` attribute equally likely,
+* all values with the ``unlikely`` attribute equally unlikely,
+* all values without an attribute equally likely.

aaron.ballman wrote:
> How about:
> ```
> This makes:
> * all labels without an attribute have neutral likelihood,
> * all labels marked [[likely]] have equally positive likelihood, and
> * all labels marked [[unlikely]] have equally negative likelihood.
> ```
adapted with a minor change "have neutral" -> "have `a` neutral". The other two 
have a similar change.



Comment at: clang/include/clang/Basic/AttrDocs.td:1732
+* all values without an attribute equally likely.
+When a ``case`` has no likelihood attribute it is more likely to be the path of
+execution than a ``case`` with the ``unlikely`` attribute and it is less likely

aaron.ballman wrote:
> Instead of `case`, how about we use `switch label`?
I liked your neutral, positive, negative wording so I rewrote this part using 
these words. I feel that looks better than the original wording.



Comment at: clang/lib/CodeGen/CGStmt.cpp:375
+ ArrayRef Attrs) {
+  // clang-format off
   switch (S->getStmtClass()) {

aaron.ballman wrote:
> How ugly is the default clang-format formatting for this? If it's not too 
> bad, perhaps we just re-format the switch statement as a whole?
It looks fine default formatted, I just thought we wanted to keep it compact. 
But I've no problem with keeping the code default formatted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89210

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


[PATCH] D89406: clang/{Format,Rewrite}: Stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Update clang/lib/Format and clang/lib/Rewrite to use a `MemoryBufferRef`
from `getBufferOrFake` instead of `MemoryBuffer*` from `getBuffer`.

No functionality change here, since the call sites weren't checking if 
the buffer was valid.


https://reviews.llvm.org/D89406

Files:
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Rewrite/HTMLRewrite.cpp


Index: clang/lib/Rewrite/HTMLRewrite.cpp
===
--- clang/lib/Rewrite/HTMLRewrite.cpp
+++ clang/lib/Rewrite/HTMLRewrite.cpp
@@ -107,9 +107,9 @@
 void html::EscapeText(Rewriter &R, FileID FID,
   bool EscapeSpaces, bool ReplaceTabs) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* C = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* C = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
 
   assert (C <= FileEnd);
 
@@ -226,9 +226,9 @@
 
 void html::AddLineNumbers(Rewriter& R, FileID FID) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* FileBeg = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* FileBeg = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
   const char* C = FileBeg;
   RewriteBuffer &RB = R.getEditBuffer(FID);
 
@@ -274,9 +274,9 @@
 void html::AddHeaderFooterInternalBuiltinCSS(Rewriter &R, FileID FID,
  StringRef title) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* FileStart = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* FileStart = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
 
   SourceLocation StartLoc = R.getSourceMgr().getLocForStartOfFile(FID);
   SourceLocation EndLoc = StartLoc.getLocWithOffset(FileEnd-FileStart);
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -763,7 +763,7 @@
   unsigned FirstInLineOffset;
   std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
   Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
-  StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
+  StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
   // Calculate the offset of the start of the current line.
   auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
   if (LineOffset == StringRef::npos) {


Index: clang/lib/Rewrite/HTMLRewrite.cpp
===
--- clang/lib/Rewrite/HTMLRewrite.cpp
+++ clang/lib/Rewrite/HTMLRewrite.cpp
@@ -107,9 +107,9 @@
 void html::EscapeText(Rewriter &R, FileID FID,
   bool EscapeSpaces, bool ReplaceTabs) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* C = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* C = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
 
   assert (C <= FileEnd);
 
@@ -226,9 +226,9 @@
 
 void html::AddLineNumbers(Rewriter& R, FileID FID) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* FileBeg = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* FileBeg = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
   const char* C = FileBeg;
   RewriteBuffer &RB = R.getEditBuffer(FID);
 
@@ -274,9 +274,9 @@
 void html::AddHeaderFooterInternalBuiltinCSS(Rewriter &R, FileID FID,
  StringRef title) {
 
-  const llvm::MemoryBuffer *Buf = R.getSourceMgr().getBuffer(FID);
-  const char* FileStart = Buf->getBufferStart();
-  const char* FileEnd = Buf->getBufferEnd();
+  llvm::MemoryBufferRef Buf = R.getSourceMgr().getBufferOrFake(FID);
+  const char* FileStart = Buf.getBufferStart();
+  const char* FileEnd = Buf.getBufferEnd();
 
   SourceLocation StartLoc = R.getSourceMgr().getLocForStartOfFile(FID);
   SourceLocation EndLoc = StartLoc.getLocWithOffset(FileEnd-FileStart);
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -763,7 +763,7 @@
   unsigned FirstInLineOffset;
   std::tie(ID, FirstInLineOffset) =

[PATCH] D89210: [Sema, CodeGen] Implement [[likely]] and [[unlikely]] in SwitchStmt

2020-10-14 Thread Mark de Wever via Phabricator via cfe-commits
Mordante updated this revision to Diff 298176.
Mordante marked 3 inline comments as done.
Mordante added a comment.

Address review comments:

- Improved the documentation
- Enabled clang-format on the new code
- Added unit tests
- Removed some unneeded code from the unit tests due to -disable-llvm-passes
- Added information for the release notes


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

https://reviews.llvm.org/D89210

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/lib/AST/Stmt.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCXX/attr-likelihood-switch-branch-weights.cpp
  clang/test/Preprocessor/has_attribute.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -988,7 +988,7 @@
 
   [[likely]] and [[unlikely]] attributes
   https://wg21.link/p0479r5";>P0479R5
-  Clang 12 (partial)
+  Clang 12
 
 
   typename optional in more contexts
Index: clang/test/Preprocessor/has_attribute.cpp
===
--- clang/test/Preprocessor/has_attribute.cpp
+++ clang/test/Preprocessor/has_attribute.cpp
@@ -62,13 +62,13 @@
 // FIXME(201806L) CHECK: ensures: 0
 // FIXME(201806L) CHECK: expects: 0
 // CHECK: fallthrough: 201603L
-// FIXME(201803L) CHECK: likely: 2L
+// CHECK: likely: 201803L
 // CHECK: maybe_unused: 201603L
 // ITANIUM: no_unique_address: 201803L
 // WINDOWS: no_unique_address: 0
 // CHECK: nodiscard: 201907L
 // CHECK: noreturn: 200809L
-// FIXME(201803L) CHECK: unlikely: 2L
+// CHECK: unlikely: 201803L
 
 // Test for Microsoft __declspec attributes
 
Index: clang/test/CodeGenCXX/attr-likelihood-switch-branch-weights.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/attr-likelihood-switch-branch-weights.cpp
@@ -0,0 +1,194 @@
+// RUN: %clang_cc1 -O1 -disable-llvm-passes -emit-llvm %s -o - -triple=x86_64-linux-gnu | FileCheck %s
+
+extern volatile int i;
+
+void OneCaseL() {
+  // CHECK-LABEL: define{{.*}}OneCaseL
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !6
+  switch (i) {
+[[likely]] case 1: break;
+  }
+}
+
+void OneCaseU() {
+  // CHECK-LABEL: define{{.*}}OneCaseU
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !7
+  switch (i) {
+[[unlikely]] case 1: ++i; break;
+  }
+}
+
+void TwoCasesLN() {
+  // CHECK-LABEL: define{{.*}}TwoCasesLN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !8
+  switch (i) {
+[[likely]] case 1: break;
+case 2: break;
+  }
+}
+
+void TwoCasesUN() {
+  // CHECK-LABEL: define{{.*}}TwoCasesUN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !9
+  switch (i) {
+[[unlikely]] case 1: break;
+case 2: break;
+  }
+}
+
+void TwoCasesLU() {
+  // CHECK-LABEL: define{{.*}}TwoCasesLU
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !10
+  switch (i) {
+[[likely]] case 1: break;
+[[unlikely]] case 2: break;
+  }
+}
+
+void CasesFallthroughNNLN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughNNLN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !11
+  switch (i) {
+case 1:
+case 2:
+[[likely]] case 3:
+case 4: break;
+  }
+}
+
+void CasesFallthroughNNUN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughNNUN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !12
+  switch (i) {
+case 1:
+case 2:
+[[unlikely]] case 3:
+case 4: break;
+  }
+}
+
+void CasesFallthroughRangeSmallLN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughRangeSmallLN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !13
+  switch (i) {
+case 1 ... 5: ++i;
+case 102:
+[[likely]] case 103:
+case 104: break;
+  }
+}
+
+void CasesFallthroughRangeSmallUN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughRangeSmallUN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !14
+  switch (i) {
+case 1 ... 5: ++i;
+case 102:
+[[unlikely]] case 103:
+case 104: break;
+  }
+}
+
+void CasesFallthroughRangeLargeLLN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughRangeLargeLLN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !8
+  // CHECK: caserange
+  // CHECK: br{{.*}} !prof !15
+  switch (i) {
+[[likely]] case 0 ... 64:
+[[likely]] case 1003:
+case 104: break;
+  }
+}
+
+void CasesFallthroughRangeLargeUUN() {
+  // CHECK-LABEL: define{{.*}}CasesFallthroughRangeLargeUUN
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !9
+  // CHECK: caserange
+  // CHECK: br{{.*}} !prof !16
+  switch (i) {
+[[unlikely]] case 0 ... 64:
+[[unlikely]] case 1003:
+case 104: break;
+  }
+}
+
+void OneCaseDefaultL() {
+  // CHECK-LABEL: define{{.*}}OneCaseDefaultL
+  // CHECK: switch
+  // CHECK: {{.*}} !prof !17
+  switch (i) {
+case 1: break;
+[[likely]

[PATCH] D89407: [clang-tidy] Add scoped enum constants to identifier naming check

2020-10-14 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: alexfh, JonasToth, aaron.ballman, gribozavr2.
Herald added subscribers: cfe-commits, xazax.hun.
Herald added a project: clang.
njames93 requested review of this revision.

Added option `ScopedEnumConstant(Prefix|Case|Suffix)` to 
readability-identitied-naming.
This controls the style for constants in scoped enums, declared as enum 
(class|struct).
If this option is unspecified the EnumConstant style will be used instead.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89407

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -18,6 +18,7 @@
 // RUN: {key: readability-identifier-naming.ConstexprVariableCase, value: lower_case}, \
 // RUN: {key: readability-identifier-naming.EnumCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.EnumPrefix, value: 'E'}, \
+// RUN: {key: readability-identifier-naming.ScopedEnumConstantCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE}, \
 // RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack}, \
 // RUN: {key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE}, \
@@ -160,6 +161,18 @@
 // CHECK-FIXES: {{^}}THIS_CONST_VALUE = 1,{{$}}
 };
 
+enum class EMyEnumeration {
+myConstant = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'myConstant'
+// CHECK-FIXES: {{^}}MyConstant = 1,{{$}}
+your_CONST = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'your_CONST'
+// CHECK-FIXES: {{^}}YourConst = 1,{{$}}
+THIS_ConstValue = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'THIS_ConstValue'
+// CHECK-FIXES: {{^}}ThisConstValue = 1,{{$}}
+};
+
 constexpr int ConstExpr_variable = MyConstant;
 // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for constexpr variable 'ConstExpr_variable'
 // CHECK-FIXES: {{^}}constexpr int const_expr_variable = MY_CONSTANT;{{$}}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
@@ -76,6 +76,7 @@
  - :option:`ProtectedMethodCase`, :option:`ProtectedMethodPrefix`, :option:`ProtectedMethodSuffix`
  - :option:`PublicMemberCase`, :option:`PublicMemberPrefix`, :option:`PublicMemberSuffix`
  - :option:`PublicMethodCase`, :option:`PublicMethodPrefix`, :option:`PublicMethodSuffix`
+ - :option:`ScopedEnumConstantCase`, :option:`ScopedEnumConstantPrefix`, :option:`ScopedEnumConstantSuffix`
  - :option:`StaticConstantCase`, :option:`StaticConstantPrefix`, :option:`StaticConstantSuffix`
  - :option:`StaticVariableCase`, :option:`StaticVariablePrefix`, :option:`StaticVariableSuffix`
  - :option:`StructCase`, :option:`StructPrefix`, :option:`StructSuffix`
@@ -1595,6 +1596,41 @@
   int pre_member_method_post();
 }
 
+.. option:: ScopedEnumConstantCase
+
+When defined, the check will ensure enum class constant names conform to the
+selected casing.
+
+.. option:: ScopedEnumConstantPrefix
+
+When defined, the check will ensure enum class constant names will add the
+prefixed with the given value (regardless of casing).
+
+.. option:: ScopedEnumConstantSuffix
+
+When defined, the check will ensure enum class constant names will add the
+suffix with the given value (regardless of casing).
+
+For example using values of:
+
+   - ScopedEnumConstantCase of ``lower_case``
+   - ScopedEnumConstantPrefix of ``pre_``
+   - ScopedEnumConstantSuffix of ``_post``
+
+Identifies and/or transforms enumeration constant names as follows:
+
+Before:
+
+.. code-block:: c++
+
+enum class FOO { One, Two, Three };
+
+After:
+
+.. code-block:: c++
+
+enum class FOO { pre_One_post, pre_Two_post, pre_Three_post };
+
 .. option:: StaticConstantCase
 
 When defined, the check will ensure static constant names conform to the
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -120,6 +120,9 @@
   Added an option `GetConfigPerFile` to supp

[PATCH] D89360: Treat constant contexts as being in the default rounding mode.

2020-10-14 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D89360#2329856 , @sepavloff wrote:

> I would propose to consider solution in D88498 
> . It tries to fix the real reason of the 
> malfunction - using dynamic rounding mode for evaluation of global variable 
> initializers.

That is not the real reason for the malfunction. If you narrowly look at C, you 
can convince yourself otherwise, but that's only because global variable 
initializers are the only place where we need to evaluate floating-point 
constant expressions in C. In C++, this problem affects all contexts where 
constant evaluation might happen (array bounds, bit-field widths, and a whole 
host of others).

D88498 's approach also can't correctly handle 
`constexpr` functions, for which we want different behavior depending on 
whether the *caller* is a manifestly constant evaluated context.




Comment at: clang/test/SemaCXX/rounding-math.cpp:9
+
+constexpr int f(int n) { return int(n * (1.0 / 3.0)); }
+

sepavloff wrote:
> This code requires additional solution. The function body is built using 
> dynamic rounding mode, which breaks its constexprness. We can avoid this kind 
> of errors if we assume that body of a constexpr function is parsed using 
> constant rounding mode (in this example it is the default mode). It makes 
> parsing constexpr function different from non-constexpr ones, but enables 
> convenient use:
> ```
> constexpr int add(float x, float y) { return x + y; }
> 
> #pragma STDC FENV_ROUND FE_UPWARD
> int a2 = add(2.0F, 0x1.02p0F);
> 
> #pragma STDC FENV_ROUND FE_DOWNWARD
> int a3 = add(2.0F, 0x1.02p0F);
> ```
> If calls of constexpr functions are processes with FP options acting in the 
> call site, a call to constexpr function becomes equivalent to execution of 
> statements of its body.
I don't understand what you mean by "breaks its constexprness". Using a dynamic 
rounding mode for the body of the function is exactly what we want here. When 
the function is called in a manifestly constant evaluated context, we should 
use the default rounding mode, and when it's called at runtime, we use the 
appropriate dynamic rounding mode; if we try to constant evaluate it outside of 
a manifestly constant evaluated constant, we deem it non-constant.

When `constexpr` function is called at runtime, it's a completely normal 
function with normal semantics. It would be wrong to use the default rounding 
mode when parsing its body.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89360

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


[PATCH] D89327: fixes compiler-rt bug when printing libgcc for baremetal

2020-10-14 Thread Manoj Gupta via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG18432bea7648: [Driver]: fix compiler-rt path when printing 
libgcc for baremetal (authored by cjdb, committed by manojgupta).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D89327?vs=297924&id=298180#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89327

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/BareMetal.h
  clang/test/Driver/print-libgcc-file-name-clangrt.c


Index: clang/test/Driver/print-libgcc-file-name-clangrt.c
===
--- clang/test/Driver/print-libgcc-file-name-clangrt.c
+++ clang/test/Driver/print-libgcc-file-name-clangrt.c
@@ -42,3 +42,9 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-ABI %s
 // CHECK-CLANGRT-ARM-ABI: libclang_rt.builtins-armhf.a
+
+// RUN: %clang -rtlib=compiler-rt -print-libgcc-file-name 2>&1 \
+// RUN: --target=armv7m-none-eabi \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
+// RUN:   | FileCheck --check-prefix=CHECK-CLANGRT-ARM-BAREMETAL %s
+// CHECK-CLANGRT-ARM-BAREMETAL: libclang_rt.builtins-armv7m.a
Index: clang/lib/Driver/ToolChains/BareMetal.h
===
--- clang/lib/Driver/ToolChains/BareMetal.h
+++ clang/lib/Driver/ToolChains/BareMetal.h
@@ -23,7 +23,7 @@
 public:
   BareMetal(const Driver &D, const llvm::Triple &Triple,
 const llvm::opt::ArgList &Args);
-  ~BareMetal() override;
+  ~BareMetal() override = default;
 
   static bool handlesTarget(const llvm::Triple &Triple);
 protected:
@@ -37,6 +37,14 @@
   bool isPICDefaultForced() const override { return false; }
   bool SupportsProfiling() const override { return false; }
 
+  StringRef getOSLibName() const override { return "baremetal"; }
+
+  std::string getCompilerRTPath() const override;
+  std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
+StringRef Component,
+FileType Type = ToolChain::FT_Static,
+bool AddArch = true) const override;
+
   RuntimeLibType GetDefaultRuntimeLibType() const override {
 return ToolChain::RLT_CompilerRT;
   }
Index: clang/lib/Driver/ToolChains/BareMetal.cpp
===
--- clang/lib/Driver/ToolChains/BareMetal.cpp
+++ clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -35,8 +35,6 @@
 getProgramPaths().push_back(getDriver().Dir);
 }
 
-BareMetal::~BareMetal() {}
-
 /// Is the triple {arm,thumb}-none-none-{eabi,eabihf} ?
 static bool isARMBareMetal(const llvm::Triple &Triple) {
   if (Triple.getArch() != llvm::Triple::arm &&
@@ -64,6 +62,13 @@
   return new tools::baremetal::Linker(*this);
 }
 
+std::string BareMetal::getCompilerRTPath() const { return getRuntimesDir(); }
+
+std::string BareMetal::getCompilerRTBasename(const llvm::opt::ArgList &,
+ StringRef, FileType, bool) const {
+  return ("libclang_rt.builtins-" + getTriple().getArchName() + ".a").str();
+}
+
 std::string BareMetal::getRuntimesDir() const {
   SmallString<128> Dir(getDriver().ResourceDir);
   llvm::sys::path::append(Dir, "lib", "baremetal");
Index: clang/include/clang/Driver/ToolChain.h
===
--- clang/include/clang/Driver/ToolChain.h
+++ clang/include/clang/Driver/ToolChain.h
@@ -419,10 +419,10 @@
   getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
  FileType Type = ToolChain::FT_Static) const;
 
-  std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
-StringRef Component,
-FileType Type = ToolChain::FT_Static,
-bool AddArch = true) const;
+  virtual std::string
+  getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component,
+FileType Type = ToolChain::FT_Static,
+bool AddArch = true) const;
 
   // Returns target specific runtime path if it exists.
   virtual Optional getRuntimePath() const;
@@ -435,7 +435,7 @@
   std::string getArchSpecificLibPath() const;
 
   // Returns  part of above.
-  StringRef getOSLibName() const;
+  virtual StringRef getOSLibName() const;
 
   /// needsProfileRT - returns true if instrumentation profile is on.
   static bool needsProfileRT(const llvm::opt::ArgList &Args);


Index: clang/test/Driver/print-libgcc-file-name-clangrt.c
===
--- clang

[clang] 18432be - [Driver]: fix compiler-rt path when printing libgcc for baremetal

2020-10-14 Thread Manoj Gupta via cfe-commits

Author: Christopher Di Bella
Date: 2020-10-14T10:29:35-07:00
New Revision: 18432bea764863d1c42fd569bd3846673ee4e802

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

LOG: [Driver]: fix compiler-rt path when printing libgcc for baremetal

clang --target arm-none-eabi --print-libgcc-file-name --rtlib=compiler-rt
used to print `/path/to/lib/clang/version/lib/libclang_rt.builtins-arm.a`
but should print 
`/path/to/lib/clang/version/lib/baremetal/libclang_rt.builtins-arm.a`.
Similarly, --target armv7m-none-eabi should print libclang_rt.builtins-armv7m.a
This matches the compiler-rt file name used at link time in the
baremetal driver.

Reviewed By: manojgupta

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

Added: 


Modified: 
clang/include/clang/Driver/ToolChain.h
clang/lib/Driver/ToolChains/BareMetal.cpp
clang/lib/Driver/ToolChains/BareMetal.h
clang/test/Driver/print-libgcc-file-name-clangrt.c

Removed: 




diff  --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 7495e08fe6e6..4704308f0450 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -419,10 +419,10 @@ class ToolChain {
   getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component,
  FileType Type = ToolChain::FT_Static) const;
 
-  std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
-StringRef Component,
-FileType Type = ToolChain::FT_Static,
-bool AddArch = true) const;
+  virtual std::string
+  getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component,
+FileType Type = ToolChain::FT_Static,
+bool AddArch = true) const;
 
   // Returns target specific runtime path if it exists.
   virtual Optional getRuntimePath() const;
@@ -435,7 +435,7 @@ class ToolChain {
   std::string getArchSpecificLibPath() const;
 
   // Returns  part of above.
-  StringRef getOSLibName() const;
+  virtual StringRef getOSLibName() const;
 
   /// needsProfileRT - returns true if instrumentation profile is on.
   static bool needsProfileRT(const llvm::opt::ArgList &Args);

diff  --git a/clang/lib/Driver/ToolChains/BareMetal.cpp 
b/clang/lib/Driver/ToolChains/BareMetal.cpp
index 6ed81c1e34a1..9df42061e12c 100644
--- a/clang/lib/Driver/ToolChains/BareMetal.cpp
+++ b/clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -35,8 +35,6 @@ BareMetal::BareMetal(const Driver &D, const llvm::Triple 
&Triple,
 getProgramPaths().push_back(getDriver().Dir);
 }
 
-BareMetal::~BareMetal() {}
-
 /// Is the triple {arm,thumb}-none-none-{eabi,eabihf} ?
 static bool isARMBareMetal(const llvm::Triple &Triple) {
   if (Triple.getArch() != llvm::Triple::arm &&
@@ -64,6 +62,13 @@ Tool *BareMetal::buildLinker() const {
   return new tools::baremetal::Linker(*this);
 }
 
+std::string BareMetal::getCompilerRTPath() const { return getRuntimesDir(); }
+
+std::string BareMetal::getCompilerRTBasename(const llvm::opt::ArgList &,
+ StringRef, FileType, bool) const {
+  return ("libclang_rt.builtins-" + getTriple().getArchName() + ".a").str();
+}
+
 std::string BareMetal::getRuntimesDir() const {
   SmallString<128> Dir(getDriver().ResourceDir);
   llvm::sys::path::append(Dir, "lib", "baremetal");

diff  --git a/clang/lib/Driver/ToolChains/BareMetal.h 
b/clang/lib/Driver/ToolChains/BareMetal.h
index 4c0c739307b1..0be9377134ce 100644
--- a/clang/lib/Driver/ToolChains/BareMetal.h
+++ b/clang/lib/Driver/ToolChains/BareMetal.h
@@ -23,7 +23,7 @@ class LLVM_LIBRARY_VISIBILITY BareMetal : public ToolChain {
 public:
   BareMetal(const Driver &D, const llvm::Triple &Triple,
 const llvm::opt::ArgList &Args);
-  ~BareMetal() override;
+  ~BareMetal() override = default;
 
   static bool handlesTarget(const llvm::Triple &Triple);
 protected:
@@ -37,6 +37,14 @@ class LLVM_LIBRARY_VISIBILITY BareMetal : public ToolChain {
   bool isPICDefaultForced() const override { return false; }
   bool SupportsProfiling() const override { return false; }
 
+  StringRef getOSLibName() const override { return "baremetal"; }
+
+  std::string getCompilerRTPath() const override;
+  std::string getCompilerRTBasename(const llvm::opt::ArgList &Args,
+StringRef Component,
+FileType Type = ToolChain::FT_Static,
+bool AddArch = true) const override;
+
   RuntimeLibType GetDefaultRuntimeLibType() const override {
 return ToolChain::RLT_CompilerRT;
   }

diff  --git a/clang/test/Driver/print-libgcc-file-name-clangrt.c 
b/clang

[PATCH] D89409: clang/Frontend: Mostly stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Update clang/lib/Frontend to use a `MemoryBufferRef` from 
`getBufferOrFake` instead of `MemoryBuffer*` from `getBuffer`, with the 
exception of `FrontendInputFile`, which I'm leaving for later.


https://reviews.llvm.org/D89409

Files:
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Frontend/Rewrite/HTMLPrint.cpp
  clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
  clang/lib/Frontend/Rewrite/RewriteObjC.cpp


Index: clang/lib/Frontend/Rewrite/RewriteObjC.cpp
===
--- clang/lib/Frontend/Rewrite/RewriteObjC.cpp
+++ clang/lib/Frontend/Rewrite/RewriteObjC.cpp
@@ -631,9 +631,9 @@
 
   // Get the ID and start/end of the main file.
   MainFileID = SM->getMainFileID();
-  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
-  MainFileStart = MainBuf->getBufferStart();
-  MainFileEnd = MainBuf->getBufferEnd();
+  llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
+  MainFileStart = MainBuf.getBufferStart();
+  MainFileEnd = MainBuf.getBufferEnd();
 
   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
 }
Index: clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
===
--- clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
+++ clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp
@@ -702,9 +702,9 @@
 
   // Get the ID and start/end of the main file.
   MainFileID = SM->getMainFileID();
-  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
-  MainFileStart = MainBuf->getBufferStart();
-  MainFileEnd = MainBuf->getBufferEnd();
+  llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
+  MainFileStart = MainBuf.getBufferStart();
+  MainFileEnd = MainBuf.getBufferEnd();
 
   Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
 }
Index: clang/lib/Frontend/Rewrite/HTMLPrint.cpp
===
--- clang/lib/Frontend/Rewrite/HTMLPrint.cpp
+++ clang/lib/Frontend/Rewrite/HTMLPrint.cpp
@@ -70,7 +70,7 @@
   if (Entry)
 Name = Entry->getName();
   else
-Name = R.getSourceMgr().getBuffer(FID)->getBufferIdentifier();
+Name = R.getSourceMgr().getBufferOrFake(FID).getBufferIdentifier();
 
   html::AddLineNumbers(R, FID);
   html::AddHeaderFooterInternalBuiltinCSS(R, FID, Name);
Index: clang/lib/Frontend/FrontendActions.cpp
===
--- clang/lib/Frontend/FrontendActions.cpp
+++ clang/lib/Frontend/FrontendActions.cpp
@@ -805,11 +805,9 @@
   // concern, so if we scan for too long, we'll just assume the file should
   // be opened in binary mode.
   bool BinaryMode = true;
-  bool InvalidFile = false;
   const SourceManager& SM = CI.getSourceManager();
-  const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
- &InvalidFile);
-  if (!InvalidFile) {
+  if (llvm::Optional Buffer =
+  SM.getBufferOrNone(SM.getMainFileID())) {
 const char *cur = Buffer->getBufferStart();
 const char *end = Buffer->getBufferEnd();
 const char *next = (cur != end) ? cur + 1 : end;
@@ -937,12 +935,12 @@
 void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
   CompilerInstance &CI = getCompilerInstance();
   SourceManager &SM = CI.getPreprocessor().getSourceManager();
-  const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
+  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
 
   llvm::SmallString<1024> Output;
   llvm::SmallVector Toks;
   if (minimizeSourceToDependencyDirectives(
-  FromFile->getBuffer(), Output, Toks, &CI.getDiagnostics(),
+  FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(),
   SM.getLocForStartOfFile(SM.getMainFileID( {
 assert(CI.getDiagnostics().hasErrorOccurred() &&
"no errors reported for failure");
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -449,7 +449,7 @@
PresumedModuleMapFile))
 return true;
 
-  if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
+  if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
 Offset = 0;
 
   return false;


Index: clang/lib/Frontend/Rewrite/RewriteObjC.cpp
===
--- clang/lib/Frontend/Rewrite/RewriteObjC.cpp
+++ clang/lib/Frontend/Rewrite/RewriteObjC.cpp
@@ -631,9 +631,9 @@
 
   // Get the ID and start/end of the main file.
   MainFileID = SM->getMainFileID();
-  const llvm::MemoryBuffer *MainBuf = SM->getBuffe

[PATCH] D89411: clang/CodeGen: Mostly stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Update `clang/lib/CodeGen` to use a `MemoryBufferRef` from `getBufferOrNone` 
instead of `MemoryBuffer*` from `getBuffer`. No functionality change here.


https://reviews.llvm.org/D89411

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CodeGenAction.cpp


Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -1122,11 +1122,10 @@
 if (BA != Backend_EmitNothing && !OS)
   return;
 
-bool Invalid;
 SourceManager &SM = CI.getSourceManager();
 FileID FID = SM.getMainFileID();
-const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
-if (Invalid)
+Optional MainFile = SM.getBufferOrNone(FID);
+if (!MainFile)
   return;
 
 TheModule = loadModule(*MainFile);
@@ -1141,8 +1140,7 @@
   TheModule->setTargetTriple(TargetOpts.Triple);
 }
 
-EmbedBitcode(TheModule.get(), CodeGenOpts,
- MainFile->getMemBufferRef());
+EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
 
 LLVMContext &Ctx = TheModule->getContext();
 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -374,9 +374,8 @@
 return None;
 
   SourceManager &SM = CGM.getContext().getSourceManager();
-  bool Invalid;
-  const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
-  if (Invalid)
+  Optional MemBuffer = SM.getBufferOrNone(FID);
+  if (!MemBuffer)
 return None;
 
   llvm::MD5 Hash;


Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -1122,11 +1122,10 @@
 if (BA != Backend_EmitNothing && !OS)
   return;
 
-bool Invalid;
 SourceManager &SM = CI.getSourceManager();
 FileID FID = SM.getMainFileID();
-const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
-if (Invalid)
+Optional MainFile = SM.getBufferOrNone(FID);
+if (!MainFile)
   return;
 
 TheModule = loadModule(*MainFile);
@@ -1141,8 +1140,7 @@
   TheModule->setTargetTriple(TargetOpts.Triple);
 }
 
-EmbedBitcode(TheModule.get(), CodeGenOpts,
- MainFile->getMemBufferRef());
+EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
 
 LLVMContext &Ctx = TheModule->getContext();
 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -374,9 +374,8 @@
 return None;
 
   SourceManager &SM = CGM.getContext().getSourceManager();
-  bool Invalid;
-  const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
-  if (Invalid)
+  Optional MemBuffer = SM.getBufferOrNone(FID);
+  if (!MemBuffer)
 return None;
 
   llvm::MD5 Hash;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D86119: [OPENMP50]Allow overlapping mapping in target constrcuts.

2020-10-14 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

In D86119#2330339 , @ABataev wrote:

> In D86119#2330310 , @jdenny wrote:
>
>> Thanks for working on this.  Sorry to take so long to review.  Before I try 
>> to digest the code, I have a few high-level questions.
>>
>> Based on the test suite changes, `TARGET_PARAM` is disappearing from many 
>> cases.  Can you explain a bit how that supports overlapping and reordering?
>
> `TARGET_PARAM` is used only for marking the data that should be passed to the 
> kernel function as an argument. We just generate it in many cases but the 
> runtime actually does not use them. Thу patch relies on this thing, 
> otherwise, we may pass an incorrect number of arguments to the kernel 
> functions.

Is it reasonable to extract that change into a parent patch?  That would at 
least make the test suite changes easier to follow.

>> Have you considered issue 2337 for the OpenMP spec and how your 
>> implementation handles the ambiguous cases cited there?
>
> Can you provide the details about this issue?

It discusses ambiguities in the way the spec describes map clause ordering.  
Here's one example relevant to `present`:

  #pragma omp target exit data map(from: x) map(present, release: x)

One statement in the spec says a map clause with `from` is effectively ordered 
before one with `release`.  Another statement says a map clause with `present` 
is effectively ordered before one without.  Which applies in the above example? 
 In some discussions, people agreed the statement about `present` was intended 
to have precedence, but the spec doesn't say that.  That resolution probably 
makes sense at entry to a region, but does it make sense at exit?  Would it 
suppress `from` in this example?  (Actually, should there be two reference 
counter decrements in this example or just one?)

These ambiguities are the reason I punted on this issue when implementing 
`present`.  If we can come up with a reasonable implementation for all cases, 
perhaps we can propose a new wording for the spec.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86119

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


[PATCH] D86119: [OPENMP50]Allow overlapping mapping in target constrcuts.

2020-10-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D86119#2330601 , @jdenny wrote:

> In D86119#2330339 , @ABataev wrote:
>
>> In D86119#2330310 , @jdenny wrote:
>>
>>> Thanks for working on this.  Sorry to take so long to review.  Before I try 
>>> to digest the code, I have a few high-level questions.
>>>
>>> Based on the test suite changes, `TARGET_PARAM` is disappearing from many 
>>> cases.  Can you explain a bit how that supports overlapping and reordering?
>>
>> `TARGET_PARAM` is used only for marking the data that should be passed to 
>> the kernel function as an argument. We just generate it in many cases but 
>> the runtime actually does not use them. Thу patch relies on this thing, 
>> otherwise, we may pass an incorrect number of arguments to the kernel 
>> functions.
>
> Is it reasonable to extract that change into a parent patch?  That would at 
> least make the test suite changes easier to follow.

I'll see what I can do about it.

>>> Have you considered issue 2337 for the OpenMP spec and how your 
>>> implementation handles the ambiguous cases cited there?
>>
>> Can you provide the details about this issue?
>
> It discusses ambiguities in the way the spec describes map clause ordering.  
> Here's one example relevant to `present`:
>
>   #pragma omp target exit data map(from: x) map(present, release: x)
>
> One statement in the spec says a map clause with `from` is effectively 
> ordered before one with `release`.  Another statement says a map clause with 
> `present` is effectively ordered before one without.  Which applies in the 
> above example?  In some discussions, people agreed the statement about 
> `present` was intended to have precedence, but the spec doesn't say that.  
> That resolution probably makes sense at entry to a region, but does it make 
> sense at exit?  Would it suppress `from` in this example?  (Actually, should 
> there be two reference counter decrements in this example or just one?)
>
> These ambiguities are the reason I punted on this issue when implementing 
> `present`.  If we can come up with a reasonable implementation for all cases, 
> perhaps we can propose a new wording for the spec.

In tgis implementation, the mapping withthe present modifier will be ordered to 
be the first.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86119

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


[PATCH] D88712: [CGBuiltin] Respect asm labels and redefine_extname for builtins with specialized emitting

2020-10-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In case my previous comment is not clear: we can do renaming in LLVM, but the 
benefit is small (for a few libcalls (only some really simple libcalls) with 
custom code emitting, if they have `asm(...)`, they are now optimizable). We 
will require a renaming infrastructure in LLVM IR, which is a large 
undertaking. The patch as is is the most practical approach.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88712

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


[PATCH] D84362: [NFC] Refactor DiagnosticBuilder and PartialDiagnostic

2020-10-14 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/include/clang/Basic/PartialDiagnostic.h:51
+  : DiagID(DiagID) {
+Allocator = &Allocator_;
+  }

Is there a particular reason to move field initialization into the body here 
and in other constructors?


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

https://reviews.llvm.org/D84362

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


[PATCH] D89414: clang/StaticAnalyzer: Stop using SourceManager::getBuffer

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added subscribers: steakhal, ASDenysPetrov, martong, ributzka, dkrupp, 
donat.nagy, Szelethus, a.sidorin, baloghadamsoftware.
dexonsmith requested review of this revision.

Update clang/lib/StaticAnalyzer to stop relying on a `MemoryBuffer*`, using the 
`MemoryBufferRef` from `getBufferOrNone` or the `Optional` 
from `getBufferOrFake`, depending on whether there's logic for checking 
validity of the buffer. The change to 
clang/lib/StaticAnalyzer/Core/IssueHash.cpp is potentially a functionality 
change, since the logic was wrong (it checked for `nullptr`, which was never 
returned by the old API), but if that was reachable the new behaviour should be 
better.


https://reviews.llvm.org/D89414

Files:
  clang/lib/StaticAnalyzer/Checkers/LocalizationChecker.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/IssueHash.cpp
  clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp

Index: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
===
--- clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
+++ clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
@@ -476,7 +476,7 @@
 static bool isBisonFile(ASTContext &C) {
   const SourceManager &SM = C.getSourceManager();
   FileID FID = SM.getMainFileID();
-  StringRef Buffer = SM.getBuffer(FID)->getBuffer();
+  StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
   if (Buffer.startswith("/* A Bison parser, made by"))
 return true;
   return false;
Index: clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
@@ -160,9 +160,8 @@
   assert(LocInfo.second > SM.getExpansionColumnNumber(Loc) &&
  "position in file is before column number?");
 
-  bool InvalidBuffer = false;
-  const MemoryBuffer *Buf = SM.getBuffer(LocInfo.first, &InvalidBuffer);
-  assert(!InvalidBuffer && "got an invalid buffer for the location's file");
+  Optional Buf = SM.getBufferOrNone(LocInfo.first);
+  assert(Buf && "got an invalid buffer for the location's file");
   assert(Buf->getBufferSize() >= (LocInfo.second + TokenLen) &&
  "token extends past end of buffer?");
 
Index: clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp
@@ -887,12 +887,12 @@
 FileID File;
 unsigned Offset;
 std::tie(File, Offset) = SM.getDecomposedLoc(ExpanLoc);
-const llvm::MemoryBuffer *MB = SM.getBuffer(File);
-const char *MacroNameTokenPos = MB->getBufferStart() + Offset;
+llvm::MemoryBufferRef MB = SM.getBufferOrFake(File);
+const char *MacroNameTokenPos = MB.getBufferStart() + Offset;
 
 RawLexer = std::make_unique(SM.getLocForStartOfFile(File), LangOpts,
-   MB->getBufferStart(), MacroNameTokenPos,
-   MB->getBufferEnd());
+   MB.getBufferStart(), MacroNameTokenPos,
+   MB.getBufferEnd());
   }
 
   void next(Token &Result) {
Index: clang/lib/StaticAnalyzer/Core/IssueHash.cpp
===
--- clang/lib/StaticAnalyzer/Core/IssueHash.cpp
+++ clang/lib/StaticAnalyzer/Core/IssueHash.cpp
@@ -120,7 +120,8 @@
   return "";
 }
 
-static StringRef GetNthLineOfFile(const llvm::MemoryBuffer *Buffer, int Line) {
+static StringRef GetNthLineOfFile(llvm::Optional Buffer,
+  int Line) {
   if (!Buffer)
 return "";
 
@@ -135,7 +136,7 @@
  const LangOptions &LangOpts) {
   static StringRef Whitespaces = " \t\n";
 
-  StringRef Str = GetNthLineOfFile(SM.getBuffer(L.getFileID(), L),
+  StringRef Str = GetNthLineOfFile(SM.getBufferOrNone(L.getFileID(), L),
L.getExpansionLineNumber());
   StringRef::size_type col = Str.find_first_not_of(Whitespaces);
   if (col == StringRef::npos)
@@ -144,8 +145,8 @@
 col++;
   SourceLocation StartOfLine =
   SM.translateLineCol(SM.getFileID(L), L.getExpansionLineNumber(), col);
-  const llvm::MemoryBuffer *Buffer =
-  SM.getBuffer(SM.getFileID(StartOfLine), StartOfLine);
+  Optional Buffer =
+  SM.getBufferOrNone(SM.getFileID(StartOfLine), StartOfLine);
   if (!Buffer)
 return {};
 
Index: clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/HTMLDiagn

[PATCH] D86671: [clang-tidy] Add new case type to check variables with Hungarian notation

2020-10-14 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Is this diff been created incorrectly again?

Taking a step back, Is Hungarian notation really a case style, Seems to me its 
mainly about the prefix and a user may want `DWORD dwUPPER_CASE`, Right now 
there is no way of adopting that.
Maybe extend the options for hungarian type decls to

  Case
  Prefix
  Suffix
  HungarianPrefix

`HungarianPrefix` would likely be a bool and if enabled, it would be 
prepended to `Prefix`
I could see a situation like this

  [Options]
  // VariableCase: UPPER_CASE
  // VariablePrefix: PRE_
  // VariableSuffix: _POST
  // VariableHungarianPrefix: true
  
  DWORD MyVariable; -> DWORD dwPRE_MY_VARIABLE_POST;

This would give users full control of exactly how they want their declarations 
with no hidden surprises.

Granted this approach would require a little rework but it would satisfy more 
users.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86671

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-14 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added inline comments.



Comment at: clang/include/clang/Basic/OpenCLExtensions.def:74
 OPENCLEXT_INTERNAL(cl_khr_mipmap_image_writes, 200, ~0U)
-OPENCLEXT_INTERNAL(cl_khr_srgb_image_writes, 200, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_subgroups, 200, ~0U)

mantognini wrote:
> azabaznov wrote:
> > cl_khr_srgb_image_writes - Extension allowing writes to sRGB images from a 
> > kernel. This extension enables write_imagef built-in function as it 
> > described [[ 
> > https://www.khronos.org/registry/OpenCL/specs/2.2/html/OpenCL_Ext.html#cl_khr_srgb_image_writes
> >  | here]]. So I think we shouldn't remove it. Do I miss something?
> On second reading, this one is slightly ambiguous. On the language side, the 
> extension doesn't add an overload; it only specifies that existing overload 
> can be used with a different kind of image. On the API side, it does extend 
> the set of features. But at the same time if the extended API is not 
> supported, it's not possible to create an image in the first place and 
> therefore impossible to call write_imagef. So I question the usefulness of 
> such macro on the device side. Does this argument convince you it should be 
> removed?
> it's not possible to create an image in the first place and therefore 
> impossible
Not quite that right. Referring to [[ 
https://www.khronos.org/registry/OpenCL/specs/2.2/html/OpenCL_C.html#conversion-rules-for-srgba-and-sbgra-images
 | this ]]:

read_imagef built-in functions for OpenCL C 2.0 devices do implicit conversions 
to RGB for sRGB images. However, implicit conversion from sRGB to RGB is done 
on write_imagef only if corresponding extension is supported. Otherwise, 
explicit conversions inside a kernel may be required.

I'm agree that this one is kind of confusing and requires some extra 
investigation. But I think now we should remove only those extensions which are 
only API related for sure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89407: [clang-tidy] Add scoped enum constants to identifier naming check

2020-10-14 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 298200.
njames93 added a comment.

Small tweak to the docs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89407

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
  clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming.cpp
@@ -18,6 +18,7 @@
 // RUN: {key: readability-identifier-naming.ConstexprVariableCase, value: lower_case}, \
 // RUN: {key: readability-identifier-naming.EnumCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.EnumPrefix, value: 'E'}, \
+// RUN: {key: readability-identifier-naming.ScopedEnumConstantCase, value: CamelCase}, \
 // RUN: {key: readability-identifier-naming.EnumConstantCase, value: UPPER_CASE}, \
 // RUN: {key: readability-identifier-naming.FunctionCase, value: camelBack}, \
 // RUN: {key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE}, \
@@ -160,6 +161,18 @@
 // CHECK-FIXES: {{^}}THIS_CONST_VALUE = 1,{{$}}
 };
 
+enum class EMyEnumeration {
+myConstant = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'myConstant'
+// CHECK-FIXES: {{^}}MyConstant = 1,{{$}}
+your_CONST = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'your_CONST'
+// CHECK-FIXES: {{^}}YourConst = 1,{{$}}
+THIS_ConstValue = 1,
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: invalid case style for scoped enum constant 'THIS_ConstValue'
+// CHECK-FIXES: {{^}}ThisConstValue = 1,{{$}}
+};
+
 constexpr int ConstExpr_variable = MyConstant;
 // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: invalid case style for constexpr variable 'ConstExpr_variable'
 // CHECK-FIXES: {{^}}constexpr int const_expr_variable = MY_CONSTANT;{{$}}
Index: clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
@@ -76,6 +76,7 @@
  - :option:`ProtectedMethodCase`, :option:`ProtectedMethodPrefix`, :option:`ProtectedMethodSuffix`
  - :option:`PublicMemberCase`, :option:`PublicMemberPrefix`, :option:`PublicMemberSuffix`
  - :option:`PublicMethodCase`, :option:`PublicMethodPrefix`, :option:`PublicMethodSuffix`
+ - :option:`ScopedEnumConstantCase`, :option:`ScopedEnumConstantPrefix`, :option:`ScopedEnumConstantSuffix`
  - :option:`StaticConstantCase`, :option:`StaticConstantPrefix`, :option:`StaticConstantSuffix`
  - :option:`StaticVariableCase`, :option:`StaticVariablePrefix`, :option:`StaticVariableSuffix`
  - :option:`StructCase`, :option:`StructPrefix`, :option:`StructSuffix`
@@ -1595,6 +1596,41 @@
   int pre_member_method_post();
 }
 
+.. option:: ScopedEnumConstantCase
+
+When defined, the check will ensure scoped enum constant names conform to 
+the selected casing.
+
+.. option:: ScopedEnumConstantPrefix
+
+When defined, the check will ensure scoped enum constant names will add the
+prefixed with the given value (regardless of casing).
+
+.. option:: ScopedEnumConstantSuffix
+
+When defined, the check will ensure scoped enum constant names will add the
+suffix with the given value (regardless of casing).
+
+For example using values of:
+
+   - ScopedEnumConstantCase of ``lower_case``
+   - ScopedEnumConstantPrefix of ``pre_``
+   - ScopedEnumConstantSuffix of ``_post``
+
+Identifies and/or transforms enumeration constant names as follows:
+
+Before:
+
+.. code-block:: c++
+
+enum class FOO { One, Two, Three };
+
+After:
+
+.. code-block:: c++
+
+enum class FOO { pre_One_post, pre_Two_post, pre_Three_post };
+
 .. option:: StaticConstantCase
 
 When defined, the check will ensure static constant names conform to the
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -120,6 +120,9 @@
   Added an option `GetConfigPerFile` to support including files which use
   different naming styles.
 
+  Added support for specifying the style of scoped ``enum`` constants. If 
+  unspecified, will fall back to the style for regular ``enum`` constants.
+
 - Removed `google-runtime-references` check because the rule it checks does
   not exist in the Goog

[PATCH] D84362: [NFC] Refactor DiagnosticBuilder and PartialDiagnostic

2020-10-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added inline comments.



Comment at: clang/include/clang/Basic/PartialDiagnostic.h:51
+  : DiagID(DiagID) {
+Allocator = &Allocator_;
+  }

tra wrote:
> Is there a particular reason to move field initialization into the body here 
> and in other constructors?
Allocator is now a member of the base class, therefore needs to be initialized 
directly. I could add ctor to the base class but I did not see too much benefit 
of doing that.


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

https://reviews.llvm.org/D84362

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


[PATCH] D89416: clang-{tools,unittests}: Stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: arphaman.
Herald added subscribers: usaxena95, ributzka, kadircet.
Herald added a reviewer: shafik.
dexonsmith requested review of this revision.

Update clang-tools-extra, clang/tools, clang/unittests to migrate from
`SourceManager::getBuffer`, which returns an always dereferenceable
`MemoryBuffer*`, to `getBufferOrNone` or `getBufferOrFake`, both of
which return a `MemoryBufferRef`, depending on whether the call site was
checking for validity of the buffer. No functionality change intended.


https://reviews.llvm.org/D89416

Files:
  clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp
  clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
  clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/modularize/PreprocessorTracker.cpp
  clang/tools/clang-diff/ClangDiff.cpp
  clang/tools/clang-import-test/clang-import-test.cpp
  clang/tools/libclang/CIndex.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5695,7 +5695,8 @@
   // Make sure the imported buffer has the original contents.
   SourceManager &ToSM = ToAST->getSourceManager();
   FileID ImportedID = ToSM.getFileID(ImportedLoc);
-  EXPECT_EQ(Source, ToSM.getBuffer(ImportedID, SourceLocation())->getBuffer());
+  EXPECT_EQ(Source,
+ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer());
 }
 
 TEST_P(ImportSourceLocations, OverwrittenFileBuffer) {
@@ -5729,7 +5730,7 @@
   SourceManager &ToSM = ToAST->getSourceManager();
   FileID ImportedID = ToSM.getFileID(ImportedLoc);
   EXPECT_EQ(Contents,
-ToSM.getBuffer(ImportedID, SourceLocation())->getBuffer());
+ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, ImportExprOfAlignmentAttr) {
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -4363,8 +4363,8 @@
   const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
   FileID fid = SM.translateFile(static_cast(file));
   bool Invalid = true;
-  const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
-  if (Invalid) {
+  llvm::Optional buf = SM.getBufferOrNone(fid);
+  if (!buf) {
 if (size)
   *size = 0;
 return nullptr;
Index: clang/tools/clang-import-test/clang-import-test.cpp
===
--- clang/tools/clang-import-test/clang-import-test.cpp
+++ clang/tools/clang-import-test/clang-import-test.cpp
@@ -106,20 +106,19 @@
 unsigned LocColumn =
 SM.getSpellingColumnNumber(Loc, /*Invalid=*/nullptr) - 1;
 FileID FID = SM.getFileID(Loc);
-const llvm::MemoryBuffer *Buffer =
-SM.getBuffer(FID, Loc, /*Invalid=*/nullptr);
+llvm::MemoryBufferRef Buffer = SM.getBufferOrFake(FID, Loc);
 
-assert(LocData >= Buffer->getBufferStart() &&
-   LocData < Buffer->getBufferEnd());
+assert(LocData >= Buffer.getBufferStart() &&
+   LocData < Buffer.getBufferEnd());
 
 const char *LineBegin = LocData - LocColumn;
 
-assert(LineBegin >= Buffer->getBufferStart());
+assert(LineBegin >= Buffer.getBufferStart());
 
 const char *LineEnd = nullptr;
 
 for (LineEnd = LineBegin; *LineEnd != '\n' && *LineEnd != '\r' &&
-  LineEnd < Buffer->getBufferEnd();
+  LineEnd < Buffer.getBufferEnd();
  ++LineEnd)
   ;
 
Index: clang/tools/clang-diff/ClangDiff.cpp
===
--- clang/tools/clang-diff/ClangDiff.cpp
+++ clang/tools/clang-diff/ClangDiff.cpp
@@ -284,7 +284,7 @@
   unsigned Begin, End;
   std::tie(Begin, End) = Tree.getSourceRangeOffsets(Node);
   const SourceManager &SrcMgr = Tree.getASTContext().getSourceManager();
-  auto Code = SrcMgr.getBuffer(SrcMgr.getMainFileID())->getBuffer();
+  auto Code = SrcMgr.getBufferOrFake(SrcMgr.getMainFileID()).getBuffer();
   for (; Offset < Begin; ++Offset)
 printHtml(OS, Code[Offset]);
   OS << "getBufferStart();
-  const char *BufferEnd = MemBuffer->getBufferEnd();
+  llvm::MemoryBufferRef MemBuffer = PP.getSourceManager().getBufferOrFake(
+  PP.getSourceManager().getFileID(Loc));
+  const char *Buffer = MemBuffer.getBufferStart();
+  const char *BufferEnd = MemBuffer.getBufferEnd();
   const char *BeginPtr = PP.getSourceManager().getCharacterData(Loc);
   const char *EndPtr = BeginPtr;
   while (BeginPtr > Buffer) {
@@ -338,9 +3

[PATCH] D17993: [CodeGen] Apply 'nonnull' to 'this' pointer arguments.

2020-10-14 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:2165
+assert(getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0 &&
+   "Expected `this` pointer without address space attribute.");
+

jdoerfert wrote:
> I'm unsure why this assertion has to hold and more importantly why we need 
> it. @arsenm do you?
Even if the `this` pointer is always an address-space-0 pointer for now, it 
would be more consistent with how we handle `Attribute::NonNull` elsewhere to 
skip adding the `NonNull` attribute for non-address-space-0 pointers rather 
than asserting here.



Comment at: clang/lib/CodeGen/CGCall.cpp:2174
+  }
+
   unsigned ArgNo = 0;

jdoerfert wrote:
> rsmith wrote:
> > CJ-Johnson wrote:
> > > jdoerfert wrote:
> > > > Even if null pointer is valid we should place dereferenceable.
> > > > 
> > > > We also could never place nonnull and let the middle-end make the 
> > > > dereferenceable -> nonnull deduction, though I don't see why we can't 
> > > > just add nonnull here.
> > > I re-ran ninja check after making this fix and addressed the 
> > > newly-affected tests. So the patch is fully up to date :)
> > The LLVM LangRef says that in address space 0, `dereferenceable` implies 
> > `nonnull`, so I don't think we can emit `dereferenceable` in 
> > `NullPointerIsValid` mode, and we'd need to use `dereferenceable_or_null` 
> > instead. (Perhaps the LangRef is wrong, though, and the 
> > `null_pointer_is_valid` function attribute overrides that determination.)
> > (Perhaps the LangRef is wrong, though, and the null_pointer_is_valid 
> > function attribute overrides that determination.)
> 
> This is the case. IMHO, dereferenceable has to be correct here, regardless of 
> the mode. You could access the object in the function entry, which we would 
> use to deduce dereferenceable, and if the `NullPointerIsValid` is not 
> translated to the function attribute also to `nonnull`. 
OK, if the LangRef is wrong about this, then I agree we should emit 
`dereferenceable` unconditionally. Thanks for clarifying.


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

https://reviews.llvm.org/D17993

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


[PATCH] D89276: Support ObjC in IncludeInserter

2020-10-14 Thread Joe Turner via Phabricator via cfe-commits
compositeprimes updated this revision to Diff 298203.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89276

Files:
  clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeSorter.h
  clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
@@ -28,8 +28,10 @@
 
 class IncludeInserterCheckBase : public ClangTidyCheck {
 public:
-  IncludeInserterCheckBase(StringRef CheckName, ClangTidyContext *Context)
-  : ClangTidyCheck(CheckName, Context) {}
+  IncludeInserterCheckBase(StringRef CheckName, ClangTidyContext *Context,
+   utils::IncludeSorter::IncludeStyle Style =
+   utils::IncludeSorter::IS_Google)
+  : ClangTidyCheck(CheckName, Context), Inserter(Style) {}
 
   void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override {
@@ -50,7 +52,7 @@
 
   virtual std::vector headersToInclude() const = 0;
 
-  utils::IncludeInserter Inserter{utils::IncludeSorter::IS_Google};
+  utils::IncludeInserter Inserter;
 };
 
 class NonSystemHeaderInserterCheck : public IncludeInserterCheckBase {
@@ -111,6 +113,42 @@
   }
 };
 
+class ObjCEarlyInAlphabetHeaderInserterCheck : public IncludeInserterCheckBase {
+public:
+  ObjCEarlyInAlphabetHeaderInserterCheck(StringRef CheckName,
+ ClangTidyContext *Context)
+  : IncludeInserterCheckBase(CheckName, Context,
+ utils::IncludeSorter::IS_Google_ObjC) {}
+
+  std::vector headersToInclude() const override {
+return {"a/header.h"};
+  }
+};
+
+class ObjCCategoryHeaderInserterCheck : public IncludeInserterCheckBase {
+public:
+  ObjCCategoryHeaderInserterCheck(StringRef CheckName,
+  ClangTidyContext *Context)
+  : IncludeInserterCheckBase(CheckName, Context,
+ utils::IncludeSorter::IS_Google_ObjC) {}
+
+  std::vector headersToInclude() const override {
+return {"clang_tidy/tests/insert_includes_test_header+foo.h"};
+  }
+};
+
+class ObjCGeneratedHeaderInserterCheck : public IncludeInserterCheckBase {
+public:
+  ObjCGeneratedHeaderInserterCheck(StringRef CheckName,
+   ClangTidyContext *Context)
+  : IncludeInserterCheckBase(CheckName, Context,
+ utils::IncludeSorter::IS_Google_ObjC) {}
+
+  std::vector headersToInclude() const override {
+return {"clang_tidy/tests/generated_file.proto.h"};
+  }
+};
+
 template 
 std::string runCheckOnCode(StringRef Code, StringRef Filename) {
   std::vector Errors;
@@ -120,12 +158,20 @@
   {"clang_tidy/tests/"
"insert_includes_test_header.h",
"\n"},
+  // ObjC category.
+  {"clang_tidy/tests/"
+   "insert_includes_test_header+foo.h",
+   "\n"},
   // Non system headers
   {"a/header.h", "\n"},
   {"path/to/a/header.h", "\n"},
   {"path/to/z/header.h", "\n"},
   {"path/to/header.h", "\n"},
   {"path/to/header2.h", "\n"},
+  // Generated headers
+  {"clang_tidy/tests/"
+   "generated_file.proto.h",
+   "\n"},
   // Fake system headers.
   {"stdlib.h", "\n"},
   {"unistd.h", "\n"},
@@ -160,9 +206,9 @@
   int a = 0;
 })";
 
-  EXPECT_EQ(PostCode, runCheckOnCode(
-  PreCode, "clang_tidy/tests/"
-   "insert_includes_test_input2.cc"));
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, "clang_tidy/tests/insert_includes_test_input2.cc"));
 }
 
 TEST(IncludeInserterTest, InsertMultipleIncludesAndDeduplicate) {
@@ -191,9 +237,9 @@
   int a = 0;
 })";
 
-  EXPECT_EQ(PostCode, runCheckOnCode(
-  PreCode, "clang_tidy/tests/"
-   "insert_includes_test_input2.cc"));
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, "clang_tidy/tests/i

[PATCH] D89416: clang-{tools,unittests}: Stop using SourceManager::getBuffer, NFC

2020-10-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 298206.
dexonsmith added a comment.

Removed the now-unused `Invalid` local variable from the libclang change; not 
sure how I missed the warning before.


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

https://reviews.llvm.org/D89416

Files:
  clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp
  clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
  clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
  clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/modularize/PreprocessorTracker.cpp
  clang/tools/clang-diff/ClangDiff.cpp
  clang/tools/clang-import-test/clang-import-test.cpp
  clang/tools/libclang/CIndex.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -5695,7 +5695,8 @@
   // Make sure the imported buffer has the original contents.
   SourceManager &ToSM = ToAST->getSourceManager();
   FileID ImportedID = ToSM.getFileID(ImportedLoc);
-  EXPECT_EQ(Source, ToSM.getBuffer(ImportedID, SourceLocation())->getBuffer());
+  EXPECT_EQ(Source,
+ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer());
 }
 
 TEST_P(ImportSourceLocations, OverwrittenFileBuffer) {
@@ -5729,7 +5730,7 @@
   SourceManager &ToSM = ToAST->getSourceManager();
   FileID ImportedID = ToSM.getFileID(ImportedLoc);
   EXPECT_EQ(Contents,
-ToSM.getBuffer(ImportedID, SourceLocation())->getBuffer());
+ToSM.getBufferOrFake(ImportedID, SourceLocation()).getBuffer());
 }
 
 TEST_P(ASTImporterOptionSpecificTestBase, ImportExprOfAlignmentAttr) {
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -4362,9 +4362,8 @@
 
   const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
   FileID fid = SM.translateFile(static_cast(file));
-  bool Invalid = true;
-  const llvm::MemoryBuffer *buf = SM.getBuffer(fid, &Invalid);
-  if (Invalid) {
+  llvm::Optional buf = SM.getBufferOrNone(fid);
+  if (!buf) {
 if (size)
   *size = 0;
 return nullptr;
Index: clang/tools/clang-import-test/clang-import-test.cpp
===
--- clang/tools/clang-import-test/clang-import-test.cpp
+++ clang/tools/clang-import-test/clang-import-test.cpp
@@ -106,20 +106,19 @@
 unsigned LocColumn =
 SM.getSpellingColumnNumber(Loc, /*Invalid=*/nullptr) - 1;
 FileID FID = SM.getFileID(Loc);
-const llvm::MemoryBuffer *Buffer =
-SM.getBuffer(FID, Loc, /*Invalid=*/nullptr);
+llvm::MemoryBufferRef Buffer = SM.getBufferOrFake(FID, Loc);
 
-assert(LocData >= Buffer->getBufferStart() &&
-   LocData < Buffer->getBufferEnd());
+assert(LocData >= Buffer.getBufferStart() &&
+   LocData < Buffer.getBufferEnd());
 
 const char *LineBegin = LocData - LocColumn;
 
-assert(LineBegin >= Buffer->getBufferStart());
+assert(LineBegin >= Buffer.getBufferStart());
 
 const char *LineEnd = nullptr;
 
 for (LineEnd = LineBegin; *LineEnd != '\n' && *LineEnd != '\r' &&
-  LineEnd < Buffer->getBufferEnd();
+  LineEnd < Buffer.getBufferEnd();
  ++LineEnd)
   ;
 
Index: clang/tools/clang-diff/ClangDiff.cpp
===
--- clang/tools/clang-diff/ClangDiff.cpp
+++ clang/tools/clang-diff/ClangDiff.cpp
@@ -284,7 +284,7 @@
   unsigned Begin, End;
   std::tie(Begin, End) = Tree.getSourceRangeOffsets(Node);
   const SourceManager &SrcMgr = Tree.getASTContext().getSourceManager();
-  auto Code = SrcMgr.getBuffer(SrcMgr.getMainFileID())->getBuffer();
+  auto Code = SrcMgr.getBufferOrFake(SrcMgr.getMainFileID()).getBuffer();
   for (; Offset < Begin; ++Offset)
 printHtml(OS, Code[Offset]);
   OS << "getBufferStart();
-  const char *BufferEnd = MemBuffer->getBufferEnd();
+  llvm::MemoryBufferRef MemBuffer = PP.getSourceManager().getBufferOrFake(
+  PP.getSourceManager().getFileID(Loc));
+  const char *Buffer = MemBuffer.getBufferStart();
+  const char *BufferEnd = MemBuffer.getBufferEnd();
   const char *BeginPtr = PP.getSourceManager().getCharacterData(Loc);
   const char *EndPtr = BeginPtr;
   while (BeginPtr > Buffer) {
@@ -338,9 +338,10 @@
 // Retrieve source line from file image given a file ID and line number.
 static std::string getSourceLine(clang::Preprocessor &PP, clang::FileID FileID,
  int Line) {
-  const llvm::MemoryBuffer *MemBuffer = PP.getSourceManager().getBuffer(FileID);
-  con

[PATCH] D88227: [clang-format] Add a SpaceAroundPointerQualifiers style option

2020-10-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88227

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


  1   2   >