[PATCH] D70390: [clang-tidy] new performance-no-automatic-move check.

2019-11-21 Thread Clement Courbet via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG95fe54931fdd: [clang-tidy] new performance-no-automatic-move 
check. (authored by courbet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70390

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.h
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
  clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp
@@ -0,0 +1,92 @@
+// RUN: %check_clang_tidy -std=c++11,c++14,c++17,c++2a %s performance-no-automatic-move %t
+
+struct Obj {
+  Obj();
+  Obj(const Obj &);
+  Obj(Obj &&);
+  virtual ~Obj();
+};
+
+template 
+struct StatusOr {
+  StatusOr(const T &);
+  StatusOr(T &&);
+};
+
+struct NonTemplate {
+  NonTemplate(const Obj &);
+  NonTemplate(Obj &&);
+};
+
+template 
+T Make();
+
+StatusOr PositiveStatusOrConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+NonTemplate PositiveNonTemplateConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+Obj PositiveSelfConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+// FIXME: Ideally we would warn here too.
+NonTemplate PositiveNonTemplateLifetimeExtension() {
+  const Obj  = Make();
+  return obj;
+}
+
+// FIXME: Ideally we would warn here too.
+StatusOr PositiveStatusOrLifetimeExtension() {
+  const Obj  = Make();
+  return obj;
+}
+
+// Negatives.
+
+StatusOr Temporary() {
+  return Make();
+}
+
+StatusOr ConstTemporary() {
+  return Make();
+}
+
+StatusOr Nrvo() {
+  Obj obj = Make();
+  return obj;
+}
+
+StatusOr Ref() {
+  Obj  = Make();
+  return obj;
+}
+
+StatusOr ConstRef() {
+  const Obj  = Make();
+  return obj;
+}
+
+const Obj global;
+
+StatusOr Global() {
+  return global;
+}
+
+struct FromConstRefOnly {
+  FromConstRefOnly(const Obj &);
+};
+
+FromConstRefOnly FromConstRefOnly() {
+  const Obj obj = Make();
+  return obj;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
@@ -0,0 +1,53 @@
+.. title:: clang-tidy - performance-no-automatic-move
+
+performance-no-automatic-move
+=
+
+Finds local variables that cannot be automatically moved due to constness.
+
+Under
+`certain conditions `_,
+local values are automatically moved out when returning from a function. A
+common mistake is to declare local ``lvalue`` variables ``const``, which
+prevents the move.
+
+Example `[1] `_:
+
+.. code-block:: c++
+
+  StatusOr> Cool() {
+std::vector obj = ...;
+return obj;  // calls StatusOr::StatusOr(std::vector&&)
+  }
+  
+  StatusOr> NotCool() {
+const std::vector obj = ...;
+return obj;  // calls `StatusOr::StatusOr(const std::vector&)`
+  }
+
+The former version (``Cool``) should be preferred over the latter (``Uncool``)
+as it will avoid allocations and potentially large memory copies.
+
+Semantics
+-
+
+In the example above, ``StatusOr::StatusOr(T&&)`` have the same semantics as
+long as the copy and move constructors for ``T`` have the same semantics. Note
+that there is no guarantee that ``S::S(T&&)`` and ``S::S(const T&)`` have the
+same semantics for any single ``S``, so we're not providing automated fixes for
+this check, and judgement should be exerted when making the suggested changes.
+
+-Wreturn-std-move
+-
+
+Another case where the move cannot happen is the following:
+
+.. code-block:: c++
+
+  StatusOr> Uncool() {
+std::vector&& obj = ...;
+return obj;  // calls `StatusOr::StatusOr(const std::vector&)`
+  }
+
+In that case the fix is more consensual: just `return std::move(obj)`.
+This is handled by the `-Wreturn-std-move` warning.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst

[clang-tools-extra] 95fe549 - [clang-tidy] new performance-no-automatic-move check.

2019-11-21 Thread Clement Courbet via cfe-commits

Author: Clement Courbet
Date: 2019-11-22T08:47:55+01:00
New Revision: 95fe54931fddf9740b3247219e30504da447

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

LOG: [clang-tidy] new performance-no-automatic-move check.

Summary: The check flags constructs that prevent automatic move of local 
variables.

Reviewers: aaron.ballman

Subscribers: mgorny, xazax.hun, cfe-commits

Tags: #clang

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

Added: 
clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.h
clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp

Modified: 
clang-tools-extra/clang-tidy/performance/CMakeLists.txt
clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
index cde2e246bf9e..d1f9897b0154 100644
--- a/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/performance/CMakeLists.txt
@@ -9,6 +9,7 @@ add_clang_library(clangTidyPerformanceModule
   InefficientVectorOperationCheck.cpp
   MoveConstArgCheck.cpp
   MoveConstructorInitCheck.cpp
+  NoAutomaticMoveCheck.cpp
   NoexceptMoveConstructorCheck.cpp
   PerformanceTidyModule.cpp
   TriviallyDestructibleCheck.cpp

diff  --git a/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
new file mode 100644
index ..d806c98d5c41
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
@@ -0,0 +1,74 @@
+//===--- NoAutomaticMoveCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "NoAutomaticMoveCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace performance {
+
+NoAutomaticMoveCheck::NoAutomaticMoveCheck(StringRef Name,
+   ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  AllowedTypes(
+  utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
+
+void NoAutomaticMoveCheck::registerMatchers(MatchFinder *Finder) {
+  // Automatic move exists only for c++11 onwards.
+  if (!getLangOpts().CPlusPlus11)
+return;
+
+  const auto ConstLocalVariable =
+  varDecl(hasLocalStorage(), unless(hasType(lValueReferenceType())),
+  hasType(qualType(
+  isConstQualified(),
+  hasCanonicalType(matchers::isExpensiveToCopy()),
+  unless(hasDeclaration(namedDecl(
+  matchers::matchesAnyListedName(AllowedTypes)))
+  .bind("vardecl");
+
+  // A matcher for a `DstT::DstT(const Src&)` where DstT also has a
+  // `DstT::DstT(Src&&)`.
+  const auto LValueRefCtor = cxxConstructorDecl(
+  hasParameter(0,
+   hasType(lValueReferenceType(pointee(type().bind("SrcT"),
+  ofClass(cxxRecordDecl(hasMethod(cxxConstructorDecl(
+  hasParameter(0, hasType(rValueReferenceType(
+  pointee(type(equalsBoundNode("SrcT")));
+
+  Finder->addMatcher(
+  returnStmt(
+  hasReturnValue(ignoringElidableConstructorCall(ignoringParenImpCasts(
+  cxxConstructExpr(hasDeclaration(LValueRefCtor),
+   hasArgument(0, 
ignoringParenImpCasts(declRefExpr(
+  to(ConstLocalVariable)
+  .bind("ctor_call"),
+  this);
+}
+
+void NoAutomaticMoveCheck::check(const MatchFinder::MatchResult ) {
+  const auto *Var = Result.Nodes.getNodeAs("vardecl");
+  const auto *CtorCall = Result.Nodes.getNodeAs("ctor_call");
+  diag(CtorCall->getExprLoc(), "constness of '%0' prevents automatic move")
+  << Var->getName();
+}
+
+void NoAutomaticMoveCheck::storeOptions(ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "AllowedTypes",
+utils::options::serializeStringList(AllowedTypes));
+}
+
+} // namespace 

[PATCH] D67508: [RISCV] support mutilib in baremetal environment

2019-11-21 Thread Kuan Hsu Chen (Zakk) via Phabricator via cfe-commits
khchen added a comment.

Re-applied with test fix in 
https://reviews.llvm.org/rG4fccd383d571865321b4723b81c3042d2c15fd80


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67508



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


[PATCH] D70390: [clang-tidy] new performance-no-automatic-move check.

2019-11-21 Thread Clement Courbet via Phabricator via cfe-commits
courbet marked an inline comment as done.
courbet added a comment.

Thanks for the review.




Comment at: clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp:32
+
+  const auto const_local_variable =
+  varDecl(hasLocalStorage(), unless(hasType(lValueReferenceType())),

JonasToth wrote:
> Last nits: all variables do not follow the LLVM convention of camel-casing. 
> Just realized now, sorry
Oh yes right, thanks for the catch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70390



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


[PATCH] D70390: [clang-tidy] new performance-no-automatic-move check.

2019-11-21 Thread Clement Courbet via Phabricator via cfe-commits
courbet updated this revision to Diff 230595.
courbet added a comment.

Use LLVM style


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70390

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.h
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
  clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance-no-automatic-move.cpp
@@ -0,0 +1,92 @@
+// RUN: %check_clang_tidy -std=c++11,c++14,c++17,c++2a %s performance-no-automatic-move %t
+
+struct Obj {
+  Obj();
+  Obj(const Obj &);
+  Obj(Obj &&);
+  virtual ~Obj();
+};
+
+template 
+struct StatusOr {
+  StatusOr(const T &);
+  StatusOr(T &&);
+};
+
+struct NonTemplate {
+  NonTemplate(const Obj &);
+  NonTemplate(Obj &&);
+};
+
+template 
+T Make();
+
+StatusOr PositiveStatusOrConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+NonTemplate PositiveNonTemplateConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+Obj PositiveSelfConstValue() {
+  const Obj obj = Make();
+  return obj;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+}
+
+// FIXME: Ideally we would warn here too.
+NonTemplate PositiveNonTemplateLifetimeExtension() {
+  const Obj  = Make();
+  return obj;
+}
+
+// FIXME: Ideally we would warn here too.
+StatusOr PositiveStatusOrLifetimeExtension() {
+  const Obj  = Make();
+  return obj;
+}
+
+// Negatives.
+
+StatusOr Temporary() {
+  return Make();
+}
+
+StatusOr ConstTemporary() {
+  return Make();
+}
+
+StatusOr Nrvo() {
+  Obj obj = Make();
+  return obj;
+}
+
+StatusOr Ref() {
+  Obj  = Make();
+  return obj;
+}
+
+StatusOr ConstRef() {
+  const Obj  = Make();
+  return obj;
+}
+
+const Obj global;
+
+StatusOr Global() {
+  return global;
+}
+
+struct FromConstRefOnly {
+  FromConstRefOnly(const Obj &);
+};
+
+FromConstRefOnly FromConstRefOnly() {
+  const Obj obj = Make();
+  return obj;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/performance-no-automatic-move.rst
@@ -0,0 +1,53 @@
+.. title:: clang-tidy - performance-no-automatic-move
+
+performance-no-automatic-move
+=
+
+Finds local variables that cannot be automatically moved due to constness.
+
+Under
+`certain conditions `_,
+local values are automatically moved out when returning from a function. A
+common mistake is to declare local ``lvalue`` variables ``const``, which
+prevents the move.
+
+Example `[1] `_:
+
+.. code-block:: c++
+
+  StatusOr> Cool() {
+std::vector obj = ...;
+return obj;  // calls StatusOr::StatusOr(std::vector&&)
+  }
+  
+  StatusOr> NotCool() {
+const std::vector obj = ...;
+return obj;  // calls `StatusOr::StatusOr(const std::vector&)`
+  }
+
+The former version (``Cool``) should be preferred over the latter (``Uncool``)
+as it will avoid allocations and potentially large memory copies.
+
+Semantics
+-
+
+In the example above, ``StatusOr::StatusOr(T&&)`` have the same semantics as
+long as the copy and move constructors for ``T`` have the same semantics. Note
+that there is no guarantee that ``S::S(T&&)`` and ``S::S(const T&)`` have the
+same semantics for any single ``S``, so we're not providing automated fixes for
+this check, and judgement should be exerted when making the suggested changes.
+
+-Wreturn-std-move
+-
+
+Another case where the move cannot happen is the following:
+
+.. code-block:: c++
+
+  StatusOr> Uncool() {
+std::vector&& obj = ...;
+return obj;  // calls `StatusOr::StatusOr(const std::vector&)`
+  }
+
+In that case the fix is more consensual: just `return std::move(obj)`.
+This is handled by the `-Wreturn-std-move` warning.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- 

[PATCH] D70445: [clangd] Show lambda signature for lambda autocompletions

2019-11-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang/lib/Sema/SemaCodeComplete.cpp:3398
+  // parameters.
+  auto AddTemplatedFunctionTypeAndResult = [&](const FunctionTemplateDecl
+   *FunTmpl) {

sammccall wrote:
> I actually think there's no need to modify the "templated function" path at 
> all - you can just take return the templated FunctionDecl from 
> `extractFunctorCallOperator` and treat it as a regular function.
> 
> The template function stuff is about identifying template parameters that 
> need to be spelled, and adding them to the CCS. With generic lambdas the type 
> parameters are always deduced and may not be specified. And this can be 
> assumed the case for general functors as well, as the syntax `Functor f; 
> f();` isn't legal.
Good point! I did that because, as I mentioned earlier, my impression was that 
we would probably want something like `foo(A a, const B ) 
-> B *` (and probably even more complicated things to print dependent types). 
But if we don't want to go that direction, this should not be needed, thanks!


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

https://reviews.llvm.org/D70445



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


[PATCH] D70445: [clangd] Show lambda signature for lambda autocompletions

2019-11-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 230594.
kbobyrev marked 7 inline comments as done.
kbobyrev added a comment.

Simplified the patch to address the comments.


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

https://reviews.llvm.org/D70445

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/test/CodeCompletion/function-templates.cpp
  clang/test/CodeCompletion/lambdas.cpp

Index: clang/test/CodeCompletion/lambdas.cpp
===
--- clang/test/CodeCompletion/lambdas.cpp
+++ clang/test/CodeCompletion/lambdas.cpp
@@ -60,3 +60,17 @@
   // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:57:24 %s -o - | FileCheck -check-prefix=CHECK-8 %s
   // CHECK-8-NOT: COMPLETION: Pattern : [<#=
 }
+
+void test6() {
+  auto my_lambda = [&](int a, double ) { return 1.f; };
+  my_
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:66:5 %s -o - | FileCheck -check-prefix=CHECK-9 %s
+  // CHECK-9: [#float#]my_lambda(<#int a#>, <#double #>)[# const#]
+}
+
+void test7() {
+  auto generic_lambda = [&](auto a, const auto ) { return a + b; };
+  generic_
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:73:10 %s -o - | FileCheck -check-prefix=CHECK-10 %s
+  // CHECK-10: [#auto#]generic_lambda(<#auto a#>, <#const auto #>)[# const#]
+}
Index: clang/test/CodeCompletion/function-templates.cpp
===
--- clang/test/CodeCompletion/function-templates.cpp
+++ clang/test/CodeCompletion/function-templates.cpp
@@ -1,7 +1,7 @@
 namespace std {
   template
   void sort(RandomAccessIterator first, RandomAccessIterator last);
-  
+
   template
   X* dyn_cast(Y *Val);
 }
@@ -11,13 +11,18 @@
   template T ();
 };
 
+template 
+V doSomething(T t, const U , V *v) { return V(); }
+
 void f() {
   std::sort(1, 2);
   Foo().getAs();
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:15:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:18:8 %s -o - | FileCheck -check-prefix=CHECK-CC1 %s
   // CHECK-CC1: dyn_cast<<#class X#>>(<#Y *Val#>)
   // CHECK-CC1: sort(<#RandomAccessIterator first#>, <#RandomAccessIterator last#>
-  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:16:9 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:19:9 %s -o - | FileCheck -check-prefix=CHECK-CC2 %s
   // CHECK-CC2: getAs<<#typename T#>>()
-)
-  
+  doSom
+  // RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:25:8 %s -o - | FileCheck -check-prefix=CHECK-CC3 %s
+  // CHECK-CC3: [#V#]doSomething(<#T t#>, <#const U #>, <#V *v#>)
+}
Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -3315,6 +3315,18 @@
   return Result.TakeString();
 }
 
+// FIXME: Right now this works well with lambdas. Add support for other functor
+// types like std::function.
+static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
+  const auto *VD = dyn_cast(ND);
+  if (!VD)
+return nullptr;
+  const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
+  if (!RecordDecl || !RecordDecl->isLambda())
+return nullptr;
+  return RecordDecl->getLambdaCallOperator();
+}
+
 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
 Preprocessor , ASTContext , CodeCompletionBuilder ,
 bool IncludeBriefComments, const CodeCompletionContext ,
@@ -3339,9 +3351,8 @@
   for (const auto *I : ND->specific_attrs())
 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
 
-  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
-
-  if (const auto *Function = dyn_cast(ND)) {
+  auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
+AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
Ctx, Policy);
 AddTypedNameChunk(Ctx, Policy, ND, Result);
@@ -3349,9 +3360,21 @@
 AddFunctionParameterChunks(PP, Policy, Function, Result);
 Result.AddChunk(CodeCompletionString::CK_RightParen);
 AddFunctionTypeQualsToCompletionString(Result, Function);
+  };
+
+  if (const auto *Function = dyn_cast(ND)) {
+AddFunctionTypeAndResult(Function);
+return Result.TakeString();
+  }
+
+  if (const auto *CallOperator =
+  dyn_cast_or_null(extractFunctorCallOperator(ND))) {
+AddFunctionTypeAndResult(CallOperator);
 return Result.TakeString();
   }
 
+  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
+
   if (const FunctionTemplateDecl *FunTmpl =
   dyn_cast(ND)) {
 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
@@ 

LLVM buildmaster will be updated and restarted soon

2019-11-21 Thread Galina Kistanova via cfe-commits
Hello everyone,

LLVM buildmaster will be updated and restarted in the nearest hour.

Thanks

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


[PATCH] D67537: [clangd] Client-side support for inactive regions

2019-11-21 Thread Nathan Ridge via Phabricator via cfe-commits
nridge marked an inline comment as done.
nridge added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:210
+  isWholeLine: true,
+  // FIXME: Avoid hardcoding these colors.
+  light: {

I'm open to suggestions for how we could avoid harcoding these colors. VSCode 
themes do not seem to include colors for `"meta.disabled"` or any similar scope 
that would fit this role.

Perhaps we can allow the user to define the colors in clangd-specifier setting 
names, e.g. `clangd.inactiveHighlightColor.light`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67537



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


[PATCH] D68720: Support -fstack-clash-protection for x86

2019-11-21 Thread serge via Phabricator via cfe-commits
serge-sans-paille updated this revision to Diff 230494.
serge-sans-paille added a comment.

Added extra test for arch support (warns if the flag is used on unsupported 
targets, and checks it's effectively unused), cc @sylvestre.ledru


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68720

Files:
  clang/docs/ClangCommandLineReference.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/TargetInfo.h
  clang/include/clang/Driver/CC1Options.td
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/stack-clash-protection.c
  clang/test/Driver/stack-clash-protection.c
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/CodeGen/TargetLowering.h
  llvm/lib/Target/X86/X86CallFrameOptimization.cpp
  llvm/lib/Target/X86/X86FrameLowering.cpp
  llvm/lib/Target/X86/X86FrameLowering.h
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/X86ISelLowering.h
  llvm/lib/Target/X86/X86InstrCompiler.td
  llvm/lib/Target/X86/X86InstrInfo.td
  llvm/test/CodeGen/X86/stack-clash-dynamic-alloca.ll
  llvm/test/CodeGen/X86/stack-clash-large.ll
  llvm/test/CodeGen/X86/stack-clash-medium-natural-probes-mutliple-objects.ll
  llvm/test/CodeGen/X86/stack-clash-medium-natural-probes.ll
  llvm/test/CodeGen/X86/stack-clash-medium.ll
  llvm/test/CodeGen/X86/stack-clash-no-free-probe.ll
  llvm/test/CodeGen/X86/stack-clash-small.ll
  llvm/test/CodeGen/X86/stack-clash-unknown-call.ll

Index: llvm/test/CodeGen/X86/stack-clash-unknown-call.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/stack-clash-unknown-call.ll
@@ -0,0 +1,31 @@
+; RUN: llc < %s | FileCheck %s
+
+
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i1 immarg);
+
+define void @foo() local_unnamed_addr #0 {
+
+;CHECK-LABEL: foo:
+;CHECK: # %bb.0:
+;CHECK-NEXT:	subq	$4096, %rsp # imm = 0x1000
+; it's important that we don't use the call as a probe here
+;CHECK-NEXT:	movq	$0, (%rsp)
+;CHECK-NEXT:	subq	$3912, %rsp # imm = 0xF48
+;CHECK-NEXT:	.cfi_def_cfa_offset 8016
+;CHECK-NEXT:	movq	%rsp, %rdi
+;CHECK-NEXT:	movl	$8000, %edx # imm = 0x1F40
+;CHECK-NEXT:	xorl	%esi, %esi
+;CHECK-NEXT:	callq	memset
+;CHECK-NEXT:	addq	$8008, %rsp # imm = 0x1F48
+;CHECK-NEXT:	.cfi_def_cfa_offset 8
+;CHECK-NEXT:	retq
+
+  %a = alloca i8, i64 8000, align 16
+  call void @llvm.memset.p0i8.i64(i8* align 16 %a, i8 0, i64 8000, i1 false)
+  ret void
+}
+
+attributes #0 =  {"probe-stack"="inline-asm"}
Index: llvm/test/CodeGen/X86/stack-clash-small.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/stack-clash-small.ll
@@ -0,0 +1,25 @@
+; RUN: llc < %s | FileCheck %s
+
+
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i32 @foo() local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:  subq	$280, %rsp # imm = 0x118
+; CHECK-NEXT:  .cfi_def_cfa_offset 288
+; CHECK-NEXT:  movl	$1, 264(%rsp)
+; CHECK-NEXT:  movl	-128(%rsp), %eax
+; CHECK-NEXT:  addq	$280, %rsp # imm = 0x118
+; CHECK-NEXT:  .cfi_def_cfa_offset 8
+; CHECK-NEXT:  retq
+
+  %a = alloca i32, i64 100, align 16
+  %b = getelementptr inbounds i32, i32* %a, i64 98
+  store volatile i32 1, i32* %b
+  %c = load volatile i32, i32* %a
+  ret i32 %c
+}
+
+attributes #0 =  {"probe-stack"="inline-asm"}
Index: llvm/test/CodeGen/X86/stack-clash-no-free-probe.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/stack-clash-no-free-probe.ll
@@ -0,0 +1,27 @@
+; RUN: llc < %s | FileCheck %s
+
+target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+define i32 @foo(i64 %i) local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:  subq	$4096, %rsp # imm = 0x1000
+; CHECK-NEXT:  movq	$0, (%rsp)
+; CHECK-NEXT:  subq	$3784, %rsp # imm = 0xEC8
+; CHECK-NEXT:  .cfi_def_cfa_offset 7888
+; CHECK-NEXT:  movl	$1, -128(%rsp,%rdi,4)
+; CHECK-NEXT:  movl	-128(%rsp), %eax
+; CHECK-NEXT:  addq	$7880, %rsp # imm = 0x1EC8
+; CHECK-NEXT:  .cfi_def_cfa_offset 8
+; CHECK-NEXT:  retq
+
+  %a = alloca i32, i32 2000, align 16
+  %b = getelementptr inbounds i32, i32* %a, i64 %i
+  store volatile i32 1, i32* %b
+  %c = load volatile i32, i32* %a
+  ret i32 %c
+}
+
+attributes #0 =  {"probe-stack"="inline-asm"}
+
Index: llvm/test/CodeGen/X86/stack-clash-medium.ll
===

[PATCH] D61446: Generalize the pass registration mechanism used by Polly to any third-party tool

2019-11-21 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

@Meinersbur to make your reviewer job easier, I've setup validation for that 
patch, see https://github.com/serge-sans-paille/llvm-project/pull/2/checks
It build and validates fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D61446



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


[PATCH] D68520: [cmake] Fix clang builds with BUILD_SHARED=ON and CLANG_LINK_CLANG_DYLIB=ON

2019-11-21 Thread Tom Stellard via Phabricator via cfe-commits
tstellar added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68520



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


[clang] a3b22da - [CFG] Fix a flaky crash in CFGBlock::getLastCondition().

2019-11-21 Thread Artem Dergachev via cfe-commits

Author: Artem Dergachev
Date: 2019-11-21T21:55:58-08:00
New Revision: a3b22da4e0ea84ed5890063926b6f54685c23225

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

LOG: [CFG] Fix a flaky crash in CFGBlock::getLastCondition().

Using an end iterator of an empty CFG block was causing
a garbage pointer dereference.

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

Added: 


Modified: 
clang/lib/Analysis/CFG.cpp
clang/test/Analysis/a_flaky_crash.cpp

Removed: 




diff  --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 762b8ecf3439..bc21d1c9076d 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -5879,6 +5879,10 @@ const Expr *CFGBlock::getLastCondition() const {
   if (succ_size() < 2)
 return nullptr;
 
+  // FIXME: Is there a better condition expression we can return in this case?
+  if (size() == 0)
+return nullptr;
+
   auto StmtElem = rbegin()->getAs();
   if (!StmtElem)
 return nullptr;

diff  --git a/clang/test/Analysis/a_flaky_crash.cpp 
b/clang/test/Analysis/a_flaky_crash.cpp
index e0bcc0057467..04bd57883fce 100644
--- a/clang/test/Analysis/a_flaky_crash.cpp
+++ b/clang/test/Analysis/a_flaky_crash.cpp
@@ -1,4 +1,7 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// This code used to crash but unpredictably and rarely.
+// Even with the current set of run-lines, if a buildbot tells you that
+// you broke this test there's a chance that someone else broke it
+// a few commits ago.
 
 struct S {
   S();
@@ -13,3 +16,262 @@ void foo() {
   if (true && bar(S()))
 ++x; // expected-warning{{The expression is an uninitialized value. The 
computed value will also be garbage}}
 }
+
+// 256 copies of the same run-line to make it crash more often when it breaks.
+
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+// RUN: 

[PATCH] D69962: [CFG] Fix a flaky crash in CFGBlock::getLastCondition().

2019-11-21 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-bootstrap-msan/builds/16031
MSan doesn't catch it >.<


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69962



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


[PATCH] D67537: [clangd] Client-side support for inactive regions

2019-11-21 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 230586.
nridge added a comment.

Clean up patch a bit and update tests as well


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67537

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -72,16 +72,25 @@
  semanticHighlighting.SemanticHighlightingLine[]) => {
   // Initialize the scope ranges list to the correct size. Otherwise
   // scopes that don't have any highlightings are missed.
-  let scopeRanges: vscode.Range[][] = scopeTable.map(() => []);
+  let tokenRanges: vscode.Range[][] = scopeTable.map(() => []);
+  let inactiveRanges: vscode.Range[] = [];
   highlightingLines.forEach((line) => {
 line.tokens.forEach((token) => {
-  scopeRanges[token.scopeIndex].push(new vscode.Range(
+  tokenRanges[token.scopeIndex].push(new vscode.Range(
   new vscode.Position(line.line, token.character),
   new vscode.Position(line.line,
   token.character + token.length)));
 });
+if (line.isInactive) {
+  inactiveRanges.push(new vscode.Range(
+new vscode.Position(line.line, 0),
+new vscode.Position(line.line, 0)
+  ));
+}
   });
-  return scopeRanges;
+  let result : semanticHighlighting.DecorationRanges = 
+{ tokenRanges, inactiveRanges };
+  return result;
 };
 
 const fileUri1 = vscode.Uri.parse('file:///file1');
@@ -121,7 +130,8 @@
 tokens : [
   {character : 1, length : 2, scopeIndex : 1},
   {character : 10, length : 2, scopeIndex : 2},
-]
+],
+isInactive: false
   },
   {
 line : 2,
@@ -129,7 +139,8 @@
   {character : 3, length : 2, scopeIndex : 1},
   {character : 6, length : 2, scopeIndex : 1},
   {character : 8, length : 2, scopeIndex : 2},
-]
+],
+isInactive: true
   },
 ];
 
@@ -144,7 +155,8 @@
   line : 1,
   tokens : [
 {character : 2, length : 1, scopeIndex : 0},
-  ]
+  ],
+  isInactive: false
 };
 highlighter.highlight(fileUri2, [ highlightingsInLine1 ]);
 assert.deepEqual(
@@ -167,7 +179,8 @@
 // Closing a text document removes all highlightings for the file and no
 // other files.
 highlighter.removeFileHighlightings(fileUri1);
-assert.deepEqual(highlighter.getDecorationRanges(fileUri1), []);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri1),
+ { tokenRanges: [], inactiveRanges: [] });
 assert.deepEqual(highlighter.getDecorationRanges(fileUri2),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
   });
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -23,6 +23,8 @@
   // with its start position, length and the "lookup table" index of of the
   // semantic highlighting Text Mate scopes.
   tokens?: string;
+  // Whether the line is part of an inactive preprocessor branch.
+  isInactive?: boolean;
 }
 
 // A SemanticHighlightingToken decoded from the base64 data sent by clangd.
@@ -40,6 +42,13 @@
   line: number;
   // All SemanticHighlightingTokens on the line.
   tokens: SemanticHighlightingToken[];
+  // Whether the line is part of an inactive preprocessor branch.
+  isInactive: boolean;
+}
+
+export interface DecorationRanges {
+  tokenRanges: vscode.Range[][],
+  inactiveRanges: vscode.Range[]
 }
 
 // Language server push notification providing the semantic highlighting
@@ -122,7 +131,10 @@
 
   handleNotification(params: SemanticHighlightingParams) {
 const lines: SemanticHighlightingLine[] = params.lines.map(
-(line) => ({line : line.line, tokens : decodeTokens(line.tokens)}));
+  (line) => ({
+line: line.line, tokens: decodeTokens(line.tokens),
+isInactive: line.isInactive || false
+  }));
 this.highlighter.highlight(vscode.Uri.parse(params.textDocument.uri),
lines);
   }
@@ -161,6 +173,7 @@
   // SemanticHighlightingToken with scopeIndex i should have the 

[PATCH] D70157: Align branches within 32-Byte boundary

2019-11-21 Thread Kan Shengchen via Phabricator via cfe-commits
skan marked an inline comment as done.
skan added a comment.

In D70157#1755927 , @jyknight wrote:

> Thanks for the comments, they help a little. But it's still somewhat 
> confusing, so let me write down what seems to be happening:
>
> - Before emitting every instruction, a new MCMachineDependentFragment is now 
> emitted, of one of the multiple types:
>   - For most instructions, that'll be BranchPrefix.
>   - For things that need branch-alignment, it'll be BranchPadding, unless 
> there's a fused conditional before, in which case it's BranchSplit
>   - For fused conditionals, it'll be FusedJccPadding.
> - After emitting an instruction that needs branch-alignment, all of those 
> previously-emitted MCMachineDependentFragment are updated to point to the 
> branch's fragment.
> - Thus, every MCDataFragment now only contains a single instruction (this 
> property is depended upon for getInstSize, at least).
>
>   All the MCMachineDependentFragments in a region bounded by a branch at the 
> end and either a branch or a fragment-type which is not type in {FT_Data, 
> FT_MachineDependent, FT_Relaxable, FT_CompactEncodedInst} at the beginning, 
> will reference the ending branch instruction's fragment.
>
>   Then, when it comes time to do relaxation, every one of those 
> machine-dependent-fragments has the opportunity to grow its instruction a 
> little bit. The first instruction in a "block" will grow up to 5 segment 
> prefixes (via modifying the BranchPrefix fragment), and then if more is 
> needed, more prefixes will be added to the next instruction, and so on. Until 
> you run out of instructions in the region. At which point the BranchPadding 
> or FusedJccPadding types (right before the branch/fused-branch) will be able 
> to emit nops to achieve the desired alignment.
>
>   An alternative would be to simply emit NOPs before branches as needed. That 
> would be substantially simpler, since it would only require special handling 
> for a branch or a fused-branch. I assume things were done this 
> substantially-more-complex way in order to reduce performance cost of 
> inserting NOP instructions? Are there numbers for how much better it is to 
> use segment prefixes, vs a separate nop instruction? It seems a little bit 
> surprising to me that it would be that important, but I don't know...
>
>   I'll note that the method here has the semantic issue of making it 
> effectively impossible to ever evaluate an expression like ".if . - symbol == 
> 24" (assuming we're emitting instructions), since every instruction can now 
> change size. I suspect that will make it impossible to turn this on by 
> default without breaking a lot of assembly code. Previously, only certain 
> instructions, like branches or arithmetic ops with constant arguments of 
> unknown value, could change size.


Thanks for your detailed and accurate analysis for my code! I am sorry that 
this should have been done by me.




Comment at: llvm/lib/MC/MCAssembler.cpp:1058
+/// is the address of the symbol, which would casuse performance regression.
+void MCAssembler::moveSymbol(const MCFragment *Src, MCFragment *Dst) const {
+  if (!(Src && Dst && Dst->getKind() == MCFragment::FT_MachineDependent))

jyknight wrote:
> I don't think this is necessary. AFAICT, the symbols should already be in the 
> right place -- pointing to the relax fragment, not the instruction itself, 
> without this. And removing all this moveSymbol/updateSymbolMap code doesn't 
> make any tests fail.
Yes, I check it and you are right. I will removing all this 
moveSymbol/updateSymbolMap code.


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

https://reviews.llvm.org/D70157



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


[clang] 4fccd38 - [RISCV] Support mutilib in baremetal environment

2019-11-21 Thread Zakk Chen via cfe-commits

Author: Zakk Chen
Date: 2019-11-21T19:58:21-08:00
New Revision: 4fccd383d571865321b4723b81c3042d2c15fd80

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

LOG: [RISCV] Support mutilib in baremetal environment

1. Currently only support the set of multilibs same to riscv-gnu-toolchain.
2. Fix testcase typo causes fail on Windows.
3. Fix testcases to set empty sysroot.

Reviewers: espindola, asb, kito-cheng, lenary

Reviewed By: lenary

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

Added: 

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32i/ilp32/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32i/ilp32/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32iac/ilp32/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32iac/ilp32/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32im/ilp32/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32im/ilp32/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imafc/ilp32f/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imafc/ilp32f/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imafdc/lp64d/crtbegin.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imafdc/lp64d/crtend.o
clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/bin/ld

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv32i/ilp32/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv32iac/ilp32/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv32im/ilp32/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv32imac/ilp32/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv32imafc/ilp32f/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o

clang/test/Driver/Inputs/multilib_riscv_elf_sdk/riscv64-unknown-elf/lib/rv64imafdc/lp64d/crt0.o

Modified: 
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/RISCVToolchain.cpp
clang/test/Driver/riscv32-toolchain.c
clang/test/Driver/riscv64-toolchain.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 2dd3450dd1ba..eb84a99a16b7 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -1503,9 +1503,65 @@ static bool findMSP430Multilibs(const Driver ,
   return false;
 }
 
+static void findRISCVBareMetalMultilibs(const Driver ,
+const llvm::Triple ,
+StringRef Path, const ArgList ,
+DetectedMultilibs ) {
+  FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS());
+  struct RiscvMultilib {
+StringRef march;
+StringRef mabi;
+  };
+  // currently only support the set of multilibs like riscv-gnu-toolchain does.
+  // TODO: support MULTILIB_REUSE
+  SmallVector RISCVMultilibSet = {
+  {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"},
+  {"rv32imac", "ilp32"},  {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"},
+  {"rv64imafdc", "lp64d"}};
+
+  std::vector Ms;
+  for (auto Element : RISCVMultilibSet) {
+// multilib path rule is ${march}/${mabi}
+Ms.emplace_back(
+makeMultilib((Twine(Element.march) + "/" + Twine(Element.mabi)).str())
+.flag(Twine("+march=", Element.march).str())
+.flag(Twine("+mabi=", Element.mabi).str()));
+  }
+  MultilibSet RISCVMultilibs =
+  MultilibSet()
+  

[PATCH] D69180: [Format] Add format check for coroutine keywords with negative numbers

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache accepted this revision.
modocache added a comment.
This revision is now accepted and ready to land.

LGTM! Let me know if you'd like me to commit this change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69180



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


[PATCH] D62035: [AST] const-ify ObjC inherited class search

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache abandoned this revision.
modocache added a comment.

I'm not super interested in this patch anymore, someone else feel free to work 
on this! :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D62035



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


[PATCH] D59765: [Lex] Warn about invisible Hangul whitespace

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache abandoned this revision.
modocache added a comment.

I'm not super interested in this patch anymore, someone else feel free to work 
on this! :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D59765



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


[PATCH] D69022: [coroutines] Remove assert on CoroutineParameterMoves in Sema::buildCoroutineParameterMoves

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache accepted this revision.
modocache added a comment.
This revision is now accepted and ready to land.

LGTM, thanks! Please let me know if you'd like me to commit this change.


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

https://reviews.llvm.org/D69022



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


[PATCH] D69022: [coroutines] Remove assert on CoroutineParameterMoves in Sema::buildCoroutineParameterMoves

2019-11-21 Thread JunMa via Phabricator via cfe-commits
junparser added a comment.

In D69022#1755636 , @modocache wrote:

> Sorry for the slow response here, @junparser!
>
> The test case you came up with here is great! I can see the issue is that 
> `ScopeInfo->CoroutineParameterMoves` are built up when Clang parses the first 
> `co_await a`, but are not cleared when `lookupPromiseType` results in an 
> error. As a result, when Clang hits the second `co_await a`, it's in a state 
> that the current code didn't anticipate. Your test case does a great job 
> demonstrating this. Your fix for the problem also looks good to me! My only 
> suggestion is to make the test case just a little clearer, as I'll explain...
>
> (Also, in the future could you please upload your patches with full context? 
> You can read https://llvm.org/docs/Phabricator.html for more details. I think 
> the section explaining the web interface might be relevant to you, where it 
> suggests `git show HEAD -U99 > mypatch.patch`. The reason I ask is 
> because on Phabricator I can see what lines you're proposing should be added, 
> but not the surrounding source lines, which made this more difficult to 
> review.)


Thanks so much for reviewing the patch and giving the helpful advise.


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

https://reviews.llvm.org/D69022



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


[PATCH] D69022: [coroutines] Remove assert on CoroutineParameterMoves in Sema::buildCoroutineParameterMoves

2019-11-21 Thread JunMa via Phabricator via cfe-commits
junparser updated this revision to Diff 230581.
junparser added a comment.

update as @modocache's suggestion


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

https://reviews.llvm.org/D69022

Files:
  clang/lib/Sema/SemaCoroutine.cpp
  clang/test/SemaCXX/coroutines.cpp


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -87,6 +87,11 @@
   co_await a;
 }
 
+int no_promise_type_multiple_awaits(int) { // expected-error {{this function 
cannot be a coroutine: 'std::experimental::coroutine_traits' has no 
member named 'promise_type'}}
+  co_await a;
+  co_await a;
+}
+
 template <>
 struct std::experimental::coroutine_traits { typedef int 
promise_type; };
 double bad_promise_type(double) { // expected-error {{this function cannot be 
a coroutine: 'experimental::coroutine_traits::promise_type' 
(aka 'int') is not a class}}
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1527,8 +1527,8 @@
   auto *FD = cast(CurContext);
 
   auto *ScopeInfo = getCurFunction();
-  assert(ScopeInfo->CoroutineParameterMoves.empty() &&
- "Should not build parameter moves twice");
+  if (!ScopeInfo->CoroutineParameterMoves.empty())
+return false;
 
   for (auto *PD : FD->parameters()) {
 if (PD->getType()->isDependentType())


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -87,6 +87,11 @@
   co_await a;
 }
 
+int no_promise_type_multiple_awaits(int) { // expected-error {{this function cannot be a coroutine: 'std::experimental::coroutine_traits' has no member named 'promise_type'}}
+  co_await a;
+  co_await a;
+}
+
 template <>
 struct std::experimental::coroutine_traits { typedef int promise_type; };
 double bad_promise_type(double) { // expected-error {{this function cannot be a coroutine: 'experimental::coroutine_traits::promise_type' (aka 'int') is not a class}}
Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -1527,8 +1527,8 @@
   auto *FD = cast(CurContext);
 
   auto *ScopeInfo = getCurFunction();
-  assert(ScopeInfo->CoroutineParameterMoves.empty() &&
- "Should not build parameter moves twice");
+  if (!ScopeInfo->CoroutineParameterMoves.empty())
+return false;
 
   for (auto *PD : FD->parameters()) {
 if (PD->getType()->isDependentType())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f7170d1 - clang/Modules: Move Serialization/Module.{h, cpp} to ModuleFile, NFC

2019-11-21 Thread Duncan P. N. Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2019-11-21T19:07:00-08:00
New Revision: f7170d17a846cd67d70884ba168fd0fad63549ea

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

LOG: clang/Modules: Move Serialization/Module.{h,cpp} to ModuleFile, NFC

Remove some cognitive load by renaming clang/Serialization/Module.h to
clang/Serialization/ModuleFile.h, since it declares the ModuleFile
class.  This also makes editing a bit easier, since the basename of the
file no long conflicts with clang/Basic/Module.h, which declares the
Module class.  Also move lib/Serialization/Module.cpp to
lib/Serialization/ModuleFile.cpp.

Added: 
clang/include/clang/Serialization/ModuleFile.h
clang/lib/Serialization/ModuleFile.cpp

Modified: 
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ModuleManager.h
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/Rewrite/FrontendActions.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/CMakeLists.txt
clang/lib/Serialization/GlobalModuleIndex.cpp
clang/lib/Serialization/ModuleManager.cpp

Removed: 
clang/include/clang/Serialization/Module.h
clang/lib/Serialization/Module.cpp



diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 2b2010f583d5..f0b5e9933823 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -36,7 +36,7 @@
 #include "clang/Sema/IdentifierResolver.h"
 #include "clang/Serialization/ASTBitCodes.h"
 #include "clang/Serialization/ContinuousRangeMap.h"
-#include "clang/Serialization/Module.h"
+#include "clang/Serialization/ModuleFile.h"
 #include "clang/Serialization/ModuleFileExtension.h"
 #include "clang/Serialization/ModuleManager.h"
 #include "llvm/ADT/APFloat.h"

diff  --git a/clang/include/clang/Serialization/Module.h 
b/clang/include/clang/Serialization/ModuleFile.h
similarity index 98%
rename from clang/include/clang/Serialization/Module.h
rename to clang/include/clang/Serialization/ModuleFile.h
index b5afdf90c6af..8f3eb0220637 100644
--- a/clang/include/clang/Serialization/Module.h
+++ b/clang/include/clang/Serialization/ModuleFile.h
@@ -1,4 +1,4 @@
-//===- Module.h - Module description *- C++ 
-*-===//
+//===- ModuleFile.h - Module file description ---*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -11,8 +11,8 @@
 //
 
//===--===//
 
-#ifndef LLVM_CLANG_SERIALIZATION_MODULE_H
-#define LLVM_CLANG_SERIALIZATION_MODULE_H
+#ifndef LLVM_CLANG_SERIALIZATION_MODULEFILE_H
+#define LLVM_CLANG_SERIALIZATION_MODULEFILE_H
 
 #include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
@@ -489,4 +489,4 @@ class ModuleFile {
 
 } // namespace clang
 
-#endif // LLVM_CLANG_SERIALIZATION_MODULE_H
+#endif // LLVM_CLANG_SERIALIZATION_MODULEFILE_H

diff  --git a/clang/include/clang/Serialization/ModuleManager.h 
b/clang/include/clang/Serialization/ModuleManager.h
index 5f20fd7d2eca..15ddb9875ff1 100644
--- a/clang/include/clang/Serialization/ModuleManager.h
+++ b/clang/include/clang/Serialization/ModuleManager.h
@@ -17,7 +17,7 @@
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
-#include "clang/Serialization/Module.h"
+#include "clang/Serialization/ModuleFile.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/STLExtras.h"

diff  --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index f5e291b7fe17..20f71ed1c411 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -61,7 +61,7 @@
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Serialization/ContinuousRangeMap.h"
 #include "clang/Serialization/InMemoryModuleCache.h"
-#include "clang/Serialization/Module.h"
+#include "clang/Serialization/ModuleFile.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"

diff  --git a/clang/lib/Frontend/Rewrite/FrontendActions.cpp 
b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
index 549b86edebcd..6b6a60869ccc 100644
--- a/clang/lib/Frontend/Rewrite/FrontendActions.cpp
+++ b/clang/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -21,7 +21,7 @@
 #include "clang/Rewrite/Frontend/FixItRewriter.h"
 #include "clang/Rewrite/Frontend/Rewriters.h"
 #include "clang/Serialization/ASTReader.h"
-#include "clang/Serialization/Module.h"

[PATCH] D70158: [analyzer] Fix Objective-C accessor body farms after D68108.

2019-11-21 Thread Artem Dergachev via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0b58b80edb81: [analyzer] Fix Objective-C accessor body farms 
after 2073dd2d. (authored by dergachev.a).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70158

Files:
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/StaticAnalyzer/Core/CallEvent.cpp
  clang/test/Analysis/Inputs/expected-plists/nullability-notes.m.plist
  clang/test/Analysis/nullability-notes.m
  clang/test/Analysis/properties.m

Index: clang/test/Analysis/properties.m
===
--- clang/test/Analysis/properties.m
+++ clang/test/Analysis/properties.m
@@ -3,6 +3,8 @@
 
 void clang_analyzer_eval(int);
 
+#define nil ((id)0)
+
 typedef const void * CFTypeRef;
 extern CFTypeRef CFRetain(CFTypeRef cf);
 void CFRelease(CFTypeRef cf);
@@ -1040,3 +1042,48 @@
 	clang_analyzer_eval(self.still_no_custom_accessor == self.still_no_custom_accessor); // expected-warning{{TRUE}}
 }
 @end
+
+@interface Shadowed
+@property (assign) NSObject *o;
+- (NSObject *)getShadowedIvar;
+- (void)clearShadowedIvar;
+- (NSObject *)getShadowedProp;
+- (void)clearShadowedProp;
+@end
+
+@implementation Shadowed
+- (NSObject *)getShadowedIvar {
+  return self->_o;
+}
+- (void)clearShadowedIvar {
+  self->_o = nil;
+}
+- (NSObject *)getShadowedProp {
+  return self.o;
+}
+- (void)clearShadowedProp {
+  self.o = nil;
+}
+@end
+
+@interface Shadowing : Shadowed
+@end
+
+@implementation Shadowing
+// Property 'o' is declared in the superclass but synthesized here.
+// This creates a separate ivar that shadows the superclass's ivar,
+// but the old ivar is still accessible from the methods of the superclass.
+// The old property, however, is not accessible with the property syntax
+// even from the superclass methods.
+@synthesize o;
+
+-(void)testPropertyShadowing {
+  NSObject *oo = self.o;
+  clang_analyzer_eval(self.o == oo); // expected-warning{{TRUE}}
+  clang_analyzer_eval([self getShadowedIvar] == oo); // expected-warning{{UNKNOWN}}
+  [self clearShadowedIvar];
+  clang_analyzer_eval(self.o == oo); // expected-warning{{TRUE}}
+  clang_analyzer_eval([self getShadowedIvar] == oo); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval([self getShadowedIvar] == nil); // expected-warning{{TRUE}}
+}
+@end
Index: clang/test/Analysis/nullability-notes.m
===
--- clang/test/Analysis/nullability-notes.m
+++ clang/test/Analysis/nullability-notes.m
@@ -1,6 +1,22 @@
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core,nullability.NullPassedToNonnull,nullability.NullReturnedFromNonnull,nullability.NullablePassedToNonnull,nullability.NullableReturnedFromNonnull,nullability.NullableDereferenced -analyzer-output=text -verify %s
-// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core,nullability.NullPassedToNonnull,nullability.NullReturnedFromNonnull,nullability.NullablePassedToNonnull,nullability.NullableReturnedFromNonnull,nullability.NullableDereferenced -analyzer-output=plist -o %t.plist %s
-// RUN: %normalize_plist <%t.plist | diff -ub %S/Inputs/expected-plists/nullability-notes.m.plist -
+// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core \
+// RUN:   -analyzer-checker=nullability.NullPassedToNonnull \
+// RUN:   -analyzer-checker=nullability.NullReturnedFromNonnull \
+// RUN:   -analyzer-checker=nullability.NullablePassedToNonnull \
+// RUN:   -analyzer-checker=nullability.NullableReturnedFromNonnull \
+// RUN:   -analyzer-checker=nullability.NullableDereferenced \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-output=text -verify %s
+// RUN: %clang_analyze_cc1 -fblocks -analyzer-checker=core \
+// RUN:   -analyzer-checker=nullability.NullPassedToNonnull \
+// RUN:   -analyzer-checker=nullability.NullReturnedFromNonnull \
+// RUN:   -analyzer-checker=nullability.NullablePassedToNonnull \
+// RUN:   -analyzer-checker=nullability.NullableReturnedFromNonnull \
+// RUN:   -analyzer-checker=nullability.NullableDereferenced \
+// RUN:   -analyzer-output=plist -o %t.plist %s
+// RUN: %normalize_plist <%t.plist \
+// RUN:   | diff -ub %S/Inputs/expected-plists/nullability-notes.m.plist -
+
+void clang_analyzer_warnOnDeadSymbol(id);
 
 #include "Inputs/system-header-simulator-for-nullability.h"
 
@@ -12,8 +28,11 @@
 @end;
 @implementation ClassWithProperties
 -(void) method {
+  clang_analyzer_warnOnDeadSymbol(self);
   // no-crash
   NSObject *x = self.x; // expected-note{{Nullability 'nullable' is inferred}}
+// expected-warning@-1{{SYMBOL DEAD}}
+// expected-note@-2   {{SYMBOL DEAD}}
   takesNonnull(x); // expected-warning{{Nullable pointer is passed to a callee that requires a non-null 1st parameter}}
// 

[PATCH] D70150: [analyzer] Don't clean up dead symbols from constraints twice.

2019-11-21 Thread Artem Dergachev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbbc8662db154: [analyzer] NFC: Dont clean up range 
constraints twice. (authored by dergachev.a).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70150

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
  clang/lib/StaticAnalyzer/Core/ProgramState.cpp


Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -91,10 +91,9 @@
 I->second.second(I->second.first);
 }
 
-ProgramStateRef
-ProgramStateManager::removeDeadBindings(ProgramStateRef state,
-   const StackFrameContext *LCtx,
-   SymbolReaper& SymReaper) {
+ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
+ProgramStateRef state, const StackFrameContext *LCtx,
+SymbolReaper ) {
 
   // This code essentially performs a "mark-and-sweep" of the VariableBindings.
   // The roots are any Block-level exprs and Decls that our liveness algorithm
@@ -112,8 +111,7 @@
   NewState.setStore(newStore);
   SymReaper.setReapedStore(newStore);
 
-  ProgramStateRef Result = getPersistentState(NewState);
-  return ConstraintMgr->removeDeadBindings(Result, SymReaper);
+  return getPersistentState(NewState);
 }
 
 ProgramStateRef ProgramState::bindLoc(Loc LV,
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -728,7 +728,8 @@
   // Create a state in which dead bindings are removed from the environment
   // and the store. TODO: The function should just return new env and store,
   // not a new state.
-  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
+  CleanedState = StateMgr.removeDeadBindingsFromEnvironmentAndStore(
+  CleanedState, SFC, SymReaper);
 
   // Process any special transfer function for dead symbols.
   // A tag to track convenience transitions, which can be removed at cleanup.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -533,9 +533,10 @@
   ConstraintManager () { return *ConstraintMgr; }
   SubEngine () { return *Eng; }
 
-  ProgramStateRef removeDeadBindings(ProgramStateRef St,
-const StackFrameContext *LCtx,
-SymbolReaper& SymReaper);
+  ProgramStateRef
+  removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St,
+const StackFrameContext *LCtx,
+SymbolReaper );
 
 public:
 


Index: clang/lib/StaticAnalyzer/Core/ProgramState.cpp
===
--- clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -91,10 +91,9 @@
 I->second.second(I->second.first);
 }
 
-ProgramStateRef
-ProgramStateManager::removeDeadBindings(ProgramStateRef state,
-   const StackFrameContext *LCtx,
-   SymbolReaper& SymReaper) {
+ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
+ProgramStateRef state, const StackFrameContext *LCtx,
+SymbolReaper ) {
 
   // This code essentially performs a "mark-and-sweep" of the VariableBindings.
   // The roots are any Block-level exprs and Decls that our liveness algorithm
@@ -112,8 +111,7 @@
   NewState.setStore(newStore);
   SymReaper.setReapedStore(newStore);
 
-  ProgramStateRef Result = getPersistentState(NewState);
-  return ConstraintMgr->removeDeadBindings(Result, SymReaper);
+  return getPersistentState(NewState);
 }
 
 ProgramStateRef ProgramState::bindLoc(Loc LV,
Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -728,7 +728,8 @@
   // Create a state in which dead bindings are removed from the environment
   // and the store. TODO: The function should just return new env and store,
   // not a new state.
-  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
+  CleanedState = StateMgr.removeDeadBindingsFromEnvironmentAndStore(
+  CleanedState, SFC, SymReaper);
 
   // Process any special transfer function for dead symbols.
 

[clang] 0b58b80 - [analyzer] Fix Objective-C accessor body farms after 2073dd2d.

2019-11-21 Thread Artem Dergachev via cfe-commits

Author: Artem Dergachev
Date: 2019-11-21T18:59:46-08:00
New Revision: 0b58b80edb81bf8fb401f8a6e057ca9d50abc0f7

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

LOG: [analyzer] Fix Objective-C accessor body farms after 2073dd2d.

Fix a canonicalization problem for the newly added property accessor stubs that
was causing a wrong decl to be used for 'self' in the accessor's body farm.

Fix a crash when constructing a body farm for accessors of a property
that is declared and @synthesize'd in different (but related) interfaces.

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

Added: 


Modified: 
clang/lib/Analysis/BodyFarm.cpp
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/test/Analysis/Inputs/expected-plists/nullability-notes.m.plist
clang/test/Analysis/nullability-notes.m
clang/test/Analysis/properties.m

Removed: 




diff  --git a/clang/lib/Analysis/BodyFarm.cpp b/clang/lib/Analysis/BodyFarm.cpp
index be065ed9330f..694913b3ac93 100644
--- a/clang/lib/Analysis/BodyFarm.cpp
+++ b/clang/lib/Analysis/BodyFarm.cpp
@@ -737,50 +737,65 @@ static const ObjCIvarDecl *findBackingIvar(const 
ObjCPropertyDecl *Prop) {
 }
 
 static Stmt *createObjCPropertyGetter(ASTContext ,
-  const ObjCPropertyDecl *Prop) {
-  // First, find the backing ivar.
-  const ObjCIvarDecl *IVar = findBackingIvar(Prop);
-  if (!IVar)
-return nullptr;
+  const ObjCMethodDecl *MD) {
+// First, find the backing ivar.
+  const ObjCIvarDecl *IVar = nullptr;
+
+  // Property accessor stubs sometimes do not correspond to any property.
+  if (MD->isSynthesizedAccessorStub()) {
+const ObjCInterfaceDecl *IntD = MD->getClassInterface();
+const ObjCImplementationDecl *ImpD = IntD->getImplementation();
+for (const auto *V: ImpD->ivars()) {
+  if (V->getName() == MD->getSelector().getNameForSlot(0))
+IVar = V;
+}
+  }
 
-  // Ignore weak variables, which have special behavior.
-  if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
-return nullptr;
+  if (!IVar) {
+const ObjCPropertyDecl *Prop = MD->findPropertyDecl();
+IVar = findBackingIvar(Prop);
+if (!IVar)
+  return nullptr;
+
+// Ignore weak variables, which have special behavior.
+if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
+  return nullptr;
 
-  // Look to see if Sema has synthesized a body for us. This happens in
-  // Objective-C++ because the return value may be a C++ class type with a
-  // non-trivial copy constructor. We can only do this if we can find the
-  // @synthesize for this property, though (or if we know it's been auto-
-  // synthesized).
-  const ObjCImplementationDecl *ImplDecl =
-IVar->getContainingInterface()->getImplementation();
-  if (ImplDecl) {
-for (const auto *I : ImplDecl->property_impls()) {
-  if (I->getPropertyDecl() != Prop)
-continue;
-
-  if (I->getGetterCXXConstructor()) {
-ASTMaker M(Ctx);
-return M.makeReturn(I->getGetterCXXConstructor());
+// Look to see if Sema has synthesized a body for us. This happens in
+// Objective-C++ because the return value may be a C++ class type with a
+// non-trivial copy constructor. We can only do this if we can find the
+// @synthesize for this property, though (or if we know it's been auto-
+// synthesized).
+const ObjCImplementationDecl *ImplDecl =
+  IVar->getContainingInterface()->getImplementation();
+if (ImplDecl) {
+  for (const auto *I : ImplDecl->property_impls()) {
+if (I->getPropertyDecl() != Prop)
+  continue;
+
+if (I->getGetterCXXConstructor()) {
+  ASTMaker M(Ctx);
+  return M.makeReturn(I->getGetterCXXConstructor());
+}
   }
 }
-  }
 
-  // Sanity check that the property is the same type as the ivar, or a
-  // reference to it, and that it is either an object pointer or trivially
-  // copyable.
-  if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
-  Prop->getType().getNonReferenceType()))
-return nullptr;
-  if (!IVar->getType()->isObjCLifetimeType() &&
-  !IVar->getType().isTriviallyCopyableType(Ctx))
-return nullptr;
+// Sanity check that the property is the same type as the ivar, or a
+// reference to it, and that it is either an object pointer or trivially
+// copyable.
+if (!Ctx.hasSameUnqualifiedType(IVar->getType(),
+Prop->getType().getNonReferenceType()))
+  return nullptr;
+if (!IVar->getType()->isObjCLifetimeType() &&
+!IVar->getType().isTriviallyCopyableType(Ctx))
+  return nullptr;
+  }
 
   // Generate our body:
   //   

[clang] bbc8662 - [analyzer] NFC: Don't clean up range constraints twice.

2019-11-21 Thread Artem Dergachev via cfe-commits

Author: Artem Dergachev
Date: 2019-11-21T18:59:46-08:00
New Revision: bbc8662db1548f98b1c475cadf6260f9079c11ea

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

LOG: [analyzer] NFC: Don't clean up range constraints twice.

Slightly improves static analysis speed.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
clang/lib/StaticAnalyzer/Core/ProgramState.cpp

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
index 07920790c80a..bdd12a3ffe33 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
@@ -533,9 +533,10 @@ class ProgramStateManager {
   ConstraintManager () { return *ConstraintMgr; }
   SubEngine () { return *Eng; }
 
-  ProgramStateRef removeDeadBindings(ProgramStateRef St,
-const StackFrameContext *LCtx,
-SymbolReaper& SymReaper);
+  ProgramStateRef
+  removeDeadBindingsFromEnvironmentAndStore(ProgramStateRef St,
+const StackFrameContext *LCtx,
+SymbolReaper );
 
 public:
 

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index d63288216220..a2e2eec97683 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -728,7 +728,8 @@ void ExprEngine::removeDead(ExplodedNode *Pred, 
ExplodedNodeSet ,
   // Create a state in which dead bindings are removed from the environment
   // and the store. TODO: The function should just return new env and store,
   // not a new state.
-  CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
+  CleanedState = StateMgr.removeDeadBindingsFromEnvironmentAndStore(
+  CleanedState, SFC, SymReaper);
 
   // Process any special transfer function for dead symbols.
   // A tag to track convenience transitions, which can be removed at cleanup.

diff  --git a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp 
b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
index f50d82de3b28..14006f79fd0f 100644
--- a/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ProgramState.cpp
@@ -91,10 +91,9 @@ ProgramStateManager::~ProgramStateManager() {
 I->second.second(I->second.first);
 }
 
-ProgramStateRef
-ProgramStateManager::removeDeadBindings(ProgramStateRef state,
-   const StackFrameContext *LCtx,
-   SymbolReaper& SymReaper) {
+ProgramStateRef ProgramStateManager::removeDeadBindingsFromEnvironmentAndStore(
+ProgramStateRef state, const StackFrameContext *LCtx,
+SymbolReaper ) {
 
   // This code essentially performs a "mark-and-sweep" of the VariableBindings.
   // The roots are any Block-level exprs and Decls that our liveness algorithm
@@ -112,8 +111,7 @@ ProgramStateManager::removeDeadBindings(ProgramStateRef 
state,
   NewState.setStore(newStore);
   SymReaper.setReapedStore(newStore);
 
-  ProgramStateRef Result = getPersistentState(NewState);
-  return ConstraintMgr->removeDeadBindings(Result, SymReaper);
+  return getPersistentState(NewState);
 }
 
 ProgramStateRef ProgramState::bindLoc(Loc LV,



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


[PATCH] D70351: [clang][WIP][clang-scan-deps] Add an experimental C API.

2019-11-21 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk added inline comments.



Comment at: clang/include/clang-c/Dependencies.h:146
+ */
+typedef struct CXOpaqueDependencyScannerWorker *CXDependencyScannerWorker;
+

It would be simpler if the clients didn't have to worry about the worker?
As far as a user of this lib is concerned, they need to create a shared cache, 
then call scanDeps() in some form with the shared cache and other inputs.

Can we hide the worker inside the implementation? So essentially we create a 
new worker for every invocation (that's assuming worker setup is cheap).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70351



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


[PATCH] D70583: clang/Modules: Rename CompilerInstance::ModuleManager, NFC

2019-11-21 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: Bigcheese, jkorous, rsmith, bruno.
Herald added subscribers: ributzka, kbarton, nemanjai.
dexonsmith added a parent revision: D70556: clang/Modules: Refactor 
CompilerInstance::loadModule, NFC.
Herald added a subscriber: wuzish.

Fix the confusing naming of `CompilerInstance::ModuleManager`.  This is
actually an instance of `ASTReader`, which contains an instance of
`ModuleManager`.  I have to assume there was a point in the past where
they were just one class, but it's been pretty confusing for a while.  I
think it's time to fix it.

The new name is `TheASTReader`; the annoying `The` prefix is so that we
don't shadow the `ASTReader` class.  I tried out `ASTRdr` but that
seemed less clear, and this choice matches `ThePCHContainerOperations`
just a couple of declarations below.

Also rename `CompilerInstance::getModuleManager` and
`CompilerInstance::createModuleManager` to `*ASTReader`, making some
cases of `getModuleManager().getModuleManager()` a little more clear.

I built this on top of https://reviews.llvm.org/D70556 so I don't need to do an 
annoying rebase later.


https://reviews.llvm.org/D70583

Files:
  clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp
  clang/include/clang/Frontend/CompilerInstance.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/Rewrite/FrontendActions.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -97,9 +97,8 @@
   MD.ModulePCMPath = M->getASTFile()->getName();
   MD.ContextHash = MDC.ContextHash;
   serialization::ModuleFile *MF =
-  MDC.Instance.getModuleManager()->getModuleManager().lookup(
-  M->getASTFile());
-  MDC.Instance.getModuleManager()->visitInputFiles(
+  MDC.Instance.getASTReader()->getModuleManager().lookup(M->getASTFile());
+  MDC.Instance.getASTReader()->visitInputFiles(
   *MF, true, true, [&](const serialization::InputFile , bool isSystem) {
 MD.FileDeps.insert(IF.getFile()->getName());
   });
Index: clang/lib/Frontend/Rewrite/FrontendActions.cpp
===
--- clang/lib/Frontend/Rewrite/FrontendActions.cpp
+++ clang/lib/Frontend/Rewrite/FrontendActions.cpp
@@ -220,7 +220,7 @@
   return;
 
 serialization::ModuleFile *MF =
-CI.getModuleManager()->getModuleManager().lookup(*File);
+CI.getASTReader()->getModuleManager().lookup(*File);
 assert(MF && "missing module file for loaded module?");
 
 // Not interested in PCH / preambles.
@@ -293,8 +293,8 @@
   // If we're rewriting imports, set up a listener to track when we import
   // module files.
   if (CI.getPreprocessorOutputOpts().RewriteImports) {
-CI.createModuleManager();
-CI.getModuleManager()->addListener(
+CI.createASTReader();
+CI.getASTReader()->addListener(
 std::make_unique(CI, OutputStream));
   }
 
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -871,9 +871,9 @@
   // extended by an external source.
   if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
   !CI.getASTContext().getExternalSource()) {
-CI.createModuleManager();
-CI.getModuleManager()->setDeserializationListener(DeserialListener,
-DeleteDeserialListener);
+CI.createASTReader();
+CI.getASTReader()->setDeserializationListener(DeserialListener,
+  DeleteDeserialListener);
   }
 }
 
@@ -892,7 +892,7 @@
   } else {
 // FIXME: If this is a problem, recover from it by creating a multiplex
 // source.
-assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
+assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
"modules enabled but created an external source that "
"doesn't support modules");
   }
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -75,7 +75,7 @@
 
 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
   return (BuildGlobalModuleIndex ||
-  (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
+  (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
getFrontendOpts().GenerateGlobalModuleIndex)) &&
  !ModuleBuildFailed;
 }
@@ -135,13 +135,13 @@
   return 

[PATCH] D69962: [CFG] Fix a flaky crash in CFGBlock::getLastCondition().

2019-11-21 Thread Artem Dergachev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6bbca3411b38: [CFG] Add a test for a flaky crash in 
CFGBlock::getLastCondition(). (authored by dergachev.a).

Changed prior to commit:
  https://reviews.llvm.org/D69962?vs=228292=230575#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69962

Files:
  clang/test/Analysis/a_flaky_crash.cpp


Index: clang/test/Analysis/a_flaky_crash.cpp
===
--- /dev/null
+++ clang/test/Analysis/a_flaky_crash.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+struct S {
+  S();
+  ~S();
+};
+
+bool bar(S);
+
+// no-crash during diagnostic construction.
+void foo() {
+  int x;
+  if (true && bar(S()))
+++x; // expected-warning{{The expression is an uninitialized value. The 
computed value will also be garbage}}
+}


Index: clang/test/Analysis/a_flaky_crash.cpp
===
--- /dev/null
+++ clang/test/Analysis/a_flaky_crash.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+struct S {
+  S();
+  ~S();
+};
+
+bool bar(S);
+
+// no-crash during diagnostic construction.
+void foo() {
+  int x;
+  if (true && bar(S()))
+++x; // expected-warning{{The expression is an uninitialized value. The computed value will also be garbage}}
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70158: [analyzer] Fix Objective-C accessor body farms after D68108.

2019-11-21 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

I'll commit in order to get rid of the crash, but i'm open for discussions :)


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

https://reviews.llvm.org/D70158



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


[PATCH] D70576: [Clang] Always set -z now linker option on Fuchsia

2019-11-21 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D70576#1756049 , @leonardchan wrote:

> LGTM. But just to confirm, did you test this on CQ/bots by adding `["now", 
> "-z"]` as linker flags to the `config("compiler")` in Fuchsia + Zircon?


https://fuchsia-review.googlesource.com/c/fuchsia/+/342078


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70576



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


[clang] 6bbca34 - [CFG] Add a test for a flaky crash in CFGBlock::getLastCondition().

2019-11-21 Thread Artem Dergachev via cfe-commits

Author: Artem Dergachev
Date: 2019-11-21T18:11:15-08:00
New Revision: 6bbca3411b3861904c3b302f61d59efa14d4d0b9

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

LOG: [CFG] Add a test for a flaky crash in CFGBlock::getLastCondition().

Push the test separately ahead of time in order to find out whether
our Memory Sanitizer bots will be able to find the problem.

If not, I'll add a much more expensive test that repeats the current
test multiple times in order to show up on normal buildbots.
I really apologize for the potential temporary inconvenience!
I'll commit the fix as soon as I get the signal.

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

Added: 
clang/test/Analysis/a_flaky_crash.cpp

Modified: 


Removed: 




diff  --git a/clang/test/Analysis/a_flaky_crash.cpp 
b/clang/test/Analysis/a_flaky_crash.cpp
new file mode 100644
index ..e0bcc0057467
--- /dev/null
+++ b/clang/test/Analysis/a_flaky_crash.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+struct S {
+  S();
+  ~S();
+};
+
+bool bar(S);
+
+// no-crash during diagnostic construction.
+void foo() {
+  int x;
+  if (true && bar(S()))
+++x; // expected-warning{{The expression is an uninitialized value. The 
computed value will also be garbage}}
+}



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


[PATCH] D70351: [clang][WIP][clang-scan-deps] Add an experimental C API.

2019-11-21 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: clang/include/clang-c/Dependencies.h:205
+ */
+CINDEX_LINKAGE void clang_experimental_DependencyScannerWorker_dispose_v0(
+CXDependencyScannerWorker);

Looks like you have a duplicate declaration of this function, and the prototype 
above is missing the comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70351



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


[PATCH] D70351: [clang][WIP][clang-scan-deps] Add an experimental C API.

2019-11-21 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

I think this patch is missing tests for the C api that use c-index-test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70351



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


[PATCH] D70268: [clang][clang-scan-deps] Aggregate the full dependency information.

2019-11-21 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp:97
+  if (OutputPaths.empty())
+OutputPaths = Opts.Targets;
   Dependencies.push_back(File);

Bigcheese wrote:
> arphaman wrote:
> > What if `Opts.Targets` is empty?
> If I recall correctly, `Opts.Targets` can never be empty. I gets set to 
> `.o` if it would be empty.
What I mean is, what if the client didn't request a dependency file in the 
original compilation command? ScanDeps worker currently has a fake 
`"clang-scan-deps dependency"` target that it adds if the target is empty, but 
I do't think that should be reported as an output file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70268



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


[PATCH] D70571: [Coverage] Emit a gap region to cover switch bodies

2019-11-21 Thread Vedant Kumar via Phabricator via cfe-commits
vsk planned changes to this revision.
vsk marked an inline comment as done.
vsk added a comment.

I'll write something up in the coverage mapping docs. Briefly, though, with 
this change there should be a gap region that covers the entire switch body 
(starting from the '{' in 'switch {', and terminating where the last case ends).




Comment at: clang/test/CoverageMapping/switch.cpp:32
   switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
-nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+nop();  // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:14 -> 
[[@LINE+2]]:10 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7

efriedma wrote:
> I'm not sure I understand the effect here.  Will we show that nop() never 
> executes, or will we not show any coverage information for it?
The report will show an execution count of 0 for that call to nop(). In general 
a gap region's count is selected as the line count when it's the only region 
present in a line.


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

https://reviews.llvm.org/D70571



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


[PATCH] D70575: [Clang] Define Fuchsia C++ABI

2019-11-21 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added a comment.

Could you add a test to show that with a fuchsia target we end up returning 
`this` from constructors + destructors and ensure that this ABI is used?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70575



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


[PATCH] D70576: [Clang] Always set -z now linker option on Fuchsia

2019-11-21 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan accepted this revision.
leonardchan added a comment.
This revision is now accepted and ready to land.

LGTM. But just to confirm, did you test this on CQ/bots by adding `["now", 
"-z"]` as linker flags to the `config("compiler")` in Fuchsia + Zircon?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70576



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


[PATCH] D70579: [coroutines][PR41909] Generalize fix from D62550

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache created this revision.
modocache added reviewers: GorNishanov, rsmith, lewissbaker.
Herald added a subscriber: EricWF.
Herald added a project: clang.

In https://reviews.llvm.org/D62550 @rsmith pointed out that there are
many situations in which a coroutine body statement may be
transformed/rebuilt as part of a template instantiation, and my naive
check whether the coroutine was a generic lambda was insufficient.

This is indeed true, as I've learned by reading more of the
TreeTransform code. Most transformations are written in a way that
doesn't assume the resulting types are not dependent types. So the
assertion in 'TransformCoroutineBodyStmt', that the promise type must no
longer be dependent, is out of place.

This patch removes the assertion, spruces up some code comments, and
adds a test that would have failed with my naive check from
https://reviews.llvm.org/D62550.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70579

Files:
  clang/lib/Sema/TreeTransform.h
  clang/test/SemaCXX/coroutines.cpp


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -726,6 +726,12 @@
   [](auto ) -> coro {
 co_await 24;
   }("argument");
+  [](auto ) ->coro { // expected-warning {{expression 
result unused}}
+[]() -> coro {
+  co_await 36;
+};
+co_await 48;
+  };
 }
 template void ok_generic_lambda_coawait_PR41909(); // expected-note {{in 
instantiation of function template specialization 
'ok_generic_lambda_coawait_PR41909' requested here}}
 
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -7205,8 +7205,12 @@
   // that may fail.
   ScopeInfo->setNeedsCoroutineSuspends(false);
 
-  // The new CoroutinePromise object needs to be built and put into the current
-  // FunctionScopeInfo before any transformations or rebuilding occurs.
+  // We re-build the coroutine promise object (and the coroutine parameters its
+  // type and constructor depend on) based on the types used in our current
+  // function. We must do so, and set it on the current FunctionScopeInfo,
+  // before attempting to transform the other parts of the coroutine body
+  // statement, such as the implicit suspend statements (because those
+  // statements reference the FunctionScopeInfo::CoroutinePromise).
   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
 return StmtError();
   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
@@ -7215,8 +7219,9 @@
   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
   ScopeInfo->CoroutinePromise = Promise;
 
-  // Transform the implicit coroutine statements we built during the initial
-  // parse.
+  // Transform the implicit coroutine statements constructed using dependent
+  // types during the previous parse: initial and final suspensions, the return
+  // object, and others. We also transform the coroutine function's body.
   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
   if (InitSuspend.isInvalid())
 return StmtError();
@@ -7243,17 +7248,13 @@
 return StmtError();
   Builder.ReturnValue = Res.get();
 
+  // If during the previous parse the coroutine still had a dependent promise
+  // statement, we may need to build some implicit coroutine statements
+  // (such as exception and fallthrough handlers) for the first time.
   if (S->hasDependentPromiseType()) {
-// PR41909: We may find a generic coroutine lambda definition within a
-// template function that is being instantiated. In this case, the lambda
-// will have a dependent promise type, until it is used in an expression
-// that creates an instantiation with a non-dependent promise type. We
-// should not assert or build coroutine dependent statements for such a
-// generic lambda.
-auto *MD = dyn_cast_or_null(FD);
-if (!MD || !MD->getParent()->isGenericLambda()) {
-  assert(!Promise->getType()->isDependentType() &&
- "the promise type must no longer be dependent");
+// We can only build these statements, however, if the current promise type
+// is not dependent.
+if (!Promise->getType()->isDependentType()) {
   assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
  !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
  "these nodes should not have been built yet");


Index: clang/test/SemaCXX/coroutines.cpp
===
--- clang/test/SemaCXX/coroutines.cpp
+++ clang/test/SemaCXX/coroutines.cpp
@@ -726,6 +726,12 @@
   [](auto ) -> coro {
 co_await 24;
   }("argument");
+  [](auto ) ->coro { // expected-warning {{expression result unused}}
+[]() -> coro {
+  co_await 36;
+};
+ 

[PATCH] D70157: Align branches within 32-Byte boundary

2019-11-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: llvm/include/llvm/MC/MCFragment.h:684
+  // need to be aligned.
+  static unsigned AlignBoundarySize;
+  // AlignMaxPrefixSize - The maximum size of prefixes per instruction.

Global variables are forbidden in LLVM libraries; there could be multiple 
LLVMContexts in the same process.


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

https://reviews.llvm.org/D70157



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


[PATCH] D70537: [clang] CGDebugInfo asserts `!DT.isNull()` when compiling with debug symbols

2019-11-21 Thread kamlesh kumar via Phabricator via cfe-commits
kamleshbhalui updated this revision to Diff 230569.
kamleshbhalui added a comment.

Added a test.


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

https://reviews.llvm.org/D70537

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/pr42710.cpp


Index: clang/test/CodeGenCXX/pr42710.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr42710.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang %s -S -emit-llvm -g -o - -std=c++17
+// expected-no-diagnostics
+
+struct TypeId
+{
+inline static int counter{};
+
+template
+inline static const auto identifier = counter++;
+
+template
+inline static const auto value = identifier;
+};
+
+int main()
+{
+return TypeId::value;
+}
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1433,6 +1433,9 @@
 if (isa(V))
   continue;
 
+if (isa(V))
+  continue;
+
 // Reuse the existing static member declaration if one exists
 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
 if (MI != StaticDataMemberCache.end()) {


Index: clang/test/CodeGenCXX/pr42710.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/pr42710.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang %s -S -emit-llvm -g -o - -std=c++17
+// expected-no-diagnostics
+
+struct TypeId
+{
+inline static int counter{};
+
+template
+inline static const auto identifier = counter++;
+
+template
+inline static const auto value = identifier;
+};
+
+int main()
+{
+return TypeId::value;
+}
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1433,6 +1433,9 @@
 if (isa(V))
   continue;
 
+if (isa(V))
+  continue;
+
 // Reuse the existing static member declaration if one exists
 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
 if (MI != StaticDataMemberCache.end()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D67536: [clangd] Inactive regions support as an extension to semantic highlighting

2019-11-21 Thread Nathan Ridge via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb2e6c2b9954b: [clangd] Inactive regions support as an 
extension to semantic highlighting (authored by nridge).

Changed prior to commit:
  https://reviews.llvm.org/D67536?vs=230195=230565#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67536

Files:
  clang-tools-extra/clangd/CollectMacros.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/SemanticHighlighting.h
  clang-tools-extra/clangd/test/semantic-highlighting.test
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -140,7 +140,7 @@
   }
   for (auto  : ExpectedLines)
 ExpectedLinePairHighlighting.push_back(
-{LineTokens.first, LineTokens.second});
+{LineTokens.first, LineTokens.second, /*IsInactive = */ false});
 
   std::vector ActualDiffed =
   diffHighlightings(NewTokens, OldTokens);
@@ -493,11 +493,11 @@
 
   #define $Macro[[test]]
   #undef $Macro[[test]]
-  #ifdef $Macro[[test]]
-  #endif
+$InactiveCode[[]]  #ifdef $Macro[[test]]
+$InactiveCode[[]]  #endif
 
-  #if defined($Macro[[test]])
-  #endif
+$InactiveCode[[]]  #if defined($Macro[[test]])
+$InactiveCode[[]]  #endif
 )cpp",
   R"cpp(
   struct $Class[[S]] {
@@ -598,6 +598,33 @@
 $Class[[Foo]]<$TemplateParameter[[TT]], $TemplateParameter[[TTs]]...>
   *$Field[[t]];
   }
+)cpp",
+  // Inactive code highlighting
+  R"cpp(
+  // Code in the preamble.
+  // Inactive lines get an empty InactiveCode token at the beginning.
+$InactiveCode[[]]  #ifdef $Macro[[test]]
+$InactiveCode[[]]  #endif
+
+  // A declaration to cause the preamble to end.
+  int $Variable[[EndPreamble]];
+
+  // Code after the preamble.
+  // Code inside inactive blocks does not get regular highlightings
+  // because it's not part of the AST.
+$InactiveCode[[]]  #ifdef $Macro[[test]]
+$InactiveCode[[]]  int Inactive2;
+$InactiveCode[[]]  #endif
+
+  #ifndef $Macro[[test]]
+  int $Variable[[Active1]];
+  #endif
+
+$InactiveCode[[]]  #ifdef $Macro[[test]]
+$InactiveCode[[]]  int Inactive3;
+$InactiveCode[[]]  #else
+  int $Variable[[Active2]];
+  #endif
 )cpp"};
   for (const auto  : TestCases) {
 checkHighlightings(TestCase);
@@ -665,10 +692,12 @@
{{HighlightingKind::Variable,
  Range{CreatePosition(3, 8), CreatePosition(3, 12)}},
 {HighlightingKind::Function,
- Range{CreatePosition(3, 4), CreatePosition(3, 7),
+ Range{CreatePosition(3, 4), CreatePosition(3, 7)}}},
+   /* IsInactive = */ false},
   {1,
{{HighlightingKind::Variable,
- Range{CreatePosition(1, 1), CreatePosition(1, 5)};
+ Range{CreatePosition(1, 1), CreatePosition(1, 5)}}},
+   /* IsInactive = */ true}};
   std::vector ActualResults =
   toSemanticHighlightingInformation(Tokens);
   std::vector ExpectedResults = {
Index: clang-tools-extra/clangd/test/semantic-highlighting.test
===
--- clang-tools-extra/clangd/test/semantic-highlighting.test
+++ clang-tools-extra/clangd/test/semantic-highlighting.test
@@ -57,6 +57,9 @@
 # CHECK-NEXT:  ],
 # CHECK-NEXT:  [
 # CHECK-NEXT:"entity.name.function.preprocessor.cpp"
+# CHECK-NEXT:  ],
+# CHECK-NEXT:  [
+# CHECK-NEXT:"meta.disabled"
 # CHECK-NEXT:  ]
 # CHECK-NEXT:]
 # CHECK-NEXT:  },
@@ -66,6 +69,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"isInactive": false,
 # CHECK-NEXT:"line": 0,
 # CHECK-NEXT:"tokens": "BAABAAA="
 # CHECK-NEXT:  }
@@ -81,10 +85,12 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"isInactive": false,
 # CHECK-NEXT:"line": 0,
 # CHECK-NEXT:"tokens": "BAABAAA="
 # CHECK-NEXT:  }
 # CHECK-NEXT:  {
+# CHECK-NEXT:"isInactive": false,
 # CHECK-NEXT:"line": 1,
 # CHECK-NEXT:"tokens": "BAABAAA="
 # CHECK-NEXT:  }
@@ -100,6 +106,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"lines": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"isInactive": false,
 # CHECK-NEXT:"line": 1,
 # CHECK-NEXT:"tokens": "BAABAAA="
 # CHECK-NEXT:  }
@@ -115,6 +122,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:

[PATCH] D70500: [WebAssembly] Enable use of wasm-opt and LTO-enabled system libraries

2019-11-21 Thread Dan Gohman via Phabricator via cfe-commits
sunfish added a comment.

In D70500#1756011 , @dschuff wrote:

> WRT the LTO directory name, there's theoretically the danger that someone 
> (e.g. emscripten) could be doing a rolling release of the compiler and get 
> invalidated within a major revision.


The LLVM revision here is the git hash, not the major version, so we should be 
good even if this happens.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70500



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


[clang-tools-extra] b2e6c2b - [clangd] Inactive regions support as an extension to semantic highlighting

2019-11-21 Thread Nathan Ridge via cfe-commits

Author: Nathan Ridge
Date: 2019-11-21T19:40:55-05:00
New Revision: b2e6c2b9954ba9f9b68b8394790f6cae35aea58e

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

LOG: [clangd] Inactive regions support as an extension to semantic highlighting

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

Added: 


Modified: 
clang-tools-extra/clangd/CollectMacros.h
clang-tools-extra/clangd/Protocol.cpp
clang-tools-extra/clangd/Protocol.h
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/SemanticHighlighting.h
clang-tools-extra/clangd/test/semantic-highlighting.test
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CollectMacros.h 
b/clang-tools-extra/clangd/CollectMacros.h
index 17e9917542bd..5c3fca10ad4a 100644
--- a/clang-tools-extra/clangd/CollectMacros.h
+++ b/clang-tools-extra/clangd/CollectMacros.h
@@ -30,6 +30,8 @@ struct MainFileMacros {
   // reference to an undefined macro. Store them separately, e.g. for semantic
   // highlighting.
   std::vector UnknownMacros;
+  // Ranges skipped by the preprocessor due to being inactive.
+  std::vector SkippedRanges;
 };
 
 /// Collects macro references (e.g. definitions, expansions) in the main file.
@@ -78,6 +80,14 @@ class CollectMainFileMacros : public PPCallbacks {
 add(MacroName, MD.getMacroInfo());
   }
 
+  void SourceRangeSkipped(SourceRange R, SourceLocation EndifLoc) override {
+if (!InMainFile)
+  return;
+Position Begin = sourceLocToPosition(SM, R.getBegin());
+Position End = sourceLocToPosition(SM, R.getEnd());
+Out.SkippedRanges.push_back(Range{Begin, End});
+  }
+
 private:
   void add(const Token , const MacroInfo *MI) {
 if (!InMainFile)

diff  --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index bdf284dc502f..25826bd5a11d 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -1063,7 +1063,8 @@ bool operator==(const SemanticHighlightingInformation 
,
 
 llvm::json::Value toJSON(const SemanticHighlightingInformation ) {
   return llvm::json::Object{{"line", Highlighting.Line},
-{"tokens", Highlighting.Tokens}};
+{"tokens", Highlighting.Tokens},
+{"isInactive", Highlighting.IsInactive}};
 }
 
 llvm::json::Value toJSON(const SemanticHighlightingParams ) {

diff  --git a/clang-tools-extra/clangd/Protocol.h 
b/clang-tools-extra/clangd/Protocol.h
index 6540365dccd8..f110292b091b 100644
--- a/clang-tools-extra/clangd/Protocol.h
+++ b/clang-tools-extra/clangd/Protocol.h
@@ -1209,6 +1209,11 @@ struct SemanticHighlightingInformation {
   int Line = 0;
   /// The base64 encoded string of highlighting tokens.
   std::string Tokens;
+  /// Is the line in an inactive preprocessor branch?
+  /// This is a clangd extension.
+  /// An inactive line can still contain highlighting tokens as well;
+  /// clients should combine line style and token style if possible.
+  bool IsInactive = false;
 };
 bool operator==(const SemanticHighlightingInformation ,
 const SemanticHighlightingInformation );

diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 4e47a83d8da0..049afb741b27 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -25,6 +25,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Casting.h"
 #include 
 
@@ -160,7 +161,7 @@ class HighlightingsBuilder {
 Tokens.push_back(HighlightingToken{Kind, *Range});
   }
 
-  std::vector collect() && {
+  std::vector collect(ParsedAST ) && {
 // Initializer lists can give duplicates of tokens, therefore all tokens
 // must be deduplicated.
 llvm::sort(Tokens);
@@ -187,6 +188,22 @@ class HighlightingsBuilder {
   // the end of the Tokens).
   TokRef = TokRef.drop_front(Conflicting.size());
 }
+// Add tokens indicating lines skipped by the preprocessor.
+for (const Range  : AST.getMacros().SkippedRanges) {
+  // Create one token for each line in the skipped range, so it works
+  // with line-based 
diff ing.
+  assert(R.start.line <= R.end.line);
+  for (int Line = R.start.line; Line < R.end.line; ++Line) {
+// Don't bother computing the offset for the end of the line, just use
+// zero. The client will treat this highlighting kind specially, and
+// highlight the entire line visually (i.e. not just to where the text
+// on the line ends, but to the 

[PATCH] D70500: [WebAssembly] Enable use of wasm-opt and LTO-enabled system libraries

2019-11-21 Thread Derek Schuff via Phabricator via cfe-commits
dschuff added a comment.

Also if at some point we are able to remove a bunch of the driver logic from 
emcc and move it here, (e.g. running clang to link instead of lld directly) 
we'll need to watch out for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70500



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


[PATCH] D70500: [WebAssembly] Enable use of wasm-opt and LTO-enabled system libraries

2019-11-21 Thread Derek Schuff via Phabricator via cfe-commits
dschuff accepted this revision.
dschuff added a comment.
This revision is now accepted and ready to land.

WRT the LTO directory name, there's theoretically the danger that someone (e.g. 
emscripten) could be doing a rolling release of the compiler and get 
invalidated within a major revision. But in that case, 1) they should be 
rebuilding their libraries on each release anyway, and 2) last time I checked, 
policy was to make auto-upgrade of bitcode work within a revision. So it's 
probably not a problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70500



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


[PATCH] D70576: [Clang] Always set -z now linker option on Fuchsia

2019-11-21 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added reviewers: leonardchan, mcgrathr.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This should be the default on Fuchsia.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70576

Files:
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  clang/test/Driver/fuchsia.c
  clang/test/Driver/fuchsia.cpp


Index: clang/test/Driver/fuchsia.cpp
===
--- clang/test/Driver/fuchsia.cpp
+++ clang/test/Driver/fuchsia.cpp
@@ -22,7 +22,7 @@
 // CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK: "-internal-isystem" "{{.*[/\\]}}include{{/|}}c++{{/|}}v1"
 // CHECK: "-internal-externc-isystem" "[[SYSROOT]]{{/|}}include"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "now" "-z" "rodynamic" "-z" 
"separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: clang/test/Driver/fuchsia.c
===
--- clang/test/Driver/fuchsia.c
+++ clang/test/Driver/fuchsia.c
@@ -24,7 +24,7 @@
 // CHECK-X86_64: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" 
"separate-loadable-segments"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "now" "-z" "rodynamic" "-z" 
"separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -46,6 +46,9 @@
   // handled somewhere else.
   Args.ClaimAllArgs(options::OPT_w);
 
+  CmdArgs.push_back("-z");
+  CmdArgs.push_back("now");
+
   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
   if (llvm::sys::path::filename(Exec).equals_lower("ld.lld") ||
   llvm::sys::path::stem(Exec).equals_lower("ld.lld")) {


Index: clang/test/Driver/fuchsia.cpp
===
--- clang/test/Driver/fuchsia.cpp
+++ clang/test/Driver/fuchsia.cpp
@@ -22,7 +22,7 @@
 // CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK: "-internal-isystem" "{{.*[/\\]}}include{{/|}}c++{{/|}}v1"
 // CHECK: "-internal-externc-isystem" "[[SYSROOT]]{{/|}}include"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "now" "-z" "rodynamic" "-z" "separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: clang/test/Driver/fuchsia.c
===
--- clang/test/Driver/fuchsia.c
+++ clang/test/Driver/fuchsia.c
@@ -24,7 +24,7 @@
 // CHECK-X86_64: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic" "-z" "separate-loadable-segments"
+// CHECK: {{.*}}ld.lld{{.*}}" "-z" "now" "-z" "rodynamic" "-z" "separate-loadable-segments"
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -46,6 +46,9 @@
   // handled somewhere else.
   Args.ClaimAllArgs(options::OPT_w);
 
+  CmdArgs.push_back("-z");
+  CmdArgs.push_back("now");
+
   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
   if (llvm::sys::path::filename(Exec).equals_lower("ld.lld") ||
   llvm::sys::path::stem(Exec).equals_lower("ld.lld")) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70477: [Clang] Enable RISC-V support for Fuchsia

2019-11-21 Thread Petr Hosek via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
phosek marked an inline comment as done.
Closed by commit rG68a3a3b28130: [Clang] Enable RISC-V support for Fuchsia 
(authored by phosek).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70477

Files:
  clang/cmake/caches/Fuchsia-stage2.cmake
  clang/cmake/caches/Fuchsia.cmake
  clang/lib/Basic/Targets.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/riscv64-fuchsia/libclang_rt.builtins.a
  clang/test/Driver/fuchsia.c
  clang/test/Driver/fuchsia.cpp

Index: clang/test/Driver/fuchsia.cpp
===
--- clang/test/Driver/fuchsia.cpp
+++ clang/test/Driver/fuchsia.cpp
@@ -1,9 +1,22 @@
 // RUN: %clangxx %s -### -no-canonical-prefixes --target=x86_64-fuchsia \
 // RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
-// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 | FileCheck %s
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK,CHECK-X86_64 %s
+// RUN: %clangxx %s -### -no-canonical-prefixes --target=aarch64-fuchsia \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK,CHECK-AARCH64 %s
+// RUN: %clangxx %s -### -no-canonical-prefixes --target=riscv64-fuchsia \
+// RUN: -ccc-install-dir %S/Inputs/basic_fuchsia_tree/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK,CHECK-RISCV64 %s
 // CHECK: {{.*}}clang{{.*}}" "-cc1"
-// CHECK: "-triple" "x86_64-fuchsia"
+// CHECK-X86_64: "-triple" "x86_64-unknown-fuchsia"
+// CHECK-AARCH64: "-triple" "aarch64-unknown-fuchsia"
+// CHECK-RISCV64: "-triple" "riscv64-unknown-fuchsia"
 // CHECK: "-fuse-init-array"
 // CHECK: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
@@ -23,7 +36,9 @@
 // CHECK: "-lc++"
 // CHECK: "-lm"
 // CHECK: "--pop-state"
-// CHECK: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}libclang_rt.builtins.a"
+// CHECK-X86_64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}libclang_rt.builtins.a"
+// CHECK-AARCH64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aarch64-fuchsia{{/|}}libclang_rt.builtins.a"
+// CHECK-RISCV64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}riscv64-fuchsia{{/|}}libclang_rt.builtins.a"
 // CHECK: "-lc"
 // CHECK-NOT: crtend.o
 // CHECK-NOT: crtn.o
Index: clang/test/Driver/fuchsia.c
===
--- clang/test/Driver/fuchsia.c
+++ clang/test/Driver/fuchsia.c
@@ -6,7 +6,14 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
 // RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
 // RUN: | FileCheck -check-prefixes=CHECK,CHECK-AARCH64 %s
+// RUN: %clang %s -### -no-canonical-prefixes --target=riscv64-fuchsia \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: --sysroot=%S/platform -fuse-ld=lld 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK,CHECK-RISCV64 %s
 // CHECK: {{.*}}clang{{.*}}" "-cc1"
+// CHECK-X86_64: "-triple" "x86_64-unknown-fuchsia"
+// CHECK-AARCH64: "-triple" "aarch64-unknown-fuchsia"
+// CHECK-RISCV64: "-triple" "riscv64-unknown-fuchsia"
 // CHECK: "--mrelax-relocations"
 // CHECK: "-munwind-tables"
 // CHECK: "-fuse-init-array"
@@ -29,6 +36,7 @@
 // CHECK: "-L[[SYSROOT]]{{/|}}lib"
 // CHECK-X86_64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}libclang_rt.builtins.a"
 // CHECK-AARCH64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aarch64-fuchsia{{/|}}libclang_rt.builtins.a"
+// CHECK-RISCV64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}riscv64-fuchsia{{/|}}libclang_rt.builtins.a"
 // CHECK: "-lc"
 // CHECK-NOT: crtend.o
 // CHECK-NOT: crtn.o
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -224,7 +224,7 @@
 std::string Fuchsia::ComputeEffectiveClangTriple(const ArgList ,
  types::ID InputType) const {
   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
-  return (Triple.getArchName() + "-" + Triple.getOSName()).str();
+  return Triple.str();
 }
 
 Tool *Fuchsia::buildLinker() const {
@@ -344,9 +344,17 @@
 
 SanitizerMask Fuchsia::getDefaultSanitizers() const {
   SanitizerMask Res;
-  if (getTriple().getArch() == llvm::Triple::aarch64)
+  switch (getTriple().getArch()) 

[PATCH] D70575: [Clang] Define Fuchsia C++ABI

2019-11-21 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added a reviewer: leonardchan.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

It is a modified version of the Itanium ABI. The only change is that
constructors and destructors return 'this'.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70575

Files:
  clang/include/clang/Basic/TargetCXXABI.h
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/CodeGen/ItaniumCXXABI.cpp


Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -487,6 +487,19 @@
   bool shouldRTTIBeUnique() const override { return false; }
 };
 
+class FuchsiaCXXABI final : public ItaniumCXXABI {
+public:
+  explicit FuchsiaCXXABI(CodeGen::CodeGenModule )
+  : ItaniumCXXABI(CGM) {}
+
+private:
+  bool HasThisReturn(GlobalDecl GD) const override {
+return isa(GD.getDecl()) ||
+   (isa(GD.getDecl()) &&
+GD.getDtorType() != Dtor_Deleting);
+  }
+};
+
 class WebAssemblyCXXABI final : public ItaniumCXXABI {
 public:
   explicit WebAssemblyCXXABI(CodeGen::CodeGenModule )
@@ -516,6 +529,9 @@
   case TargetCXXABI::iOS64:
 return new iOS64CXXABI(CGM);
 
+  case TargetCXXABI::Fuchsia:
+return new FuchsiaCXXABI(CGM);
+
   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
   // include the other 32-bit ARM oddities: constructor/destructor return 
values
   // and array cookies.
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -808,6 +808,7 @@
   FuchsiaTargetInfo(const llvm::Triple , const TargetOptions )
   : OSTargetInfo(Triple, Opts) {
 this->MCountName = "__mcount";
+this->TheCXXABI.set(TargetCXXABI::Fuchsia);
   }
 };
 
Index: clang/include/clang/Basic/TargetCXXABI.h
===
--- clang/include/clang/Basic/TargetCXXABI.h
+++ clang/include/clang/Basic/TargetCXXABI.h
@@ -103,6 +103,12 @@
 /// of these details is necessarily final yet.
 WebAssembly,
 
+/// The Fuchsia ABI is a modified version of the Itanium ABI.
+///
+/// The relevant changes from the Itanium ABI are:
+///   - constructors and destructors return 'this', as in ARM.
+Fuchsia,
+
 /// The Microsoft ABI is the ABI used by Microsoft Visual Studio (and
 /// compatible compilers).
 ///


Index: clang/lib/CodeGen/ItaniumCXXABI.cpp
===
--- clang/lib/CodeGen/ItaniumCXXABI.cpp
+++ clang/lib/CodeGen/ItaniumCXXABI.cpp
@@ -487,6 +487,19 @@
   bool shouldRTTIBeUnique() const override { return false; }
 };
 
+class FuchsiaCXXABI final : public ItaniumCXXABI {
+public:
+  explicit FuchsiaCXXABI(CodeGen::CodeGenModule )
+  : ItaniumCXXABI(CGM) {}
+
+private:
+  bool HasThisReturn(GlobalDecl GD) const override {
+return isa(GD.getDecl()) ||
+   (isa(GD.getDecl()) &&
+GD.getDtorType() != Dtor_Deleting);
+  }
+};
+
 class WebAssemblyCXXABI final : public ItaniumCXXABI {
 public:
   explicit WebAssemblyCXXABI(CodeGen::CodeGenModule )
@@ -516,6 +529,9 @@
   case TargetCXXABI::iOS64:
 return new iOS64CXXABI(CGM);
 
+  case TargetCXXABI::Fuchsia:
+return new FuchsiaCXXABI(CGM);
+
   // Note that AArch64 uses the generic ItaniumCXXABI class since it doesn't
   // include the other 32-bit ARM oddities: constructor/destructor return values
   // and array cookies.
Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -808,6 +808,7 @@
   FuchsiaTargetInfo(const llvm::Triple , const TargetOptions )
   : OSTargetInfo(Triple, Opts) {
 this->MCountName = "__mcount";
+this->TheCXXABI.set(TargetCXXABI::Fuchsia);
   }
 };
 
Index: clang/include/clang/Basic/TargetCXXABI.h
===
--- clang/include/clang/Basic/TargetCXXABI.h
+++ clang/include/clang/Basic/TargetCXXABI.h
@@ -103,6 +103,12 @@
 /// of these details is necessarily final yet.
 WebAssembly,
 
+/// The Fuchsia ABI is a modified version of the Itanium ABI.
+///
+/// The relevant changes from the Itanium ABI are:
+///   - constructors and destructors return 'this', as in ARM.
+Fuchsia,
+
 /// The Microsoft ABI is the ABI used by Microsoft Visual Studio (and
 /// compatible compilers).
 ///
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 68a3a3b - [Clang] Enable RISC-V support for Fuchsia

2019-11-21 Thread Petr Hosek via cfe-commits

Author: Petr Hosek
Date: 2019-11-21T16:02:26-08:00
New Revision: 68a3a3b28130ff055159632e8f94ef87fa8cba45

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

LOG: [Clang] Enable RISC-V support for Fuchsia

We don't have a full sysroot yet, so for now we only include compiler
support and compiler-rt builtins, the rest of the runtimes will get
enabled later.

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

Added: 

clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/riscv64-fuchsia/libclang_rt.builtins.a

Modified: 
clang/cmake/caches/Fuchsia-stage2.cmake
clang/cmake/caches/Fuchsia.cmake
clang/lib/Basic/Targets.cpp
clang/lib/Driver/ToolChains/Fuchsia.cpp
clang/test/Driver/fuchsia.c
clang/test/Driver/fuchsia.cpp

Removed: 




diff  --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index 9fdf147fd395..a1ae83bdea0e 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -1,6 +1,6 @@
 # This file sets up a CMakeCache for the second stage of a Fuchsia toolchain 
build.
 
-set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64 CACHE STRING "")
+set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64;RISCV CACHE STRING "")
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 
@@ -106,13 +106,14 @@ endforeach()
 if(FUCHSIA_SDK)
   set(FUCHSIA_aarch64_NAME arm64)
   set(FUCHSIA_x86_64_NAME x64)
-  foreach(target x86_64;aarch64)
+  set(FUCHSIA_riscv64_NAME riscv64)
+  foreach(target x86_64;aarch64;riscv64)
 set(FUCHSIA_${target}_COMPILER_FLAGS "-I${FUCHSIA_SDK}/pkg/fdio/include")
 set(FUCHSIA_${target}_LINKER_FLAGS 
"-L${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/lib")
 set(FUCHSIA_${target}_SYSROOT 
"${FUCHSIA_SDK}/arch/${FUCHSIA_${target}_NAME}/sysroot")
   endforeach()
 
-  foreach(target x86_64;aarch64)
+  foreach(target x86_64;aarch64;riscv64)
 # Set the per-target builtins options.
 list(APPEND BUILTIN_TARGETS "${target}-unknown-fuchsia")
 set(BUILTINS_${target}-unknown-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE 
STRING "")
@@ -124,7 +125,9 @@ if(FUCHSIA_SDK)
 set(BUILTINS_${target}-unknown-fuchsia_CMAKE_MODULE_LINKER_FLAGS 
${FUCHSIA_${target}_LINKER_FLAGS} CACHE STRING "")
 set(BUILTINS_${target}-unknown-fuchsia_CMAKE_EXE_LINKER_FLAGS 
${FUCHSIA_${target}_LINKER_FLAGS} CACHE STRING "")
 set(BUILTINS_${target}-unknown-fuchsia_CMAKE_SYSROOT 
${FUCHSIA_${target}_SYSROOT} CACHE PATH "")
+  endforeach()
 
+  foreach(target x86_64;aarch64)
 # Set the per-target runtimes options.
 list(APPEND RUNTIME_TARGETS "${target}-unknown-fuchsia")
 set(RUNTIMES_${target}-unknown-fuchsia_CMAKE_SYSTEM_NAME Fuchsia CACHE 
STRING "")

diff  --git a/clang/cmake/caches/Fuchsia.cmake 
b/clang/cmake/caches/Fuchsia.cmake
index 607bf0b0776d..97e272db4aa3 100644
--- a/clang/cmake/caches/Fuchsia.cmake
+++ b/clang/cmake/caches/Fuchsia.cmake
@@ -1,6 +1,6 @@
 # This file sets up a CMakeCache for a Fuchsia toolchain build.
 
-set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64 CACHE STRING "")
+set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64;RISCV CACHE STRING "")
 
 set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 

diff  --git a/clang/lib/Basic/Targets.cpp b/clang/lib/Basic/Targets.cpp
index 664260d184fc..c063f8ca4472 100644
--- a/clang/lib/Basic/Targets.cpp
+++ b/clang/lib/Basic/Targets.cpp
@@ -383,6 +383,8 @@ TargetInfo *AllocateTarget(const llvm::Triple ,
 switch (os) {
 case llvm::Triple::FreeBSD:
   return new FreeBSDTargetInfo(Triple, Opts);
+case llvm::Triple::Fuchsia:
+  return new FuchsiaTargetInfo(Triple, Opts);
 case llvm::Triple::Linux:
   return new LinuxTargetInfo(Triple, Opts);
 default:

diff  --git a/clang/lib/Driver/ToolChains/Fuchsia.cpp 
b/clang/lib/Driver/ToolChains/Fuchsia.cpp
index df2b4724dc22..9bea0b15c873 100644
--- a/clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ b/clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -224,7 +224,7 @@ Fuchsia::Fuchsia(const Driver , const llvm::Triple 
,
 std::string Fuchsia::ComputeEffectiveClangTriple(const ArgList ,
  types::ID InputType) const {
   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
-  return (Triple.getArchName() + "-" + Triple.getOSName()).str();
+  return Triple.str();
 }
 
 Tool *Fuchsia::buildLinker() const {
@@ -344,9 +344,17 @@ SanitizerMask Fuchsia::getSupportedSanitizers() const {
 
 SanitizerMask Fuchsia::getDefaultSanitizers() const {
   SanitizerMask Res;
-  if (getTriple().getArch() == llvm::Triple::aarch64)
+  switch (getTriple().getArch()) {
+  case llvm::Triple::aarch64:
 Res |= SanitizerKind::ShadowCallStack;
-  else
+break;
+  case llvm::Triple::x86_64:
 Res |= SanitizerKind::SafeStack;
+break;
+  case 

[PATCH] D70157: Align branches within 32-Byte boundary

2019-11-21 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D70157#1755927 , @jyknight wrote:

> Thanks for the comments, they help a little. But it's still somewhat 
> confusing, so let me write down what seems to be happening:
>
> - Before emitting every instruction, a new MCMachineDependentFragment is now 
> emitted, of one of the multiple types:
>   - For most instructions, that'll be BranchPrefix.
>   - For things that need branch-alignment, it'll be BranchPadding, unless 
> there's a fused conditional before, in which case it's BranchSplit
>   - For fused conditionals, it'll be FusedJccPadding.
> - After emitting an instruction that needs branch-alignment, all of those 
> previously-emitted MCMachineDependentFragment are updated to point to the 
> branch's fragment.
> - Thus, every MCDataFragment now only contains a single instruction (this 
> property is depended upon for getInstSize, at least).
>
>   All the MCMachineDependentFragments in a region bounded by a branch at the 
> end and either a branch or a fragment-type which is not type in {FT_Data, 
> FT_MachineDependent, FT_Relaxable, FT_CompactEncodedInst} at the beginning, 
> will reference the ending branch instruction's fragment.
>
>   Then, when it comes time to do relaxation, every one of those 
> machine-dependent-fragments has the opportunity to grow its instruction a 
> little bit. The first instruction in a "block" will grow up to 5 segment 
> prefixes (via modifying the BranchPrefix fragment), and then if more is 
> needed, more prefixes will be added to the next instruction, and so on. Until 
> you run out of instructions in the region. At which point the BranchPadding 
> or FusedJccPadding types (right before the branch/fused-branch) will be able 
> to emit nops to achieve the desired alignment.
>
>   An alternative would be to simply emit NOPs before branches as needed. That 
> would be substantially simpler, since it would only require special handling 
> for a branch or a fused-branch. I assume things were done this 
> substantially-more-complex way in order to reduce performance cost of 
> inserting NOP instructions? Are there numbers for how much better it is to 
> use segment prefixes, vs a separate nop instruction? It seems a little bit 
> surprising to me that it would be that important, but I don't know...


I don't have any numbers myself. I was only involved in some of the code review 
internally. My understanding is that NOP instructions would place extra nop 
uops into the DSB(the decoded uop buffer) and that limits the performance that 
can be recovered. By using redundant prefixes no extra uops are generated and 
more performance is recovered.

> I'll note that the method here has the semantic issue of making it 
> effectively impossible to ever evaluate an expression like ".if . - symbol == 
> 24" (assuming we're emitting instructions), since every instruction can now 
> change size. I suspect that will make it impossible to turn this on by 
> default without breaking a lot of assembly code. Previously, only certain 
> instructions, like branches or arithmetic ops with constant arguments of 
> unknown value, could change size.




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

https://reviews.llvm.org/D70157



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


[PATCH] D69618: NeonEmitter: clean up prototype modifiers

2019-11-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

It looks like this broke vcreate_u16 and friends.  From 
http://lab.llvm.org:8011/builders/aosp-O3-polly-before-vectorizer-unprofitable/builds/1224/steps/build-aosp/logs/stdio
 :

  external/skia/src/opts/SkBitmapProcState_filter_neon.h:53:42: error: C-style 
cast from scalar 'int' to vector 'uint16x4_t' (vector of 4 'uint16_t' values) 
of different size
  vres = vshrn_n_u16(vcombine_u16(tmp, vcreate_u16(0)), 8); // shift down 
result by 8
 ~~^~~
  llvm.inst/lib/clang/10.0.0/include/arm_neon.h:4149:11: note: expanded from 
macro 'vcreate_u16'
__ret = (uint16x4_t)(__p0); \
^
  llvm.inst/lib/clang/10.0.0/include/arm_neon.h:24249:21: note: expanded from 
macro 'vshrn_n_u16'
uint16x8_t __s0 = __p0; \
  ^~~~


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

https://reviews.llvm.org/D69618



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


[PATCH] D70157: Align branches within 32-Byte boundary

2019-11-21 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

Thanks for the comments, they help a little. But it's still somewhat confusing, 
so let me write down what seems to be happening:

- Before emitting every instruction, a new MCMachineDependentFragment is now 
emitted, of one of the multiple types:
  - For most instructions, that'll be BranchPrefix.
  - For things that need branch-alignment, it'll be BranchPadding, unless 
there's a fused conditional before, in which case it's BranchSplit
  - For fused conditionals, it'll be FusedJccPadding.
- After emitting an instruction that needs branch-alignment, all of those 
previously-emitted MCMachineDependentFragment are updated to point to the 
branch's fragment.
- Thus, every MCDataFragment now only contains a single instruction (this 
property is depended upon for getInstSize, at least).

All the MCMachineDependentFragments in a region bounded by a branch at the end 
and either a branch or a fragment-type which is not type in {FT_Data, 
FT_MachineDependent, FT_Relaxable, FT_CompactEncodedInst} at the beginning, 
will reference the ending branch instruction's fragment.

Then, when it comes time to do relaxation, every one of those 
machine-dependent-fragments has the opportunity to grow its instruction a 
little bit. The first instruction in a "block" will grow up to 5 segment 
prefixes (via modifying the BranchPrefix fragment), and then if more is needed, 
more prefixes will be added to the next instruction, and so on. Until you run 
out of instructions in the region. At which point the BranchPadding or 
FusedJccPadding types (right before the branch/fused-branch) will be able to 
emit nops to achieve the desired alignment.

An alternative would be to simply emit NOPs before branches as needed. That 
would be substantially simpler, since it would only require special handling 
for a branch or a fused-branch. I assume things were done this 
substantially-more-complex way in order to reduce performance cost of inserting 
NOP instructions? Are there numbers for how much better it is to use segment 
prefixes, vs a separate nop instruction? It seems a little bit surprising to me 
that it would be that important, but I don't know...

I'll note that the method here has the semantic issue of making it effectively 
impossible to ever evaluate an expression like ".if . - symbol == 24" (assuming 
we're emitting instructions), since every instruction can now change size. I 
suspect that will make it impossible to turn this on by default without 
breaking a lot of assembly code. Previously, only certain instructions, like 
branches or arithmetic ops with constant arguments of unknown value, could 
change size.




Comment at: llvm/lib/MC/MCAssembler.cpp:1058
+/// is the address of the symbol, which would casuse performance regression.
+void MCAssembler::moveSymbol(const MCFragment *Src, MCFragment *Dst) const {
+  if (!(Src && Dst && Dst->getKind() == MCFragment::FT_MachineDependent))

I don't think this is necessary. AFAICT, the symbols should already be in the 
right place -- pointing to the relax fragment, not the instruction itself, 
without this. And removing all this moveSymbol/updateSymbolMap code doesn't 
make any tests fail.


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

https://reviews.llvm.org/D70157



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


[PATCH] D70571: [Coverage] Emit a gap region to cover switch bodies

2019-11-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Could you write a description somewhere of what the overall region tree should 
look like for a switch?




Comment at: clang/test/CoverageMapping/switch.cpp:32
   switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
-nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+nop();  // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:14 -> 
[[@LINE+2]]:10 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7

I'm not sure I understand the effect here.  Will we show that nop() never 
executes, or will we not show any coverage information for it?


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

https://reviews.llvm.org/D70571



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


[PATCH] D70572: [Serialization] #pragma clang transform

2019-11-21 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur created this revision.
Meinersbur added reviewers: hfinkel, kbarton, SjoerdMeijer, aaron.ballman, 
ABataev, fhahn, hsaito, hans, greened, dmgreen, Ayal, asavonic, rtrieu, dorit, 
rsmith, tyler.nowicki, jdoerfert.
Herald added subscribers: cfe-commits, zzheng.
Herald added a project: clang.
Meinersbur removed subscribers: zzheng, llvm-commits.
Meinersbur added a subscriber: zzheng.

De(-serialization) of #pragma clang transform AST nodes and clauses.

For a full description, see D69088 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70572

Files:
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/include/clang/Serialization/ASTReader.h
  clang/include/clang/Serialization/ASTWriter.h
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/test/PCH/transform-interleave.cpp
  clang/test/PCH/transform-unroll.cpp
  clang/test/PCH/transform-unrollandjam.cpp
  clang/test/PCH/transform-vectorize.cpp

Index: clang/test/PCH/transform-vectorize.cpp
===
--- /dev/null
+++ clang/test/PCH/transform-vectorize.cpp
@@ -0,0 +1,28 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -emit-pch -o %t.pch %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -include-pch %t.pch %s -ast-dump-all -o - | FileCheck %s --dump-input=fail -vv
+
+#ifndef HEADER
+#define HEADER
+
+void vectorize_heuristic(int n) {
+#pragma clang transform vectorize
+  for (int i = 0; i < n; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported vectorize_heuristic
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: ForStmt
+
+
+void vectorize_width(int n) {
+#pragma clang transform vectorize width(4)
+  for (int i = 0; i < n; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported vectorize_width
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: WidthClause
+// CHECK-NEXT:   IntegerLiteral {{.*}} 'int' 4
+// CHECK-NEXT: ForStmt
+
+#endif /* HEADER */
Index: clang/test/PCH/transform-unrollandjam.cpp
===
--- /dev/null
+++ clang/test/PCH/transform-unrollandjam.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -emit-pch -o %t.pch %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -include-pch %t.pch %s -ast-dump-all -o - | FileCheck %s --dump-input=fail -vv
+
+#ifndef HEADER
+#define HEADER
+
+void  unrollandjam_heuristic(int n) {
+#pragma clang transform unrollandjam
+  for (int i = 0; i < n; i+=1)
+for (int j = 0; j < n; j+=1)
+  ;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unrollandjam_heuristic
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: ForStmt
+
+
+void unrollandjam_partial(int n) {
+#pragma clang transform unrollandjam partial(4)
+  for (int i = 0; i < n; i+=1)
+for (int j = 0; j < n; j+=1)
+  ;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unrollandjam_partial
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: PartialClause
+// CHECK-NEXT:   IntegerLiteral {{.*}} 'int' 4
+// CHECK-NEXT: ForStmt
+
+#endif /* HEADER */
Index: clang/test/PCH/transform-unroll.cpp
===
--- /dev/null
+++ clang/test/PCH/transform-unroll.cpp
@@ -0,0 +1,85 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -emit-pch -o %t.pch %s
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fexperimental-transform-pragma -include-pch %t.pch %s -ast-dump-all -o - | FileCheck %s --dump-input=fail -vv
+
+#ifndef HEADER
+#define HEADER
+
+void  unroll_heuristic(int n) {
+#pragma clang transform unroll
+  for (int i = 0; i < 4; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unroll_heuristic
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: ForStmt
+
+
+void unroll_full(int n) {
+#pragma clang transform unroll full
+  for (int i = 0; i < 4; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unroll_full
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: FullClause
+// CHECK-NEXT: ForStmt
+
+
+void unroll_partial(int n) {
+#pragma clang transform unroll partial(4)
+  for (int i = 0; i < n; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unroll_partial
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: PartialClause
+// CHECK-NEXT:   IntegerLiteral {{.*}} 'int' 4
+// CHECK-NEXT: ForStmt
+
+
+template
+void unroll_template_function(int n) {
+#pragma clang transform unroll partial(FACTOR)
+  for (int i = 0; i < n; i+=1)
+;
+}
+// CHECK-LABEL: FunctionDecl {{.*}} imported unroll_template_function
+// CHECK: TransformExecutableDirective
+// CHECK-NEXT: PartialClause
+// CHECK-NEXT:   

[PATCH] D70268: [clang][clang-scan-deps] Aggregate the full dependency information.

2019-11-21 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese marked an inline comment as done.
Bigcheese added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp:97
+  if (OutputPaths.empty())
+OutputPaths = Opts.Targets;
   Dependencies.push_back(File);

arphaman wrote:
> What if `Opts.Targets` is empty?
If I recall correctly, `Opts.Targets` can never be empty. I gets set to 
`.o` if it would be empty.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70268



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


[PATCH] D70571: [Coverage] Emit a gap region to cover switch bodies

2019-11-21 Thread Vedant Kumar via Phabricator via cfe-commits
vsk created this revision.
vsk added reviewers: hans, rnk, efriedma.
vsk edited the summary of this revision.

Emit a gap region beginning where the switch body begins. This sets line
execution counts in the areas between non-overlapping cases to 0.

This does not resolve an outstanding issue with case statement regions
that do not end when a region is terminated. But it should address
llvm.org/PR44011.


https://reviews.llvm.org/D70571

Files:
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/test/CoverageMapping/switch.cpp
  clang/test/CoverageMapping/switchmacro.c

Index: clang/test/CoverageMapping/switchmacro.c
===
--- clang/test/CoverageMapping/switchmacro.c
+++ clang/test/CoverageMapping/switchmacro.c
@@ -4,7 +4,7 @@
 
 // CHECK: foo
 int foo(int i) { // CHECK-NEXT: File 0, [[@LINE]]:16 -> {{[0-9]+}}:2 = #0
-  switch (i) {
+  switch (i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:14 -> {{[0-9]+}}:11 = 0
   default:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> {{[0-9]+}}:11 = #2
 if (i == 1)  // CHECK-NEXT: File 0, [[@LINE]]:9 -> [[@LINE]]:15 = #2
   return 0;  // CHECK: File 0, [[@LINE]]:7 -> [[@LINE]]:15 = #3
Index: clang/test/CoverageMapping/switch.cpp
===
--- clang/test/CoverageMapping/switch.cpp
+++ clang/test/CoverageMapping/switch.cpp
@@ -2,11 +2,11 @@
 
 // CHECK: foo
 void foo(int i) {   // CHECK-NEXT: File 0, [[@LINE]]:17 -> [[@LINE+8]]:2 = #0
-  switch(i) {
+  switch(i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:13 -> [[@LINE+4]]:10 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:11 = #2
 return;
   case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #3
-break;  // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:3 = #1
+break;  // CHECK-NEXT: Gap,File 0, [[@LINE]]:10 -> [[@LINE+2]]:3 = #1
   }
   int x = 0;// CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:2 = #1
 }
@@ -29,7 +29,7 @@
 nop();
 
   switch (i) {  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+6]]:2 = #4
-nop();  // CHECK-NEXT: File 0, [[@LINE]]:5 -> [[@LINE+2]]:10 = 0
+nop();  // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:14 -> [[@LINE+2]]:10 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = #7
 nop();
   }
@@ -47,7 +47,7 @@
 // CHECK-NEXT: main
 int main() {// CHECK-NEXT: File 0, [[@LINE]]:12 -> [[@LINE+35]]:2 = #0
   int i = 0;
-  switch(i) {
+  switch(i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:13 -> [[@LINE+8]]:10 = 0
   case 0:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #2
 i = 1;
 break;
@@ -58,16 +58,16 @@
 break;  // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+2]]:3 = #1
   }
   switch(i) {   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+23]]:2 = #1
-  case 0:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = #6
-i = 1;
+  case 0:   // CHECK-NEXT: Gap,File 0, [[@LINE-1]]:13 -> [[@LINE+6]]:10 = 0
+i = 1;  // CHECK-NEXT: File 0, [[@LINE-1]]:3 -> [[@LINE+1]]:10 = #6
 break;
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+3]]:10 = #7
 i = 2;
   default:  // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:10 = (#7 + #8)
 break;  // CHECK-NEXT: File 0, [[@LINE]]:10 -> [[@LINE+3]]:3 = #5
   }
-
-  switch(i) {   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+13]]:2 = #5
+// CHECK-NEXT: File 0, [[@LINE+1]]:3 -> [[@LINE+14]]:2 = #5
+  switch(i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:13 -> [[@LINE+6]]:11 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+5]]:11 = #10
   case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+4]]:11 = (#10 + #11)
 i = 11;
@@ -85,7 +85,7 @@
 // FIXME: End location for "case 1" shouldn't point at the end of the switch.
  // CHECK: fallthrough
 int fallthrough(int i) { // CHECK-NEXT: File 0, [[@LINE]]:24 -> [[@LINE+12]]:2 = #0
-  switch(i) {
+  switch(i) {   // CHECK-NEXT: Gap,File 0, [[@LINE]]:13 -> [[@LINE+9]]:10 = 0
   case 1:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+8]]:10 = #2
 i = 23;
   case 2:   // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+2]]:10 = (#2 + #3)
@@ -101,7 +101,7 @@
 void abort(void) __attribute((noreturn));
// CHECK: noret
 int noret(int x) { // CHECK-NEXT: File 0, [[@LINE]]:18 -> [[@LINE+9]]:2
-  switch (x) {
+  switch (x) { // CHECK-NEXT: Gap,File 0, [[@LINE]]:14 -> [[@LINE+6]]:14 = 0
   default: // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:12
 abort();
   case 1: // CHECK-NEXT: File 0, [[@LINE]]:3 -> [[@LINE+1]]:13
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- 

[PATCH] D70569: [clangd] Allow extract-to-function on regions that always return.

2019-11-21 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: pass - 60231 tests passed, 0 failed and 732 were skipped.
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70569



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


[PATCH] D70268: [clang][clang-scan-deps] Aggregate the full dependency information.

2019-11-21 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp:97
+  if (OutputPaths.empty())
+OutputPaths = Opts.Targets;
   Dependencies.push_back(File);

What if `Opts.Targets` is empty?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70268



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


[PATCH] D70556: clang/Modules: Refactor CompilerInstance::loadModule, NFC

2019-11-21 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith marked 2 inline comments as done.
dexonsmith added inline comments.



Comment at: clang/include/clang/Lex/ModuleLoader.h:50
+// We failed to load the module, but we shouldn't cache the failure.
+OtherUncachedFailure,
   };

jkorous wrote:
> Just a typo - the comma at the end.
That comma was intentional, actually!  Then the next time a value gets 
added/removed it doesn't unnecessarily cause differences to other liens :).


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

https://reviews.llvm.org/D70556



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


[PATCH] D70569: [clangd] Allow extract-to-function on regions that always return.

2019-11-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: cfe-commits, usaxena95, arphaman, jkorous, MaskRay, 
ilya-biryukov.
Herald added a project: clang.

We only do a trivial check whether the region always returns - it has to end
with a return statement.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70569

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.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
@@ -573,8 +573,10 @@
   EXPECT_THAT(apply(" for([[int i = 0;]];);"), HasSubstr("extracted"));
   // Don't extract because needs hoisting.
   EXPECT_THAT(apply(" [[int a = 5;]] a++; "), StartsWith("fail"));
-  // Don't extract return
-  EXPECT_THAT(apply(" if(true) [[return;]] "), StartsWith("fail"));
+  // Extract certain return
+  EXPECT_THAT(apply(" if(true) [[{ return; }]] "), HasSubstr("extracted"));
+  // Don't extract uncertain return
+  EXPECT_THAT(apply(" if(true) [[if (false) return;]] "), StartsWith("fail"));
 }
 
 TEST_F(ExtractFunctionTest, FileTest) {
@@ -679,6 +681,42 @@
   StartsWith("fail"));
 }
 
+TEST_F(ExtractFunctionTest, ExistingReturnStatement) {
+  Context = File;
+  const char* Before = R"cpp(
+bool lucky(int N);
+int getNum(bool Superstitious, int Min, int Max) {
+  if (Superstitious) [[{
+for (int I = Min; I <= Max; ++I)
+  if (lucky(I))
+return I;
+return -1;
+  }]] else {
+return (Min + Max) / 2;
+  }
+}
+  )cpp";
+  // FIXME: min/max should be by value.
+  // FIXME: avoid emitting redundant braces
+  const char* After = R"cpp(
+bool lucky(int N);
+int extracted(int , int ) {
+{
+for (int I = Min; I <= Max; ++I)
+  if (lucky(I))
+return I;
+return -1;
+  }
+}
+int getNum(bool Superstitious, int Min, int Max) {
+  if (Superstitious) return extracted(Min, Max); else {
+return (Min + Max) / 2;
+  }
+}
+  )cpp";
+  EXPECT_EQ(apply(Before), After);
+}
+
 TWEAK_TEST(RemoveUsingNamespace);
 TEST_F(RemoveUsingNamespaceTest, All) {
   std::pair Cases[] = {
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -165,6 +165,21 @@
   llvm::DenseSet RootStmts;
 };
 
+// Whether the code in the extraction zone is guaranteed to return, assuming
+// no broken control flow (unbound break/continue).
+// This is a very naive check (does it end with a return stmt).
+// Doing some rudimentary control flow analysis would cover more cases.
+bool alwaysReturns(const ExtractionZone ) {
+  const Stmt *Last = EZ.Parent->Children.back()->ASTNode.get();
+  // Unwrap enclosing (unconditional) compound statement.
+  while (const auto *CS = llvm::dyn_cast(Last))
+if (CS->body_empty())
+  return false;
+else
+  Last = CS->body_back();
+  return llvm::isa(Last);
+}
+
 bool ExtractionZone::isRootStmt(const Stmt *S) const {
   return RootStmts.find(S) != RootStmts.end();
 }
@@ -283,11 +298,12 @@
 }
   };
   std::string Name = "extracted";
-  std::string ReturnType;
+  QualType ReturnType;
   std::vector Parameters;
   SourceRange BodyRange;
   SourceLocation InsertionPoint;
   const DeclContext *EnclosingFuncContext;
+  bool CallerReturnsValue = false;
   // Decides whether the extracted function body and the function call need a
   // semicolon after extraction.
   tooling::ExtractionSemicolonPolicy SemicolonPolicy;
@@ -330,13 +346,16 @@
 }
 
 std::string NewFunction::renderCall() const {
-  return Name + "(" + renderParametersForCall() + ")" +
- (SemicolonPolicy.isNeededInOriginalFunction() ? ";" : "");
+  return llvm::formatv(
+  "{0}{1}({2}){3}", CallerReturnsValue ? "return " : "", Name,
+  renderParametersForCall(),
+  (SemicolonPolicy.isNeededInOriginalFunction() ? ";" : ""));
 }
 
 std::string NewFunction::renderDefinition(const SourceManager ) const {
-  return ReturnType + " " + Name + "(" + renderParametersForDefinition() + ")" +
- " {\n" + getFuncBody(SM) + "\n}\n";
+  return llvm::formatv("{0} {1}({2}) {\n{3}\n}\n",
+   printType(ReturnType, *EnclosingFuncContext), Name,
+   renderParametersForDefinition(), getFuncBody(SM));
 }
 
 std::string NewFunction::getFuncBody(const SourceManager ) const {
@@ -370,8 +389,8 @@
   };
   // Maps Decls to their DeclInfo
   llvm::DenseMap DeclInfoMap;
-  // True if there is a return statement in zone.
-  bool HasReturnStmt = false;
+  bool HasReturnStmt = false; // Are there any return statements in the zone?

[PATCH] D70556: clang/Modules: Refactor CompilerInstance::loadModule, NFC

2019-11-21 Thread Jan Korous via Phabricator via cfe-commits
jkorous added inline comments.



Comment at: clang/include/clang/Lex/ModuleLoader.h:50
+// We failed to load the module, but we shouldn't cache the failure.
+OtherUncachedFailure,
   };

Just a typo - the comma at the end.


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

https://reviews.llvm.org/D70556



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


[PATCH] D70568: [Support] Possibly use exception handler in the Crash Recovery Context in the same way as global exceptions

2019-11-21 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea created this revision.
aganea added reviewers: hans, rnk, thakis.
Herald added subscribers: llvm-commits, cfe-commits, jfb, arphaman, hiraditya.
Herald added a reviewer: jfb.
Herald added projects: clang, LLVM.
aganea edited the summary of this revision.
Herald added a subscriber: dexonsmith.

This is a support patch for D69825 .
It handles an exception in the same way as the global exception handler (same 
side-effect, print call stack & cleanup), and can return the exception code.
It enables `CrashRecoveryContext` exceptions by default (instead of disabled 
before) - however the exception handlers are lazily installed on the first 
creation of a `CrashRecoveryContext`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70568

Files:
  clang/test/Modules/signal.m
  clang/tools/libclang/CIndex.cpp
  llvm/include/llvm/Support/CrashRecoveryContext.h
  llvm/include/llvm/Support/Signals.h
  llvm/lib/Support/CrashRecoveryContext.cpp
  llvm/lib/Support/Unix/Signals.inc
  llvm/lib/Support/Windows/Signals.inc

Index: llvm/lib/Support/Windows/Signals.inc
===
--- llvm/lib/Support/Windows/Signals.inc
+++ llvm/lib/Support/Windows/Signals.inc
@@ -521,10 +521,13 @@
 extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
 #endif
 
-void llvm::sys::PrintStackTrace(raw_ostream ) {
-  STACKFRAME64 StackFrame = {};
-  CONTEXT Context = {};
-  ::RtlCaptureContext();
+static void LocalPrintStackTrace(raw_ostream , PCONTEXT C) {
+  STACKFRAME64 StackFrame{};
+  CONTEXT Context{};
+  if (!C) {
+::RtlCaptureContext();
+C = 
+  }
 #if defined(_M_X64)
   StackFrame.AddrPC.Offset = Context.Rip;
   StackFrame.AddrStack.Offset = Context.Rsp;
@@ -546,9 +549,12 @@
   StackFrame.AddrStack.Mode = AddrModeFlat;
   StackFrame.AddrFrame.Mode = AddrModeFlat;
   PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
-   StackFrame, );
+   StackFrame, C);
 }
 
+void llvm::sys::PrintStackTrace(raw_ostream ) {
+  LocalPrintStackTrace(OS, nullptr);
+}
 
 void llvm::sys::SetInterruptFunction(void (*IF)()) {
   RegisterHandler();
@@ -792,6 +798,10 @@
   return std::error_code();
 }
 
+signed sys::InvokeExceptionHandler(int &, void *ExceptionInfo) {
+  return LLVMUnhandledExceptionFilter((LPEXCEPTION_POINTERS)ExceptionInfo);
+}
+
 static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
   Cleanup();
 
@@ -810,42 +820,9 @@
<< "\n";
   }
 
-  // Initialize the STACKFRAME structure.
-  STACKFRAME64 StackFrame = {};
-
-#if defined(_M_X64)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#elif defined(_M_IX86)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#elif defined(_M_ARM64) || defined(_M_ARM)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Pc;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Sp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-#if defined(_M_ARM64)
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Fp;
-#else
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->R11;
-#endif
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#endif
-
-  HANDLE hProcess = GetCurrentProcess();
-  HANDLE hThread = GetCurrentThread();
-  PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
-   ep->ContextRecord);
+  LocalPrintStackTrace(llvm::errs(), ep ? ep->ContextRecord : nullptr);
 
-  _exit(ep->ExceptionRecord->ExceptionCode);
+  return EXCEPTION_EXECUTE_HANDLER;
 }
 
 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Index: llvm/lib/Support/Unix/Signals.inc
===
--- llvm/lib/Support/Unix/Signals.inc
+++ llvm/lib/Support/Unix/Signals.inc
@@ -345,6 +345,17 @@
   FileToRemoveList::removeAllFiles(FilesToRemove);
 }
 
+signed sys::InvokeExceptionHandler(int , void *) {
+  SignalHandler(RetCode);
+  // llvm/lib/Support/Unix/Program.inc:Wait() returns -2 if a crash occurs,
+  // not the actual error code. If we want to diagnose a crash in the same
+  // way as invoking/forking a new process (in
+  // clang/tools/driver/driver.cpp), we need to do this here.
+  if (WIFSIGNALED(RetCode))
+RetCode = -2;
+  return 0;
+}
+
 // The signal handler that runs.
 static RETSIGTYPE SignalHandler(int Sig) {
   // Restore the signal behavior to default, so that the program actually

[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

In D70551#1755768 , @ABataev wrote:

> In D70551#1755761 , @sdmitriev wrote:
>
> > In D70551#1755583 , @ABataev wrote:
> >
> > > In D70551#173 , @sdmitriev 
> > > wrote:
> > >
> > > > In D70551#1755527 , @ABataev 
> > > > wrote:
> > > >
> > > > > Why do we need this?
> > > >
> > > >
> > > > To pass wrapper bitcode directly to the linker when LTO is enabled. LTO 
> > > > plugin does not accept bc if there is no data layout.
> > >
> > >
> > > Maybe it would better to pass it a parameter just like for opt?
> >
> >
> > In this case clang driver would need to get it from somewhere in order to 
> > pass it to the wrapper tool. I do not know where it can get it from.
>
>
> `TargetInfo` class is not accessible in the driver?


Ah, I see, you mean clang's TargetInfo. Let me check if/how it will work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[PATCH] D69825: [Clang][Driver] Re-use the calling process instead of creating a new process for the cc1 invocation

2019-11-21 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

I've split the `CrashRecoveryContext` changes into another patch to minimize 
the risks, please see D70568 . That patch will 
need to go first before this one.


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

https://reviews.llvm.org/D69825



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


[PATCH] D69825: [Clang][Driver] Re-use the calling process instead of creating a new process for the cc1 invocation

2019-11-21 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added inline comments.



Comment at: clang/lib/Driver/Job.cpp:347
+StringRef DriverExe = llvm::sys::path::stem(D.ClangExecutable);
+if (CommandExe.equals_lower(DriverExe))
+CC1Main = Driver::CC1Main;

hans wrote:
> aganea wrote:
> > hans wrote:
> > > Now that we're not calling main() anymore, but cc1 directly -- is this 
> > > checking still necessary?
> > Yes it is - see my other comment just above.
> > 
> > The driver builds phases that do not always call the cc1 process. Simply 
> > stating `clang a.cpp` would invoke `clang -cc1`, then the linker, say 
> > `link.exe`. In this later case (invoking `link.exe`), even if we have 
> > `Driver::Main` it doesn't mean we should use it. There are a number of 
> > other edge cases of the same kind, such as `/fallback` or building cuda 
> > files, where a different executable is invoked along the way."
> Okay, but couldn't we find a cleaner way of figuring out that the Command is 
> a cc1 invocation? The thing that creates the Command would know.. maybe it 
> could set a flag or something? Or maybe instead of creating a Command it 
> would create something else?
Yeah you're right, I've refactored and added a `CC1Command` instead, makes 
things much cleaner, thank you!


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

https://reviews.llvm.org/D69825



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


[PATCH] D69825: [Clang][Driver] Re-use the calling process instead of creating a new process for the cc1 invocation

2019-11-21 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 230527.
aganea marked 3 inline comments as done.

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

https://reviews.llvm.org/D69825

Files:
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Job.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/tools/driver/driver.cpp

Index: clang/tools/driver/driver.cpp
===
--- clang/tools/driver/driver.cpp
+++ clang/tools/driver/driver.cpp
@@ -30,6 +30,7 @@
 #include "llvm/Option/OptTable.h"
 #include "llvm/Option/Option.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -303,7 +304,13 @@
 TheDriver.setInstalledDir(InstalledPathParent);
 }
 
-static int ExecuteCC1Tool(ArrayRef argv, StringRef Tool) {
+static int ExecuteCC1Tool(ArrayRef argv) {
+  // If we call the cc1 tool from the clangDriver library (through
+  // Driver::CC1Main), we need to cleanup the options usage count. The options
+  // are currently global, and they might have been used previously by the
+  // driver.
+  llvm::cl::ResetAllOptionOccurrences();
+  StringRef Tool = argv[1] + 4;
   void *GetExecutablePathVP = (void *)(intptr_t) GetExecutablePath;
   if (Tool == "")
 return cc1_main(argv.slice(2), argv[0], GetExecutablePathVP);
@@ -379,7 +386,7 @@
   auto newEnd = std::remove(argv.begin(), argv.end(), nullptr);
   argv.resize(newEnd - argv.begin());
 }
-return ExecuteCC1Tool(argv, argv[1] + 4);
+return ExecuteCC1Tool(argv);
   }
 
   bool CanonicalPrefixes = true;
@@ -455,6 +462,11 @@
 
   SetBackdoorDriverOutputsFromEnvVars(TheDriver);
 
+  // Here we provide a shortcut for calling the -cc1 cmd-line within the same
+  // process, instead of starting a new process. This saves a huge amount of
+  // time of Windows, as process creation can be expensive on that platform.
+  TheDriver.CC1Main = 
+
   std::unique_ptr C(TheDriver.BuildCompilation(argv));
   int Res = 1;
   if (C && !C->containsError()) {
@@ -503,7 +515,7 @@
 
 #ifdef _WIN32
   // Exit status should not be negative on Win32, unless abnormal termination.
-  // Once abnormal termiation was caught, negative status should not be
+  // Once abnormal termination was caught, negative status should not be
   // propagated.
   if (Res < 0)
 Res = 1;
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5656,6 +5656,10 @@
 // fails, so that the main compilation's fallback to cl.exe runs.
 C.addCommand(std::make_unique(JA, *this, Exec,
 CmdArgs, Inputs));
+  } else if (D.CC1Main && !D.CCGenDiagnostics) {
+// Invoke the CC1 directly in this process
+C.addCommand(
+std::make_unique(JA, *this, Exec, CmdArgs, Inputs));
   } else {
 C.addCommand(std::make_unique(JA, *this, Exec, CmdArgs, Inputs));
   }
Index: clang/lib/Driver/Job.cpp
===
--- clang/lib/Driver/Job.cpp
+++ clang/lib/Driver/Job.cpp
@@ -19,8 +19,10 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
@@ -313,15 +315,49 @@
   Environment.push_back(nullptr);
 }
 
-int Command::Execute(ArrayRef> Redirects,
- std::string *ErrMsg, bool *ExecutionFailed) const {
+int Command::PrepareExecution(SmallVectorImpl ,
+  std::string *ErrMsg,
+  bool *ExecutionFailed) const {
   if (PrintInputFilenames) {
 for (const char *Arg : InputFilenames)
   llvm::outs() << llvm::sys::path::filename(Arg) << "\n";
 llvm::outs().flush();
   }
 
-  SmallVector Argv;
+  if (ResponseFile == nullptr) {
+Argv.push_back(Executable);
+Argv.append(Arguments.begin(), Arguments.end());
+Argv.push_back(nullptr);
+  } else {
+// If the command is too large, we need to put arguments in a response file.
+std::string RespContents;
+llvm::raw_string_ostream SS(RespContents);
+
+// Write file contents and build the Argv vector
+writeResponseFile(SS);
+buildArgvForResponseFile(Argv);
+Argv.push_back(nullptr);
+SS.flush();
+
+// Save the response file in the appropriate encoding
+if (std::error_code EC = writeFileWithEncoding(
+ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
+  if (ErrMsg)
+*ErrMsg = EC.message();
+  if 

[clang] f8ff3d7 - [OPENMP]Remove unused template parameter, NFC.

2019-11-21 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2019-11-21T16:42:26-05:00
New Revision: f8ff3d7ebd8499cad896b2e934fbc9d7412ba823

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

LOG: [OPENMP]Remove unused template parameter, NFC.

Added: 


Modified: 
clang/include/clang/Basic/OpenMPKinds.h
clang/include/clang/Sema/Sema.h
clang/lib/CodeGen/CGOpenMPRuntime.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/OpenMPKinds.h 
b/clang/include/clang/Basic/OpenMPKinds.h
index 121c8bd2e48b..2621afe7afbb 100644
--- a/clang/include/clang/Basic/OpenMPKinds.h
+++ b/clang/include/clang/Basic/OpenMPKinds.h
@@ -39,8 +39,7 @@ OpenMPContextSelectorKind 
getOpenMPContextSelector(llvm::StringRef Str);
 llvm::StringRef getOpenMPContextSelectorName(OpenMPContextSelectorKind Kind);
 
 /// Struct to store the context selectors info.
-template 
-struct OpenMPCtxSelectorData {
+template  struct OpenMPCtxSelectorData {
   OpenMPContextSelectorSetKind CtxSet = OMP_CTX_SET_unknown;
   OpenMPContextSelectorKind Ctx = OMP_CTX_unknown;
   ScoreT Score;

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 7d8ab59fe900..55e39a27e6c6 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -9315,8 +9315,7 @@ class Sema final {
   /// Struct to store the context selectors info for declare variant directive.
   using OMPCtxStringType = SmallString<8>;
   using OMPCtxSelectorData =
-  OpenMPCtxSelectorData,
-ExprResult>;
+  OpenMPCtxSelectorData, ExprResult>;
 
   /// Checks if the variant/multiversion functions are compatible.
   bool areMultiversionVariantFunctionsCompatible(

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 347606fc7461..c2d895b4ea4a 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11028,7 +11028,7 @@ Address 
CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction ,
 
 namespace {
 using OMPContextSelectorData =
-OpenMPCtxSelectorData, llvm::APSInt>;
+OpenMPCtxSelectorData, llvm::APSInt>;
 using CompleteOMPContextSelectorData = SmallVector;
 } // anonymous namespace
 



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


[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D70551#1755761 , @sdmitriev wrote:

> In D70551#1755583 , @ABataev wrote:
>
> > In D70551#173 , @sdmitriev 
> > wrote:
> >
> > > In D70551#1755527 , @ABataev 
> > > wrote:
> > >
> > > > Why do we need this?
> > >
> > >
> > > To pass wrapper bitcode directly to the linker when LTO is enabled. LTO 
> > > plugin does not accept bc if there is no data layout.
> >
> >
> > Maybe it would better to pass it a parameter just like for opt?
>
>
> In this case clang driver would need to get it from somewhere in order to 
> pass it to the wrapper tool. I do not know where it can get it from.


`TargetInfo` class is not accessible in the driver?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[PATCH] D70467: [Distro] Bypass distro detection on Windows

2019-11-21 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 230525.
aganea added a comment.

Removed `#ifdef _WIN32`
Use the target triple where possible to detect the distro. The Cuda 
installation detector uses the host triple, in order to use the host tooling.
Skip distro detection when the target or host system is not Linux.


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

https://reviews.llvm.org/D70467

Files:
  clang/include/clang/Driver/Distro.h
  clang/lib/Driver/Distro.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/unittests/Driver/DistroTest.cpp

Index: clang/unittests/Driver/DistroTest.cpp
===
--- clang/unittests/Driver/DistroTest.cpp
+++ clang/unittests/Driver/DistroTest.cpp
@@ -44,7 +44,7 @@
"SUPPORT_URL=\"http://help.ubuntu.com/\"\n;
"BUG_REPORT_URL=\"http://bugs.launchpad.net/ubuntu/\"\n;));
 
-  Distro UbuntuTrusty{UbuntuTrustyFileSystem};
+  Distro UbuntuTrusty{UbuntuTrustyFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UbuntuTrusty), UbuntuTrusty);
   ASSERT_TRUE(UbuntuTrusty.IsUbuntu());
   ASSERT_FALSE(UbuntuTrusty.IsRedhat());
@@ -52,6 +52,9 @@
   ASSERT_FALSE(UbuntuTrusty.IsDebian());
   ASSERT_FALSE(UbuntuTrusty.IsGentoo());
 
+  Distro UbuntuTrusty2{UbuntuTrustyFileSystem, llvm::Triple("unknown-pc-windows")};
+  ASSERT_EQ(Distro(Distro::UnknownDistro), UbuntuTrusty2);
+
   llvm::vfs::InMemoryFileSystem UbuntuYakketyFileSystem;
   UbuntuYakketyFileSystem.addFile("/etc/debian_version", 0,
   llvm::MemoryBuffer::getMemBuffer("stretch/sid\n"));
@@ -74,7 +77,7 @@
"VERSION_CODENAME=yakkety\n"
"UBUNTU_CODENAME=yakkety\n"));
 
-  Distro UbuntuYakkety{UbuntuYakketyFileSystem};
+  Distro UbuntuYakkety{UbuntuYakketyFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UbuntuYakkety), UbuntuYakkety);
   ASSERT_TRUE(UbuntuYakkety.IsUbuntu());
   ASSERT_FALSE(UbuntuYakkety.IsRedhat());
@@ -109,7 +112,7 @@
"REDHAT_SUPPORT_PRODUCT=\"Fedora\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=25\n"
"PRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicy\n;));
-  Distro Fedora25{Fedora25FileSystem};
+  Distro Fedora25{Fedora25FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::Fedora), Fedora25);
   ASSERT_FALSE(Fedora25.IsUbuntu());
   ASSERT_TRUE(Fedora25.IsRedhat());
@@ -146,7 +149,7 @@
"REDHAT_SUPPORT_PRODUCT=\"centos\"\n"
"REDHAT_SUPPORT_PRODUCT_VERSION=\"7\"\n"));
 
-  Distro CentOS7{CentOS7FileSystem};
+  Distro CentOS7{CentOS7FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::RHEL7), CentOS7);
   ASSERT_FALSE(CentOS7.IsUbuntu());
   ASSERT_TRUE(CentOS7.IsRedhat());
@@ -174,7 +177,7 @@
"HOME_URL=\"https://opensuse.org/\"\n;
"ID_LIKE=\"suse\"\n"));
 
-  Distro OpenSUSELeap421{OpenSUSELeap421FileSystem};
+  Distro OpenSUSELeap421{OpenSUSELeap421FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::OpenSUSE), OpenSUSELeap421);
   ASSERT_FALSE(OpenSUSELeap421.IsUbuntu());
   ASSERT_FALSE(OpenSUSELeap421.IsRedhat());
@@ -200,7 +203,7 @@
"HOME_URL=\"https://opensuse.org/\"\n;
"ID_LIKE=\"suse\"\n"));
 
-  Distro OpenSUSE132{OpenSUSE132FileSystem};
+  Distro OpenSUSE132{OpenSUSE132FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::OpenSUSE), OpenSUSE132);
   ASSERT_FALSE(OpenSUSE132.IsUbuntu());
   ASSERT_FALSE(OpenSUSE132.IsRedhat());
@@ -217,7 +220,7 @@
   llvm::MemoryBuffer::getMemBuffer("LSB_VERSION=\"core-2.0-noarch:core-3.0-noarch:core-2.0-x86_64:core-3.0-x86_64\"\n"));
 
   // SLES10 is unsupported and therefore evaluates to unknown
-  Distro SLES10{SLES10FileSystem};
+  Distro SLES10{SLES10FileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::UnknownDistro), SLES10);
   ASSERT_FALSE(SLES10.IsUbuntu());
   ASSERT_FALSE(SLES10.IsRedhat());
@@ -240,7 +243,7 @@
"SUPPORT_URL=\"http://www.debian.org/support\"\n;
"BUG_REPORT_URL=\"https://bugs.debian.org/\"\n;));
 
-  Distro DebianJessie{DebianJessieFileSystem};
+  Distro DebianJessie{DebianJessieFileSystem, llvm::Triple("unknown-pc-linux")};
   ASSERT_EQ(Distro(Distro::DebianJessie), DebianJessie);
   ASSERT_FALSE(DebianJessie.IsUbuntu());
   ASSERT_FALSE(DebianJessie.IsRedhat());
@@ -259,7 +262,7 @@

[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

In D70551#1755583 , @ABataev wrote:

> In D70551#173 , @sdmitriev wrote:
>
> > In D70551#1755527 , @ABataev wrote:
> >
> > > Why do we need this?
> >
> >
> > To pass wrapper bitcode directly to the linker when LTO is enabled. LTO 
> > plugin does not accept bc if there is no data layout.
>
>
> Maybe it would better to pass it a parameter just like for opt?


In this case clang driver would need to get it from somewhere in order to pass 
it to the wrapper tool. I do not know where it can get it from.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[PATCH] D69938: [OpenCL] Use __generic addr space when generating internal representation of lambda

2019-11-21 Thread John McCall via Phabricator via cfe-commits
rjmccall added a reviewer: rsmith.
rjmccall added a comment.

In D69938#1754894 , @Anastasia wrote:

> In D69938#1752024 , @rjmccall wrote:
>
> > Yes, in that case copy-elision into the global variable is guaranteed.  You 
> > can write arbitrary expressions in global initializers, however, and those 
> > can use temporary lambdas.
>
>
> I guess you mean something like this?
>
>   auto glambda = []() { return 1; }();
>   


Yes, or just passing it as an argument to something.

> I don't see a way to change the address space of a lambda object however. It 
> would only be possible to specify addr space qualifiers for a call operator 
> of such lambdas.

Yes, I think the language has to say what address space the lambda temporary is 
in.  Among other things, this can affect how captures are initialized, since 
some constructors are only usable in certain address spaces.  (Lambdas in 
global contexts can't capture surrounding local variables, but they can still 
have explicitly-initialized captures, like `[x=foo()] { ... }`.)  That language 
rule could be that lambda temporaries are always in the private address space, 
or it could be that lambdas in global contexts are in the global address space. 
 The latter might be easier because it's compatible with lifetime-extension: we 
don't necessarily know when processing the lambda whether its temporary will be 
lifetime-extended, and if it is, it needs to be in the global address space.  
The only disadvantage of that is that we'd have to use global memory even for 
non-extended temporaries in global initializers.

Richard might have thoughts about this.  I don't know if there's been any 
language work around copy-elision and/or lifetime-extension that might be 
stretchable to allow us to delay the address-space decision until later.


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

https://reviews.llvm.org/D69938



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


[PATCH] D69122: Add support to find out resource dir and add it as compilation args

2019-11-21 Thread Michael Spencer via Phabricator via cfe-commits
Bigcheese added a comment.

Thanks, you're good to commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69122



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


[PATCH] D69022: [coroutines] Remove assert on CoroutineParameterMoves in Sema::buildCoroutineParameterMoves

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache requested changes to this revision.
modocache added a comment.
This revision now requires changes to proceed.

Sorry for the slow response here, @junparser!

The test case you came up with here is great! I can see the issue is that 
`ScopeInfo->CoroutineParameterMoves` are built up when Clang parses the first 
`co_await a`, but are not cleared when `lookupPromiseType` results in an error. 
As a result, when Clang hits the second `co_await a`, it's in a state that the 
current code didn't anticipate. Your test case does a great job demonstrating 
this. Your fix for the problem also looks good to me! My only suggestion is to 
make the test case just a little clearer, as I'll explain...

(Also, in the future could you please upload your patches with full context? 
You can read https://llvm.org/docs/Phabricator.html for more details. I think 
the section explaining the web interface might be relevant to you, where it 
suggests `git show HEAD -U99 > mypatch.patch`. The reason I ask is because 
on Phabricator I can see what lines you're proposing should be added, but not 
the surrounding source lines, which made this more difficult to review.)




Comment at: test/SemaCXX/coroutines.cpp:93
+  co_await a;
+}
+

This is a great test case, thanks for coming up with it! However, I think it 
could be a little clearer, though: right now the `int a` variable is shadowing 
the `awaitable a` that's declared further up in this file. At first, I wasn't 
sure whether the shadowing had something to do with the test, but in fact it 
doesn't. This test case demonstrates the issue but without the confusion, I 
think:

```
int no_promise_type_multiple_awaits(int) { // expected-error {{this function 
cannot be a coroutine: 'std::experimental::coroutine_traits' has no 
member named 'promise_type'}}
  co_await a;
  co_await a;
}
```


Repository:
  rC Clang

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

https://reviews.llvm.org/D69022



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


[PATCH] D69122: Add support to find out resource dir and add it as compilation args

2019-11-21 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk added inline comments.



Comment at: clang/tools/clang-scan-deps/ClangScanDeps.cpp:75-79
+llvm::Optional Redirects[] = {
+{""}, // Stdin
+StringRef(OutputFile),
+StringRef(ErrorFile),
+};

Bigcheese wrote:
> It would be nice if this didn't need to be a real file, but it looks like 
> `llvm::sys::Execute` can only handle file paths.
Yup - I'm going to leave it as such for now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69122



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


[PATCH] D69122: Add support to find out resource dir and add it as compilation args

2019-11-21 Thread Kousik Kumar via Phabricator via cfe-commits
kousikk updated this revision to Diff 230508.
kousikk marked 4 inline comments as done.
kousikk added a comment.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69122

Files:
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -13,6 +13,7 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
@@ -39,6 +40,64 @@
   raw_ostream 
 };
 
+class ResourceDirectoryCache {
+public:
+  /// findResourceDir finds the resource directory relative to the clang
+  /// compiler being used in Args, by running it with "-print-resource-dir"
+  /// option and cache the results for reuse. \returns resource directory path
+  /// associated with the given invocation command or empty string if the
+  /// compiler path is NOT an absolute path.
+  StringRef findResourceDir(const tooling::CommandLineArguments ) {
+if (Args.size() < 1)
+  return "";
+
+const std::string  = Args[0];
+if (!llvm::sys::path::is_absolute(ClangBinaryPath))
+  return "";
+
+const std::string  =
+llvm::sys::path::filename(ClangBinaryPath);
+
+std::unique_lock LockGuard(CacheLock);
+const auto  = Cache.find(ClangBinaryPath);
+if (CachedResourceDir != Cache.end())
+  return CachedResourceDir->second;
+
+std::vector PrintResourceDirArgs{ClangBinaryName,
+"-print-resource-dir"};
+llvm::SmallString<64> OutputFile, ErrorFile;
+llvm::sys::fs::createTemporaryFile("print-resource-dir-output",
+   "" /*no-suffix*/, OutputFile);
+llvm::sys::fs::createTemporaryFile("print-resource-dir-error",
+   "" /*no-suffix*/, ErrorFile);
+llvm::FileRemover OutputRemover(OutputFile.c_str());
+llvm::FileRemover ErrorRemover(ErrorFile.c_str());
+llvm::Optional Redirects[] = {
+{""}, // Stdin
+StringRef(OutputFile),
+StringRef(ErrorFile),
+};
+if (const int RC = llvm::sys::ExecuteAndWait(
+ClangBinaryPath, PrintResourceDirArgs, {}, Redirects)) {
+  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str());
+  llvm::errs() << ErrorBuf.get()->getBuffer();
+  return "";
+}
+
+auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str());
+if (!OutputBuf)
+  return "";
+StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
+
+Cache[ClangBinaryPath] = Output.str();
+return Cache[ClangBinaryPath];
+  }
+
+private:
+  std::map Cache;
+  std::mutex CacheLock;
+};
+
 llvm::cl::opt Help("h", llvm::cl::desc("Alias for -help"),
  llvm::cl::Hidden);
 
@@ -169,12 +228,15 @@
   auto AdjustingCompilations =
   std::make_unique(
   std::move(Compilations));
+  ResourceDirectoryCache ResourceDirCache;
   AdjustingCompilations->appendArgumentsAdjuster(
-  [](const tooling::CommandLineArguments , StringRef FileName) {
+  [](const tooling::CommandLineArguments ,
+  StringRef FileName) {
 std::string LastO = "";
 bool HasMT = false;
 bool HasMQ = false;
 bool HasMD = false;
+bool HasResourceDir = false;
 // We need to find the last -o value.
 if (!Args.empty()) {
   std::size_t Idx = Args.size() - 1;
@@ -188,6 +250,8 @@
 HasMQ = true;
   if (Args[Idx] == "-MD")
 HasMD = true;
+  if (Args[Idx] == "-resource-dir")
+HasResourceDir = true;
 }
 --Idx;
   }
@@ -215,6 +279,15 @@
 AdjustedArgs.push_back("-Xclang");
 AdjustedArgs.push_back("-sys-header-deps");
 AdjustedArgs.push_back("-Wno-error");
+
+if (!HasResourceDir) {
+  StringRef ResourceDir =
+  ResourceDirCache.findResourceDir(Args);
+  if (!ResourceDir.empty()) {
+AdjustedArgs.push_back("-resource-dir");
+AdjustedArgs.push_back(ResourceDir);
+  }
+}
 return AdjustedArgs;
   });
   AdjustingCompilations->appendArgumentsAdjuster(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70556: clang/Modules: Refactor CompilerInstance::loadModule, NFC

2019-11-21 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith marked 2 inline comments as done.
dexonsmith added inline comments.



Comment at: clang/include/clang/Frontend/CompilerInstance.h:801-804
+  ModuleLoadResult findOrCompileModuleAndReadAST(StringRef ModuleName,
+ SourceLocation ImportLoc,
+ SourceLocation ModuleNameLoc,
+ bool IsInclusionDirective);

I put this in the header to reduce how many parameters to pass in by-reference 
(it felt unnecessarily verbose).  But it's possible to make it a `static` in 
the source file if that's better.



Comment at: clang/lib/Frontend/CompilerInstance.cpp:1867-1874
 /// FIXME: perhaps we should (a) look for a module using the module name
 //  to file map (PrebuiltModuleFiles) and (b) diagnose if still not found?
 //if (Module == nullptr) {
 //  getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
 //<< ModuleName;
 //  ModuleBuildFailed = true;
 //  return ModuleLoadResult();

Note that this FIXME predates this patch (it has just moved).


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

https://reviews.llvm.org/D70556



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


[PATCH] D70488: [InstCombine] Infer fast math flags on fadd/fsub/fmul/fcmp

2019-11-21 Thread Benjamin Kramer via Phabricator via cfe-commits
bkramer added a comment.

In D70488#1753897 , @mcberg2017 wrote:

> For us this would be an impediment as we have math models that want ieee 
> behavior while relaxing precision.  Adding nnan or ninf would obstruct those 
> choices.


Mind elaborating why nnan/ninf are problematic for you? They're supposed to be 
a hint to the optimizer and can be dropped any time.

In D70488#1753832 , @spatel wrote:

> I like the idea, but I'd be more comfortable reviewing the diffs in stages, 
> so we know that the test coverage for the value tracking calls is good. So 
> I'd prefer if we split this somehow - either by the opcode callers (fadd, 
> fsub, fmul...) or the the FMF analysis (nnan, nsz, ninf). That raises a few 
> questions:
>
> 1. Why aren't fdiv and frem included?


We currently cannot infer anything for fdiv/frem in isKnownNeverNaN/Inf so 
there's no way to test it.

> 2. Can we infer FMF for FP intrinsics/libcalls/select/phi? (follow-on patches)

Yeah, that's a logical followup

> 3. We're moving away from FMF on fcmp (recent step: rGebf9bf2cbc8f 
> ), so is 
> it worth including starting from fcmp, or can we wait for that part to 
> settle? (Side question may be if/when we're going to allow FMF on 
> fptrunc/fpextend).

I'll drop fcmp then and split this up once we know that it's actually a 
direction we want to pursue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70488



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


[PATCH] D70556: clang/Modules: Refactor CompilerInstance::loadModule, NFC

2019-11-21 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: bruno, Bigcheese, jkorous, rsmith.
Herald added a subscriber: ributzka.

Refactor the logic on CompilerInstance::loadModule and a couple of
surrounding methods in order to clarify what's going on.

- Rename ModuleLoader::loadModuleFromSource to compileModuleFromSource and fix 
its documentation, since it never loads a module.  It just creates/compiles one.
- Rename one of the overloads of compileModuleImpl to compileModule, making it 
more obvious which one calls the other.
- Rename compileAndLoadModule to compileModuleAndReadAST.  This clarifies the 
relationship between this helper and its caller, CompilerInstance::loadModule 
(the old name implied the opposite relationship).  It also (correctly) 
indicates that more needs to be done to load the module than this function is 
responsible for.
- Split findOrCompileModuleAndReadAST out of loadModule.  Besides reducing 
nesting for this code thanks to early returns and the like, this refactor 
clarifies the logic in loadModule, particularly around calls to 
ModuleMap::cacheModuleLoad and ModuleMap::getCachedModuleLoad.  
findOrCompileModuleAndReadAST also breaks early if the initial ReadAST call 
returns Missing or OutOfDate, allowing the last ditch call to 
compileModuleAndReadAST to come at the end of the function body.
  - Additionally split out selectModuleSource, clarifying the logic due to 
early returns.
  - Add ModuleLoadResult::isNormal and OtherUncachedFailure, so that loadModule 
knows whether to cache the result. OtherUncachedFailure was added to keep this 
patch NFC, but there's a chance that these cases were uncached by accident, 
through copy/paste/modify failures.  These should be audited as a follow-up 
(maybe we can eliminate this case).
  - Do *not* lift the setting of `ModuleLoadFailed = true` to loadModule 
because there isn't a clear pattern for when it's set. This should be 
reconsidered in a follow-up, in case it would be correct to set 
`ModuleLoadFailed` whenever no module is returned and the result is either 
Normal or OtherUncachedFailure.
- Add some header documentation where it was missing, and fix it where it was 
wrong.

This should have no functionality change.


https://reviews.llvm.org/D70556

Files:
  clang/include/clang/Frontend/CompilerInstance.h
  clang/include/clang/Lex/ModuleLoader.h
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Lex/Pragma.cpp

Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -848,8 +848,8 @@
  CurLexer->getBuffer().begin() <= End &&
  End <= CurLexer->getBuffer().end() &&
  "module source range not contained within same file buffer");
-  TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
-   StringRef(Start, End - Start));
+  TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
+ StringRef(Start, End - Start));
 }
 
 void Preprocessor::HandlePragmaHdrstop(Token ) {
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -1179,13 +1179,12 @@
   return nullptr;
 }
 
-/// Compile a module file for the given module, using the options
-/// provided by the importing compiler instance. Returns true if the module
-/// was built without errors.
-static bool compileModuleImpl(CompilerInstance ,
-  SourceLocation ImportLoc,
-  Module *Module,
-  StringRef ModuleFileName) {
+/// Compile a module file for the given module in a separate compiler instance,
+/// using the options provided by the importing compiler instance. Returns true
+/// if the module was built without errors.
+static bool compileModule(CompilerInstance ,
+  SourceLocation ImportLoc, Module *Module,
+  StringRef ModuleFileName) {
   InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()),
InputKind::ModuleMap);
 
@@ -1245,10 +1244,17 @@
   return Result;
 }
 
-static bool compileAndLoadModule(CompilerInstance ,
- SourceLocation ImportLoc,
- SourceLocation ModuleNameLoc, Module *Module,
- StringRef ModuleFileName) {
+/// Compile a module in a separate compiler instance and read the AST,
+/// returning true if the module compiles without errors.
+///
+/// Uses a lock file manager and exponential backoff to reduce the chances that
+/// multiple instances will compete to create the same module.  On timeout,
+/// deletes the lock file in order to avoid deadlock from crashing processes or
+/// bugs in the lock file manager.
+static bool 

[PATCH] D70555: [coroutines] Don't build promise init with no args

2019-11-21 Thread Brian Gesiak via Phabricator via cfe-commits
modocache created this revision.
modocache added reviewers: GorNishanov, rsmith, lewissbaker.
Herald added subscribers: cfe-commits, EricWF.
Herald added a project: clang.
modocache edited the summary of this revision.

In the case of a coroutine that takes no arguments,
`Sema::buildCoroutinePromise` constructs a list-initialization
(`clang::InitializationKind::InitKind::IK_DirectList`) of the
promise variable, using a list of empty arguments. So, if one were to
dump the promise `VarDecl` immediately after `Sema::ActOnCoroutineBodyStart`
calls `checkCoroutineContext`, for a coroutine function that takes no
arguments, they'd see the following:

  VarDecl 0xb514490  col:3 __promise '' callinit
  `-ParenListExpr 0xb514510  'NULL TYPE'

But after this patch, the `ParenListExpr` is no longer constructed, and
the promise variable uses default initialization
(`clang::InitializationKind::InitKind::IK_Default`):

  VarDecl 0x63100012dae0  col:3 __promise ''

As far as I know, there's no case in which list-initialization with no
arguments differs from default initialization, but if I'm wrong please
let me know (and I'll add a test case that demonstrates the change --
but as-is I can't think of a functional test case for this). I think both
comply with the wording of C++20 `[dcl.fct.def.coroutine]p5`:

> _promise-constructor-arguments_ is determined as follows: overload
>  resolution is performed on a promise constructor call created by
>  assembling an argument list with lvalues `p1 ... pn`. If a viable
>  constructor is found (12.4.2), then _promise-constructor-arguments_
>  is `(p1, ... , pn)`, otherwise _promise-constructor-arguments_ is
>  empty.

Still, I think this patch is an improvement regardless, because it
reduces the size of the AST.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70555

Files:
  clang/lib/Sema/SemaCoroutine.cpp


Index: clang/lib/Sema/SemaCoroutine.cpp
===
--- clang/lib/Sema/SemaCoroutine.cpp
+++ clang/lib/Sema/SemaCoroutine.cpp
@@ -502,8 +502,9 @@
 return nullptr;
 
   auto *ScopeInfo = getCurFunction();
-  // Build a list of arguments, based on the coroutine functions arguments,
-  // that will be passed to the promise type's constructor.
+
+  // Build a list of arguments, based on the coroutine function's arguments,
+  // that if present will be passed to the promise type's constructor.
   llvm::SmallVector CtorArgExprs;
 
   // Add implicit object parameter.
@@ -519,6 +520,7 @@
 }
   }
 
+  // Add the coroutine function's parameters.
   auto  = ScopeInfo->CoroutineParameterMoves;
   for (auto *PD : FD->parameters()) {
 if (PD->getType()->isDependentType())
@@ -540,28 +542,33 @@
 CtorArgExprs.push_back(RefExpr.get());
   }
 
-  // Create an initialization sequence for the promise type using the
-  // constructor arguments, wrapped in a parenthesized list expression.
-  Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
-CtorArgExprs, FD->getLocation());
-  InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
-  InitializationKind Kind = InitializationKind::CreateForInit(
-  VD->getLocation(), /*DirectInit=*/true, PLE);
-  InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
- /*TopLevelOfInitList=*/false,
- /*TreatUnavailableAsInvalid=*/false);
-
-  // Attempt to initialize the promise type with the arguments.
-  // If that fails, fall back to the promise type's default constructor.
-  if (InitSeq) {
-ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
-if (Result.isInvalid()) {
-  VD->setInvalidDecl();
-} else if (Result.get()) {
-  VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
-  VD->setInitStyle(VarDecl::CallInit);
-  CheckCompleteVariableDeclaration(VD);
-}
+  // If we have a non-zero number of constructor arguments, try to use them.
+  // Otherwise, fall back to the promise type's default constructor.
+  if (!CtorArgExprs.empty()) {
+// Create an initialization sequence for the promise type using the
+// constructor arguments, wrapped in a parenthesized list expression.
+Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
+  CtorArgExprs, FD->getLocation());
+InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
+InitializationKind Kind = InitializationKind::CreateForInit(
+VD->getLocation(), /*DirectInit=*/true, PLE);
+InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
+   /*TopLevelOfInitList=*/false,
+   /*TreatUnavailableAsInvalid=*/false);
+
+// Attempt to initialize the promise type with the arguments.
+// If that fails, fall back to the promise type's default constructor.
+if (InitSeq) {
+ 

[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D70551#173 , @sdmitriev wrote:

> In D70551#1755527 , @ABataev wrote:
>
> > Why do we need this?
>
>
> To pass wrapper bitcode directly to the linker when LTO is enabled. LTO 
> plugin does not accept bc if there is no data layout.


Maybe it would better to pass it a parameter just like for opt?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[PATCH] D70554: [libTooling] Add stencil combinators for nodes that may be pointers or values.

2019-11-21 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel created this revision.
ymandel added a reviewer: gribozavr.
Herald added a project: clang.

Adds combinators `asValue` and `asPointer` to provide a uniform way to handle
nodes which may be bound to either a pointer or a value (most often in the
context of member expressions). Such polymorphism is already supported by
`access`; these combinators extend it to more general uses.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70554

Files:
  clang/include/clang/Tooling/Transformer/Stencil.h
  clang/lib/Tooling/Transformer/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -233,6 +233,46 @@
   testExpr(Id, "int *x; *x;", addressOf(Id), "x");
 }
 
+TEST_F(StencilTest, AsValueValue) {
+  StringRef Id = "id";
+  testExpr(Id, "int x; x;", asValue(Id), "x");
+}
+
+TEST_F(StencilTest, AsValuePointer) {
+  StringRef Id = "id";
+  testExpr(Id, "int *x; x;", asValue(Id), "*x");
+}
+
+TEST_F(StencilTest, AsValueBinOp) {
+  StringRef Id = "id";
+  testExpr(Id, "int *x; x + 1;", asValue(Id), "*(x + 1)");
+}
+
+TEST_F(StencilTest, AsValueAddressExpr) {
+  StringRef Id = "id";
+  testExpr(Id, "int x; ", asValue(Id), "x");
+}
+
+TEST_F(StencilTest, AsPointerPointer) {
+  StringRef Id = "id";
+  testExpr(Id, "int *x; x;", asPointer(Id), "x");
+}
+
+TEST_F(StencilTest, AsPointerValue) {
+  StringRef Id = "id";
+  testExpr(Id, "int x; x;", addressOf(Id), "");
+}
+
+TEST_F(StencilTest, AsPointerBinOp) {
+  StringRef Id = "id";
+  testExpr(Id, "int x; x + 1;", asPointer(Id), "&(x + 1)");
+}
+
+TEST_F(StencilTest, AsPointerDerefExpr) {
+  StringRef Id = "id";
+  testExpr(Id, "int *x; *x;", addressOf(Id), "x");
+}
+
 TEST_F(StencilTest, AccessOpValue) {
   StringRef Snippet = R"cc(
 S x;
Index: clang/lib/Tooling/Transformer/Stencil.cpp
===
--- clang/lib/Tooling/Transformer/Stencil.cpp
+++ clang/lib/Tooling/Transformer/Stencil.cpp
@@ -60,6 +60,8 @@
   Parens,
   Deref,
   Address,
+  AsValue,
+  AsPointer,
 };
 
 // Generic container for stencil operations with a (single) node-id argument.
@@ -124,6 +126,12 @@
   case UnaryNodeOperator::Address:
 OpName = "addressOf";
 break;
+  case UnaryNodeOperator::AsValue:
+OpName = "asValue";
+break;
+  case UnaryNodeOperator::AsPointer:
+OpName = "asPointer";
+break;
   }
   return (OpName + "(\"" + Data.Id + "\")").str();
 }
@@ -194,6 +202,21 @@
   case UnaryNodeOperator::Address:
 Source = tooling::buildAddressOf(*E, *Match.Context);
 break;
+  case UnaryNodeOperator::AsValue:
+if (!E->getType()->isAnyPointerType()) {
+  *Result += tooling::getText(*E, *Match.Context);
+  return Error::success();
+}
+Source = tooling::buildDereference(*E, *Match.Context);
+break;
+
+  case UnaryNodeOperator::AsPointer:
+if (E->getType()->isAnyPointerType()) {
+  *Result += tooling::getText(*E, *Match.Context);
+  return Error::success();
+}
+Source = tooling::buildAddressOf(*E, *Match.Context);
+break;
   }
   if (!Source)
 return llvm::make_error(
@@ -305,6 +328,16 @@
   UnaryNodeOperator::Address, ExprId);
 }
 
+Stencil transformer::asValue(llvm::StringRef ExprId) {
+  return std::make_shared>(
+  UnaryNodeOperator::AsValue, ExprId);
+}
+
+Stencil transformer::asPointer(llvm::StringRef ExprId) {
+  return std::make_shared>(
+  UnaryNodeOperator::AsPointer, ExprId);
+}
+
 Stencil transformer::access(StringRef BaseId, Stencil Member) {
   return std::make_shared>(BaseId, std::move(Member));
 }
Index: clang/include/clang/Tooling/Transformer/Stencil.h
===
--- clang/include/clang/Tooling/Transformer/Stencil.h
+++ clang/include/clang/Tooling/Transformer/Stencil.h
@@ -92,6 +92,14 @@
 /// needed.
 Stencil addressOf(llvm::StringRef ExprId);
 
+// Constructs an expression that idiomatically represents a value, taking into
+// account whether `ExprId` is a pointer or already a value.
+Stencil asValue(llvm::StringRef ExprId);
+
+// Constructs an expression that idiomatically represents a pointer, taking into
+// account whether `ExprId` is a value or already a pointer.
+Stencil asPointer(llvm::StringRef ExprId);
+
 /// Constructs a `MemberExpr` that accesses the named member (\p Member) of the
 /// object bound to \p BaseId. The access is constructed idiomatically: if \p
 /// BaseId is bound to `e` and \p Member identifies member `m`, then returns
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5fcf89f - [PowerPC] Add new Future CPU for PowerPC

2019-11-21 Thread Stefan Pintilie via cfe-commits

Author: Stefan Pintilie
Date: 2019-11-21T13:35:48-06:00
New Revision: 5fcf89f77893b4c3367f23dd82b426f783e67cff

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

LOG: [PowerPC] Add new Future CPU for PowerPC

This patch will add -mcpu=future into clang for PowerPC.

A CPU type is required for work that may possibly be enabled for some future
Power CPU. The CPU type future will serve that purpose. This patch introduces
no new functionality. It is an incremental patch on top of which Power PC work
for some future CPU can be done.

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

Added: 


Modified: 
clang/lib/Basic/Targets/PPC.cpp
clang/lib/Basic/Targets/PPC.h
clang/lib/Driver/ToolChains/Arch/PPC.cpp
clang/test/Misc/target-invalid-cpu-note.c
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index baa96e21707b..1877d4a5ef70 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -159,6 +159,8 @@ void PPCTargetInfo::getTargetDefines(const LangOptions 
,
   }
   if (ArchDefs & ArchDefineE500)
 Builder.defineMacro("__NO_LWSYNC__");
+  if (ArchDefs & ArchDefineFuture)
+Builder.defineMacro("_ARCH_PWR_FUTURE");
 
   if (getTriple().getVendor() == llvm::Triple::BGQ) {
 Builder.defineMacro("__bg__");
@@ -319,6 +321,13 @@ bool PPCTargetInfo::initFeatureMap(
 .Case("e500", true)
 .Default(false);
 
+  // Future CPU should include all of the features of Power 9 as well as any
+  // additional features (yet to be determined) specific to it.
+  if (CPU == "future") {
+initFeatureMap(Features, Diags, "pwr9", FeaturesVec);
+addFutureSpecificFeatures(Features);
+  }
+
   if (!ppcUserFeaturesCheck(Diags, FeaturesVec))
 return false;
 
@@ -332,6 +341,12 @@ bool PPCTargetInfo::initFeatureMap(
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
 }
 
+// Add features specific to the "Future" CPU.
+void PPCTargetInfo::addFutureSpecificFeatures(
+llvm::StringMap ) const {
+  return;
+}
+
 bool PPCTargetInfo::hasFeature(StringRef Feature) const {
   return llvm::StringSwitch(Feature)
   .Case("powerpc", true)
@@ -466,6 +481,7 @@ static constexpr llvm::StringLiteral ValidCPUNames[] = {
 {"pwr6"},  {"power6x"},   {"pwr6x"},   {"power7"},  {"pwr7"},
 {"power8"},{"pwr8"},  {"power9"},  {"pwr9"},
{"powerpc"},
 {"ppc"},   {"powerpc64"}, {"ppc64"},   {"powerpc64le"}, 
{"ppc64le"},
+{"future"}
 };
 
 bool PPCTargetInfo::isValidCPUName(StringRef Name) const {

diff  --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h
index 847338bbac1b..7c7307461f91 100644
--- a/clang/lib/Basic/Targets/PPC.h
+++ b/clang/lib/Basic/Targets/PPC.h
@@ -43,9 +43,10 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
 ArchDefinePwr7 = 1 << 11,
 ArchDefinePwr8 = 1 << 12,
 ArchDefinePwr9 = 1 << 13,
-ArchDefineA2 = 1 << 14,
-ArchDefineA2q = 1 << 15,
-ArchDefineE500 = 1 << 16
+ArchDefineFuture = 1 << 14,
+ArchDefineA2 = 1 << 15,
+ArchDefineA2q = 1 << 16,
+ArchDefineE500 = 1 << 17
   } ArchDefineTypes;
 
 
@@ -146,6 +147,11 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
  ArchDefinePwr9 | ArchDefinePwr8 | ArchDefinePwr7 |
  ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 |
  ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
+  .Case("future",
+ArchDefineFuture | ArchDefinePwr9 | ArchDefinePwr8 |
+ArchDefinePwr7 | ArchDefinePwr6 | ArchDefinePwr5x |
+ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr |
+ArchDefinePpcsq)
   .Cases("8548", "e500", ArchDefineE500)
   .Default(ArchDefineNone);
 }
@@ -166,6 +172,8 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
  StringRef CPU,
  const std::vector ) const override;
 
+  void addFutureSpecificFeatures(llvm::StringMap ) const;
+
   bool handleTargetFeatures(std::vector ,
 DiagnosticsEngine ) override;
 

diff  --git a/clang/lib/Driver/ToolChains/Arch/PPC.cpp 
b/clang/lib/Driver/ToolChains/Arch/PPC.cpp
index e1b0311f2ad0..625f7cb2f1f3 100644
--- a/clang/lib/Driver/ToolChains/Arch/PPC.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/PPC.cpp
@@ -70,6 +70,7 @@ std::string ppc::getPPCTargetCPU(const ArgList ) {
 .Case("power7", "pwr7")
 .Case("power8", "pwr8")
 .Case("power9", "pwr9")
+.Case("future", "future")
 

[PATCH] D70262: [PowerPC] Add new Future CPU for PowerPC

2019-11-21 Thread Stefan Pintilie via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5fcf89f77893: [PowerPC] Add new Future CPU for PowerPC 
(authored by stefanp).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70262

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/lib/Driver/ToolChains/Arch/PPC.cpp
  clang/test/Misc/target-invalid-cpu-note.c
  clang/test/Preprocessor/init.c

Index: clang/test/Preprocessor/init.c
===
--- clang/test/Preprocessor/init.c
+++ clang/test/Preprocessor/init.c
@@ -6452,6 +6452,22 @@
 // PPCPOWER9:#define _ARCH_PWR7 1
 // PPCPOWER9:#define _ARCH_PWR9 1
 //
+// RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc64-none-none -target-cpu future -fno-signed-char < /dev/null | FileCheck -match-full-lines -check-prefix PPCFUTURE %s
+//
+// PPCFUTURE:#define _ARCH_PPC 1
+// PPCFUTURE:#define _ARCH_PPC64 1
+// PPCFUTURE:#define _ARCH_PPCGR 1
+// PPCFUTURE:#define _ARCH_PPCSQ 1
+// PPCFUTURE:#define _ARCH_PWR4 1
+// PPCFUTURE:#define _ARCH_PWR5 1
+// PPCFUTURE:#define _ARCH_PWR5X 1
+// PPCFUTURE:#define _ARCH_PWR6 1
+// PPCFUTURE-NOT:#define _ARCH_PWR6X 1
+// PPCFUTURE:#define _ARCH_PWR7 1
+// PPCFUTURE:#define _ARCH_PWR8 1
+// PPCFUTURE:#define _ARCH_PWR9 1
+// PPCFUTURE:#define _ARCH_PWR_FUTURE 1
+//
 // RUN: %clang_cc1 -E -dM -ffreestanding -triple=powerpc64-none-none -target-feature +float128 -target-cpu power9 -fno-signed-char < /dev/null | FileCheck -check-prefix PPC-FLOAT128 %s
 // PPC-FLOAT128:#define __FLOAT128__ 1
 //
Index: clang/test/Misc/target-invalid-cpu-note.c
===
--- clang/test/Misc/target-invalid-cpu-note.c
+++ clang/test/Misc/target-invalid-cpu-note.c
@@ -82,7 +82,7 @@
 // PPC-SAME: 8548, 970, g5, a2, a2q, e500, e500mc, e5500, power3, pwr3, power4,
 // PPC-SAME: pwr4, power5, pwr5, power5x, pwr5x, power6, pwr6, power6x, pwr6x,
 // PPC-SAME: power7, pwr7, power8, pwr8, power9, pwr9, powerpc, ppc, powerpc64,
-// PPC-SAME: ppc64, powerpc64le, ppc64le
+// PPC-SAME: ppc64, powerpc64le, ppc64le, future
 
 // RUN: not %clang_cc1 -triple mips--- -target-cpu not-a-cpu -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix MIPS
 // MIPS: error: unknown target CPU 'not-a-cpu'
Index: clang/lib/Driver/ToolChains/Arch/PPC.cpp
===
--- clang/lib/Driver/ToolChains/Arch/PPC.cpp
+++ clang/lib/Driver/ToolChains/Arch/PPC.cpp
@@ -70,6 +70,7 @@
 .Case("power7", "pwr7")
 .Case("power8", "pwr8")
 .Case("power9", "pwr9")
+.Case("future", "future")
 .Case("pwr3", "pwr3")
 .Case("pwr4", "pwr4")
 .Case("pwr5", "pwr5")
Index: clang/lib/Basic/Targets/PPC.h
===
--- clang/lib/Basic/Targets/PPC.h
+++ clang/lib/Basic/Targets/PPC.h
@@ -43,9 +43,10 @@
 ArchDefinePwr7 = 1 << 11,
 ArchDefinePwr8 = 1 << 12,
 ArchDefinePwr9 = 1 << 13,
-ArchDefineA2 = 1 << 14,
-ArchDefineA2q = 1 << 15,
-ArchDefineE500 = 1 << 16
+ArchDefineFuture = 1 << 14,
+ArchDefineA2 = 1 << 15,
+ArchDefineA2q = 1 << 16,
+ArchDefineE500 = 1 << 17
   } ArchDefineTypes;
 
 
@@ -146,6 +147,11 @@
  ArchDefinePwr9 | ArchDefinePwr8 | ArchDefinePwr7 |
  ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 |
  ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
+  .Case("future",
+ArchDefineFuture | ArchDefinePwr9 | ArchDefinePwr8 |
+ArchDefinePwr7 | ArchDefinePwr6 | ArchDefinePwr5x |
+ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr |
+ArchDefinePpcsq)
   .Cases("8548", "e500", ArchDefineE500)
   .Default(ArchDefineNone);
 }
@@ -166,6 +172,8 @@
  StringRef CPU,
  const std::vector ) const override;
 
+  void addFutureSpecificFeatures(llvm::StringMap ) const;
+
   bool handleTargetFeatures(std::vector ,
 DiagnosticsEngine ) override;
 
Index: clang/lib/Basic/Targets/PPC.cpp
===
--- clang/lib/Basic/Targets/PPC.cpp
+++ clang/lib/Basic/Targets/PPC.cpp
@@ -159,6 +159,8 @@
   }
   if (ArchDefs & ArchDefineE500)
 Builder.defineMacro("__NO_LWSYNC__");
+  if (ArchDefs & ArchDefineFuture)
+Builder.defineMacro("_ARCH_PWR_FUTURE");
 
   if (getTriple().getVendor() == llvm::Triple::BGQ) {
 Builder.defineMacro("__bg__");
@@ -319,6 +321,13 @@
 .Case("e500", true)
 .Default(false);
 
+  // Future CPU should include all of the features of Power 9 as well 

[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added a comment.

In D70551#1755527 , @ABataev wrote:

> Why do we need this?


To pass wrapper bitcode directly to the linker when LTO is enabled. LTO plugin 
does not accept bc if there is no data layout.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[PATCH] D70368: [clang-tidy] Rewrite modernize-avoid-bind check

2019-11-21 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

Changes should be also reflected in Release Notes.




Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:7
+The check finds uses of ``std::bind`` and ``boost::bind`` and replaces them
+with lambdas.  Lambdas will use value-capture unless reference capture is
+explicitly requested with ``std::ref`` or ``boost::ref``.

Please fix double space. Same in other places.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:12
+and free functions, and all variations thereof.  Anything that you can pass
+to the first argument of `bind` should be diagnosable.  Currently, the only
+known case where a fixit is unsupported is when the same placeholder is

Please use double back-ticks for bind.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:13
+to the first argument of `bind` should be diagnosable.  Currently, the only
+known case where a fixit is unsupported is when the same placeholder is
+specified multiple times in the parameter list.

fixit -> fix-it.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:49
+
+  If the option is set to non-zero, the check will append `auto&&...` to the 
end
+  of every placeholder parameter list.  Without this, it is possible for a 
fixit

Please use double back-ticks for auto&&



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:50
+  If the option is set to non-zero, the check will append `auto&&...` to the 
end
+  of every placeholder parameter list.  Without this, it is possible for a 
fixit
+  to perform an incorrect transformation in the case where the result of the 
bind

fixit -> fix-it.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:51
+  of every placeholder parameter list.  Without this, it is possible for a 
fixit
+  to perform an incorrect transformation in the case where the result of the 
bind
+  is used in the context of a type erased functor such as ``std::function`` 
which

Please use double back-ticks for bind.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:64
+
+is valid code, and returns `4`.  The actual values passed to `ignore_args` are
+simply ignored.  Without `PermissiveParameterList`, this would be transformed 
into

Please use double back-ticks for ignore_args.



Comment at: clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst:75
+
+which will *not* compile, since the lambda does not contain an `operator()` 
that
+that accepts 2 arguments.  With permissive parameter list, it instead generates

Please use double back-ticks for operator().


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

https://reviews.llvm.org/D70368



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


[PATCH] D70470: [analyzer] Add FuchsiaHandleCheck to catch handle leaks, use after frees and double frees

2019-11-21 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 230500.
xazax.hun edited the summary of this revision.
xazax.hun added a comment.

- Make the patch standalone and the check on by default for the fuchsia 
platform.


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

https://reviews.llvm.org/D70470

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
  clang/test/Analysis/fuchsia_handle.c

Index: clang/test/Analysis/fuchsia_handle.c
===
--- /dev/null
+++ clang/test/Analysis/fuchsia_handle.c
@@ -0,0 +1,112 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,fuchsia.FuchsiaHandleChecker -verify %s
+
+typedef __typeof__(sizeof(int)) size_t;
+typedef int zx_status_t;
+typedef __typeof__(sizeof(int)) zx_handle_t;
+typedef unsigned int uint32_t;
+#define NULL ((void *)0)
+
+#if defined(__clang__)
+#define XZ_HANDLE_ACQUIRE  __attribute__((acquire_handle))
+#define XZ_HANDLE_RELEASE  __attribute__((release_handle))
+#define XZ_HANDLE_USE  __attribute__((use_handle))
+#else
+#define XZ_HANDLE_ACQUIRE
+#define XZ_HANDLE_RELEASE
+#define XZ_HANDLE_USE
+#endif
+
+zx_status_t zx_channel_create(
+uint32_t options,
+XZ_HANDLE_ACQUIRE zx_handle_t* out0,
+zx_handle_t* out1 XZ_HANDLE_ACQUIRE);
+
+zx_status_t zx_handle_close(
+zx_handle_t handle XZ_HANDLE_RELEASE);
+
+void escape1(zx_handle_t *in);
+void escape2(zx_handle_t in);
+
+void use1(const zx_handle_t *in XZ_HANDLE_USE);
+void use2(zx_handle_t in XZ_HANDLE_USE);
+
+void checkNoLeak01() {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  zx_handle_close(sa);
+  zx_handle_close(sb);
+}
+
+void checkNoLeak02() {
+  zx_handle_t ay[2];
+  zx_channel_create(0, [0], [1]);
+  zx_handle_close(ay[0]);
+  zx_handle_close(ay[1]);
+}
+
+void checkNoLeak03() {
+  zx_handle_t ay[2];
+  zx_channel_create(0, [0], [1]);
+  for (int i = 0; i < 2; i++)
+zx_handle_close(ay[i]);
+}
+
+zx_handle_t checkNoLeak04() {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  zx_handle_close(sa);
+  return sb; // no warning
+}
+
+zx_handle_t checkNoLeak05(zx_handle_t *out1) {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  *out1 = sa;
+  return sb; // no warning
+}
+
+void checkNoLeak06() {
+  zx_handle_t sa, sb;
+  if (zx_channel_create(0, , ))
+return;
+  zx_handle_close(sa);
+  zx_handle_close(sb);
+} 
+
+void checkNoLeak07(int tag) {
+  zx_handle_t sa, sb;
+  if (zx_channel_create(0, , ))
+return;
+  escape1();
+  escape2(sb);
+}
+
+void checkNoLeak08(int tag) {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  use1();
+  if (tag)
+zx_handle_close(sa);
+  use2(sb); // expected-warning {{Potential leak of handle}}
+  zx_handle_close(sb);
+}
+
+void checkDoubleRelease01(int tag) {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  if (tag)
+zx_handle_close(sa);
+  zx_handle_close(sa); // expected-warning {{Releasing a previously released handle}}
+  zx_handle_close(sb);
+}
+
+void checkUseAfterFree01(int tag) {
+  zx_handle_t sa, sb;
+  zx_channel_create(0, , );
+  if (tag) {
+zx_handle_close(sa);
+use1(); // expected-warning {{Using a previously released handle}}
+  }
+  zx_handle_close(sb);
+  use2(sb); // expected-warning {{Using a previously released handle}}
+}
Index: clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
===
--- /dev/null
+++ clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -0,0 +1,469 @@
+//=== FuchsiaHandleChecker.cpp - Find handle leaks/double closes -*- C++ -*--=//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This checker checks if the handle of Fuchsia is properly used according to
+// following rules.
+//   - If a handle is acquired, it should be released before execution
+//ends.
+//   - If a handle is released, it should not be released again.
+//   - If a handle is released, it should not be used for other purposes
+//such as I/O.
+//
+// In this checker, each tracked handle is associated with a state. When the
+// handle variable is passed to different function calls or syscalls, its state
+// changes. The state changes can be generally represented by following ASCII
+// Art:
+//
+//+---+
+//|   |
+//|release_func failed|
+//|   +-+ 

[PATCH] D70544: Debug info: Emit objc_direct methods as members of their containing class

2019-11-21 Thread Adrian Prantl via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe0cabe280b80: Debug info: Emit objc_direct methods as 
members of their containing class (authored by aprantl).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D70544?vs=230477=230499#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70544

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGenObjC/debug-info-direct-method.m

Index: clang/test/CodeGenObjC/debug-info-direct-method.m
===
--- /dev/null
+++ clang/test/CodeGenObjC/debug-info-direct-method.m
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -dwarf-version=5 -emit-llvm -debug-info-kind=limited -w -triple x86_64-apple-darwin10 %s -o - | FileCheck %s
+// RUN: %clang_cc1 -dwarf-version=4 -emit-llvm -debug-info-kind=limited -w -triple x86_64-apple-darwin10 %s -o - | FileCheck %s
+
+__attribute__((objc_root_class))
+@interface Root
+@end
+
+@implementation Root
+- (int)getInt __attribute__((objc_direct)) {
+  return 42;
+}
+@end
+
+// Test that objc_direct methods are always (even in DWARF < 5) emitted
+// as members of their containing class.
+
+// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Root",
+// CHECK-SAME: elements: ![[MEMBERS:[0-9]+]],
+// CHECK-SAME: runtimeLang: DW_LANG_ObjC)
+// CHECK: ![[MEMBERS]] = !{![[GETTER:[0-9]+]]}
+// CHECK: ![[GETTER]] = !DISubprogram(name: "-[Root getInt]",
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -114,7 +114,10 @@
   llvm::SmallVector ObjCInterfaceCache;
 
   /// Cache of forward declarations for methods belonging to the interface.
-  llvm::DenseMap>
+  /// The extra bit on the DISubprogram specifies whether a method is
+  /// "objc_direct".
+  llvm::DenseMap>>
   ObjCMethodCache;
 
   /// Cache of references to clang modules and precompiled headers.
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3495,14 +3495,15 @@
   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
 return nullptr;
 
-  if (CGM.getCodeGenOpts().DwarfVersion < 5)
+  const auto *OMD = dyn_cast(D);
+  if (!OMD)
+return nullptr;
+
+  if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
 return nullptr;
 
   // Starting with DWARF V5 method declarations are emitted as children of
   // the interface type.
-  const auto *OMD = dyn_cast(D);
-  if (!OMD)
-return nullptr;
   auto *ID = dyn_cast_or_null(D->getDeclContext());
   if (!ID)
 ID = OMD->getClassInterface();
@@ -3517,7 +3518,7 @@
   InterfaceType, getObjCMethodName(OMD), StringRef(),
   InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
   DBuilder.finalizeSubprogram(FD);
-  ObjCMethodCache[ID].push_back(FD);
+  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
   return FD;
 }
 
@@ -4713,27 +4714,28 @@
 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
   }
 
-  if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
-// Add methods to interface.
-for (const auto  : ObjCMethodCache) {
-  if (P.second.empty())
-continue;
+  // Add methods to interface.
+  for (const auto  : ObjCMethodCache) {
+if (P.second.empty())
+  continue;
 
-  QualType QTy(P.first->getTypeForDecl(), 0);
-  auto It = TypeCache.find(QTy.getAsOpaquePtr());
-  assert(It != TypeCache.end());
+QualType QTy(P.first->getTypeForDecl(), 0);
+auto It = TypeCache.find(QTy.getAsOpaquePtr());
+assert(It != TypeCache.end());
 
-  llvm::DICompositeType *InterfaceDecl =
-  cast(It->second);
+llvm::DICompositeType *InterfaceDecl =
+cast(It->second);
 
-  SmallVector EltTys;
-  auto CurrenetElts = InterfaceDecl->getElements();
-  EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
-  for (auto  : P.second)
-EltTys.push_back(MD);
-  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
-  DBuilder.replaceArrays(InterfaceDecl, Elements);
-}
+auto CurElts = InterfaceDecl->getElements();
+SmallVector EltTys(CurElts.begin(), CurElts.end());
+
+// For DWARF v4 or earlier, only add objc_direct methods.
+for (auto  : P.second)
+  if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
+EltTys.push_back(SubprogramDirect.getPointer());
+
+llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
+DBuilder.replaceArrays(InterfaceDecl, Elements);
   }
 
   for (const auto  : ReplaceMap) {
___
cfe-commits mailing list

[PATCH] D70368: [clang-tidy] Rewrite modernize-avoid-bind check

2019-11-21 Thread Zachary Turner via Phabricator via cfe-commits
zturner updated this revision to Diff 230495.
zturner added a comment.

- Updated documentation for this check
- Incorporated additional suggestions from @aaron.ballman
- Fixed an invalid transformation that was generated when binding a member 
function and the second argument of `bind` (the object pointer) was a 
placeholder.  Test is added for this case as well.
- Fixed an invalid transformation that was generated when a placeholder index 
was entirely skipped, as in the call `std::bind(add, 0, _2);`  In this case we 
need to generate an unused placeholder in the first position of the resulting 
lambda's parameter list.
- Added a clang-tidy option `PermissiveParameterList` which appends `auto&&...` 
to the end of every lambda's placeholder list.  This is necessary in some 
situations to prevent clang-tidy from applying a fixit that causes the code to 
no longer compile.


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

https://reviews.llvm.org/D70368

Files:
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp
  clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.h
  clang-tools-extra/docs/clang-tidy/checks/modernize-avoid-bind.rst
  
clang-tools-extra/test/clang-tidy/checkers/modernize-avoid-bind-permissive-parameter-list.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-avoid-bind.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-avoid-bind.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-avoid-bind.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-avoid-bind.cpp
@@ -8,75 +8,62 @@
 template 
 bind_rt bind(Fp &&, Arguments &&...);
 }
+
+template 
+T ref(T );
 }
 
-int add(int x, int y) { return x + y; }
+namespace boost {
+template 
+class bind_rt {};
 
-void f() {
-  auto clj = std::bind(add, 2, 2);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind [modernize-avoid-bind]
-  // CHECK-FIXES: auto clj = [] { return add(2, 2); };
-}
+template 
+bind_rt bind(const Fp &, Arguments...);
 
-void g() {
-  int x = 2;
-  int y = 2;
-  auto clj = std::bind(add, x, y);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto clj = [=] { return add(x, y); };
+template 
+struct reference_wrapper {
+  explicit reference_wrapper(T ) {}
+};
+
+template 
+reference_wrapper const ref(T ) {
+  return reference_wrapper(t);
 }
 
-struct placeholder {};
-placeholder _1;
-placeholder _2;
+} // namespace boost
 
-void h() {
-  int x = 2;
-  auto clj = std::bind(add, x, _1);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto clj = [=](auto && arg1) { return add(x, arg1); };
-}
+namespace C {
+int add(int x, int y) { return x + y; }
+} // namespace C
 
-struct A;
-struct B;
-bool ABTest(const A &, const B &);
+struct Foo {
+  static int add(int x, int y) { return x + y; }
+};
 
-void i() {
-  auto BATest = std::bind(ABTest, _2, _1);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto BATest = [](auto && arg1, auto && arg2) { return ABTest(arg2, arg1); };
-}
+struct D {
+  D() = default;
+  void operator()(int x, int y) const {}
 
-void j() {
-  auto clj = std::bind(add, 2, 2, 2);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // No fix is applied for argument mismatches.
-  // CHECK-FIXES: auto clj = std::bind(add, 2, 2, 2);
-}
+  void MemberFunction(int x) {}
 
-void k() {
-  auto clj = std::bind(add, _1, _1);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // No fix is applied for reused placeholders.
-  // CHECK-FIXES: auto clj = std::bind(add, _1, _1);
-}
+  static D *create();
+};
 
-void m() {
-  auto clj = std::bind(add, 1, add(2, 5));
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // No fix is applied for nested calls.
-  // CHECK-FIXES: auto clj = std::bind(add, 1, add(2, 5));
-}
+struct F {
+  F(int x) {}
+  ~F() {}
 
-namespace C {
-  int add(int x, int y){ return x + y; }
-}
+  int get() { return 42; }
+};
 
-void n() {
-  auto clj = std::bind(C::add, 1, 1);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: prefer a lambda to std::bind
-  // CHECK-FIXES: auto clj = [] { return C::add(1, 1); };
-}
+void UseF(F);
+
+struct placeholder {};
+placeholder _1;
+placeholder _2;
+
+int add(int x, int y) { return x + y; }
+int addThree(int x, int y, int z) { return x + y + z; }
 
 // Let's fake a minimal std::function-like facility.
 namespace std {
@@ -114,10 +101,213 @@
   void Reset(std::function);
 };
 
-void test(Thing *t) {
+int GlobalVariable = 42;
+
+struct TestCaptureByValueStruct {
+  int MemberVariable;
+  static int StaticMemberVariable;
+  F MemberStruct;
+
+  void testCaptureByValue(int Param, F f) {
+int x = 3;
+int y = 4;
+auto AAA = std::bind(add, x, y);
+// CHECK-MESSAGES: :[[@LINE-1]]:16: 

[PATCH] D70485: [ARM,MVE] Add intrinsics to deal with predicates.

2019-11-21 Thread Dave Green via Phabricator via cfe-commits
dmgreen accepted this revision.
dmgreen added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70485



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


[PATCH] D70553: [clang-apply-replacements] Add command line option to overwrite readonly files.

2019-11-21 Thread Zachary Turner via Phabricator via cfe-commits
zturner created this revision.
zturner added reviewers: aaron.ballman, alexfh, hokein.
zturner added a project: clang-tools-extra.
Herald added a project: clang.

Some source code control systems attempt to prevent you from editing files 
unless you explicitly check them out.  This makes it impossible to use certain 
refactoring tools such as this, since only the tool itself is able to determine 
the set of files that need to be modified.  This patch adds a `--force` option 
which clears the read-only bit of the file so that it can be modified.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D70553

Files:
  clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp


Index: 
clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
===
--- 
clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
+++ 
clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
@@ -48,6 +48,10 @@
  "Use -style to choose formatting style.\n"),
 cl::cat(FormattingCategory));
 
+static cl::opt ForceOverwriteReadOnly(
+"force", cl::desc("Overwrite read-only files when applying 
replacements\n"),
+cl::init(false), cl::cat(ReplacementCategory));
+
 // FIXME: Consider making the default behaviour for finding a style
 // configuration file to start the search anew for every file being changed to
 // handle situations where the style is different for different parts of a
@@ -152,6 +156,13 @@
 
 // Write new file to disk
 std::error_code EC;
+if (ForceOverwriteReadOnly) {
+  using namespace llvm::sys::fs;
+  if (auto ErrorOrPerms = getPermissions(FileName)) {
+perms P = ErrorOrPerms.get();
+setPermissions(FileName, P | all_write);
+  }
+}
 llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::OF_None);
 if (EC) {
   llvm::errs() << "Could not open " << FileName << " for writing\n";


Index: clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
===
--- clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
+++ clang-tools-extra/clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp
@@ -48,6 +48,10 @@
  "Use -style to choose formatting style.\n"),
 cl::cat(FormattingCategory));
 
+static cl::opt ForceOverwriteReadOnly(
+"force", cl::desc("Overwrite read-only files when applying replacements\n"),
+cl::init(false), cl::cat(ReplacementCategory));
+
 // FIXME: Consider making the default behaviour for finding a style
 // configuration file to start the search anew for every file being changed to
 // handle situations where the style is different for different parts of a
@@ -152,6 +156,13 @@
 
 // Write new file to disk
 std::error_code EC;
+if (ForceOverwriteReadOnly) {
+  using namespace llvm::sys::fs;
+  if (auto ErrorOrPerms = getPermissions(FileName)) {
+perms P = ErrorOrPerms.get();
+setPermissions(FileName, P | all_write);
+  }
+}
 llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::OF_None);
 if (EC) {
   llvm::errs() << "Could not open " << FileName << " for writing\n";
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D68720: Support -fstack-clash-protection for x86

2019-11-21 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

https://reviews.llvm.org/rG397fa687691876de9ff0fbaaf0def3ac5a48899c

Commited?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D68720



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


[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Why do we need this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70551



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


[clang] e0cabe2 - Debug info: Emit objc_direct methods as members of their containing class

2019-11-21 Thread Adrian Prantl via cfe-commits

Author: Adrian Prantl
Date: 2019-11-21T11:01:10-08:00
New Revision: e0cabe280b80ab71045d90b2d6f1a70e5d4c5d05

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

LOG: Debug info: Emit objc_direct methods as members of their containing class

even in DWARF 4 and earlier. This allows the debugger to recognize
them as direct functions as opposed to Objective-C methods.



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

Added: 
clang/test/CodeGenObjC/debug-info-direct-method.m

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDebugInfo.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index a9b3831aa0b5..a8d4ed12808e 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3495,14 +3495,15 @@ llvm::DISubprogram 
*CGDebugInfo::getObjCMethodDeclaration(
   if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
 return nullptr;
 
-  if (CGM.getCodeGenOpts().DwarfVersion < 5)
+  const auto *OMD = dyn_cast(D);
+  if (!OMD)
+return nullptr;
+
+  if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
 return nullptr;
 
   // Starting with DWARF V5 method declarations are emitted as children of
   // the interface type.
-  const auto *OMD = dyn_cast(D);
-  if (!OMD)
-return nullptr;
   auto *ID = dyn_cast_or_null(D->getDeclContext());
   if (!ID)
 ID = OMD->getClassInterface();
@@ -3517,7 +3518,7 @@ llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
   InterfaceType, getObjCMethodName(OMD), StringRef(),
   InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
   DBuilder.finalizeSubprogram(FD);
-  ObjCMethodCache[ID].push_back(FD);
+  ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
   return FD;
 }
 
@@ -4713,27 +4714,28 @@ void CGDebugInfo::finalize() {
 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
   }
 
-  if (CGM.getCodeGenOpts().DwarfVersion >= 5) {
-// Add methods to interface.
-for (const auto  : ObjCMethodCache) {
-  if (P.second.empty())
-continue;
+  // Add methods to interface.
+  for (const auto  : ObjCMethodCache) {
+if (P.second.empty())
+  continue;
 
-  QualType QTy(P.first->getTypeForDecl(), 0);
-  auto It = TypeCache.find(QTy.getAsOpaquePtr());
-  assert(It != TypeCache.end());
+QualType QTy(P.first->getTypeForDecl(), 0);
+auto It = TypeCache.find(QTy.getAsOpaquePtr());
+assert(It != TypeCache.end());
 
-  llvm::DICompositeType *InterfaceDecl =
-  cast(It->second);
+llvm::DICompositeType *InterfaceDecl =
+cast(It->second);
 
-  SmallVector EltTys;
-  auto CurrenetElts = InterfaceDecl->getElements();
-  EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
-  for (auto  : P.second)
-EltTys.push_back(MD);
-  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
-  DBuilder.replaceArrays(InterfaceDecl, Elements);
-}
+auto CurElts = InterfaceDecl->getElements();
+SmallVector EltTys(CurElts.begin(), CurElts.end());
+
+// For DWARF v4 or earlier, only add objc_direct methods.
+for (auto  : P.second)
+  if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
+EltTys.push_back(SubprogramDirect.getPointer());
+
+llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
+DBuilder.replaceArrays(InterfaceDecl, Elements);
   }
 
   for (const auto  : ReplaceMap) {

diff  --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 5341bfa7f350..13e9c7a38fcc 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -114,7 +114,10 @@ class CGDebugInfo {
   llvm::SmallVector ObjCInterfaceCache;
 
   /// Cache of forward declarations for methods belonging to the interface.
-  llvm::DenseMap>
+  /// The extra bit on the DISubprogram specifies whether a method is
+  /// "objc_direct".
+  llvm::DenseMap>>
   ObjCMethodCache;
 
   /// Cache of references to clang modules and precompiled headers.

diff  --git a/clang/test/CodeGenObjC/debug-info-direct-method.m 
b/clang/test/CodeGenObjC/debug-info-direct-method.m
new file mode 100644
index ..f822088f946c
--- /dev/null
+++ b/clang/test/CodeGenObjC/debug-info-direct-method.m
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -dwarf-version=5 -emit-llvm -debug-info-kind=limited -w 
-triple x86_64-apple-darwin10 %s -o - | FileCheck %s
+// RUN: %clang_cc1 -dwarf-version=4 -emit-llvm -debug-info-kind=limited -w 
-triple x86_64-apple-darwin10 %s -o - | FileCheck %s
+
+__attribute__((objc_root_class))
+@interface Root
+@end
+
+@implementation Root
+- (int)getInt __attribute__((objc_direct)) {
+  return 42;
+}
+@end
+

[PATCH] D70551: [clang-offload-wrapper] Add data layout to the wrapper bitcode

2019-11-21 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev created this revision.
sdmitriev added a reviewer: ABataev.
Herald added subscribers: cfe-commits, mgorny.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70551

Files:
  clang/test/Driver/clang-offload-wrapper.c
  clang/tools/clang-offload-wrapper/CMakeLists.txt
  clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp

Index: clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
===
--- clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
+++ clang/tools/clang-offload-wrapper/ClangOffloadWrapper.cpp
@@ -29,9 +29,13 @@
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/ToolOutputFile.h"
 #include "llvm/Support/WithColor.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetOptions.h"
 #include "llvm/Transforms/Utils/ModuleUtils.h"
 #include 
 #include 
@@ -55,9 +59,9 @@
 cl::cat(ClangOffloadWrapperCategory));
 
 static cl::opt
-Target("target", cl::Required,
-   cl::desc("Target triple for the output module"),
-   cl::value_desc("triple"), cl::cat(ClangOffloadWrapperCategory));
+TargetTriple("target", cl::Required,
+ cl::desc("Target triple for the output module"),
+ cl::value_desc("triple"), cl::cat(ClangOffloadWrapperCategory));
 
 namespace {
 
@@ -287,8 +291,9 @@
   }
 
 public:
-  BinaryWrapper(StringRef Target) : M("offload.wrapper.object", C) {
-M.setTargetTriple(Target);
+  BinaryWrapper(const TargetMachine *TM) : M("offload.wrapper.object", C) {
+M.setTargetTriple(TM->getTargetTriple().getTriple());
+M.setDataLayout(TM->createDataLayout());
   }
 
   const Module (ArrayRef> Binaries) {
@@ -321,16 +326,33 @@
 return 0;
   }
 
+  InitializeAllTargets();
+  InitializeAllTargetMCs();
+
   auto reportError = [argv](Error E) {
 logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
   };
 
-  if (Triple(Target).getArch() == Triple::UnknownArch) {
-reportError(createStringError(
-errc::invalid_argument, "'" + Target + "': unsupported target triple"));
+  if (Triple(TargetTriple).getArch() == Triple::UnknownArch) {
+reportError(
+createStringError(errc::invalid_argument,
+  "'" + TargetTriple + "': unsupported target triple"));
 return 1;
   }
 
+  // Lookup and create target machine. We need it for setting data layout for
+  // the wrapper module.
+  std::string Error;
+  const Target *TheTarget = TargetRegistry::lookupTarget(TargetTriple, Error);
+  if (!TheTarget) {
+reportError(createStringError(errc::invalid_argument, Error));
+return 1;
+  }
+
+  std::unique_ptr TM(TheTarget->createTargetMachine(
+  TargetTriple, "", "", TargetOptions(), None));
+  assert(TM && "Could not allocate target machine!");
+
   // Read device binaries.
   SmallVector, 4u> Buffers;
   SmallVector, 4u> Images;
@@ -357,7 +379,7 @@
   }
 
   // Create a wrapper for device binaries and write its bitcode to the file.
-  WriteBitcodeToFile(BinaryWrapper(Target).wrapBinaries(
+  WriteBitcodeToFile(BinaryWrapper(TM.get()).wrapBinaries(
  makeArrayRef(Images.data(), Images.size())),
  Out.os());
   if (Out.os().has_error()) {
Index: clang/tools/clang-offload-wrapper/CMakeLists.txt
===
--- clang/tools/clang-offload-wrapper/CMakeLists.txt
+++ clang/tools/clang-offload-wrapper/CMakeLists.txt
@@ -1,4 +1,15 @@
-set(LLVM_LINK_COMPONENTS BitWriter Core Support TransformUtils)
+set(LLVM_LINK_COMPONENTS
+  AllTargetsAsmParsers
+  AllTargetsCodeGens
+  AllTargetsDescs
+  AllTargetsInfos
+  BitWriter
+  Core
+  MC
+  Support
+  Target
+  TransformUtils
+  )
 
 if(NOT CLANG_BUILT_STANDALONE)
   set(tablegen_deps intrinsics_gen)
Index: clang/test/Driver/clang-offload-wrapper.c
===
--- clang/test/Driver/clang-offload-wrapper.c
+++ clang/test/Driver/clang-offload-wrapper.c
@@ -22,6 +22,7 @@
 // RUN: clang-offload-wrapper -target=x86_64-pc-linux-gnu -o %t.wrapper.bc %t.tgt
 // RUN: llvm-dis %t.wrapper.bc -o - | FileCheck %s --check-prefix CHECK-IR
 
+// CHECK-IR: target datalayout =
 // CHECK-IR: target triple = "x86_64-pc-linux-gnu"
 
 // CHECK-IR-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70245: [OPENMP50]Add device/kind context selector support.

2019-11-21 Thread Alexey Bataev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4e8231b5cf0f: [OPENMP50]Add device/kind context selector 
support. (authored by ABataev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70245

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/OpenMP/declare_variant_ast_print.c
  clang/test/OpenMP/declare_variant_ast_print.cpp
  clang/test/OpenMP/declare_variant_device_kind_codegen.cpp
  clang/test/OpenMP/declare_variant_messages.c
  clang/test/OpenMP/declare_variant_messages.cpp
  clang/test/OpenMP/declare_variant_mixed_codegen.cpp
  clang/test/OpenMP/nvptx_declare_variant_device_kind_codegen.cpp

Index: clang/test/OpenMP/nvptx_declare_variant_device_kind_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/nvptx_declare_variant_device_kind_codegen.cpp
@@ -0,0 +1,170 @@
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc -fopenmp-version=50 -DGPU
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -fopenmp-version=50 -DGPU | FileCheck %s --implicit-check-not='ret i32 {{1|81|84}}'
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t -fopenmp-version=50 -DGPU
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - -fopenmp-version=50 -DGPU | FileCheck %s --implicit-check-not='ret i32 {{1|81|84}}'
+
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc -fopenmp-version=50 -DNOHOST
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -fopenmp-version=50 -DNOHOST | FileCheck %s --implicit-check-not='ret i32 {{1|81|84}}'
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -emit-pch -o %t -fopenmp-version=50 -DNOHOST
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -aux-triple powerpc64le-unknown-unknown -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -o - -fopenmp-version=50 -DNOHOST | FileCheck %s --implicit-check-not='ret i32 {{1|81|84}}'
+// expected-no-diagnostics
+
+// CHECK-NOT: ret i32 {{1|81|84}}
+// CHECK-DAG: define {{.*}}i32 @_Z3barv()
+// CHECK-DAG: define {{.*}}i32 @_ZN16SpecSpecialFuncs6MethodEv(%struct.SpecSpecialFuncs* %{{.+}})
+// CHECK-DAG: define {{.*}}i32 @_ZN12SpecialFuncs6MethodEv(%struct.SpecialFuncs* %{{.+}})
+// CHECK-DAG: define linkonce_odr {{.*}}i32 @_ZN16SpecSpecialFuncs6methodEv(%struct.SpecSpecialFuncs* %{{.+}})
+// CHECK-DAG: define linkonce_odr {{.*}}i32 @_ZN12SpecialFuncs6methodEv(%struct.SpecialFuncs* %{{.+}})
+// CHECK-DAG: define {{.*}}i32 @_Z5prio_v()
+// CHECK-DAG: define internal i32 @_ZL6prio1_v()
+// CHECK-DAG: define {{.*}}i32 @_Z4callv()
+// CHECK-DAG: define internal i32 @_ZL9stat_usedv()
+// CHECK-DAG: define {{.*}}i32 @fn_linkage()
+// CHECK-DAG: define {{.*}}i32 @_Z11fn_linkage1v()
+
+// CHECK-DAG: ret i32 2
+// CHECK-DAG: ret i32 3
+// CHECK-DAG: ret i32 4
+// CHECK-DAG: ret i32 5
+// CHECK-DAG: ret i32 6
+// CHECK-DAG: ret i32 7
+// CHECK-DAG: ret i32 82
+// CHECK-DAG: ret i32 83
+// CHECK-DAG: ret i32 85
+// CHECK-DAG: ret i32 86
+// CHECK-DAG: ret i32 87
+
+// Outputs for function members
+// CHECK-DAG: ret i32 6
+// CHECK-DAG: ret i32 7
+// CHECK-NOT: ret i32 {{1|81|84}}
+
+#ifndef HEADER
+#define HEADER
+
+#ifdef GPU
+#define CORRECT gpu
+#define SUBSET nohost, gpu
+#define WRONG cpu, gpu
+#endif // GPU
+#ifdef NOHOST
+#define CORRECT nohost
+#define SUBSET nohost, gpu
+#define WRONG nohost, host
+#endif // NOHOST
+
+int foo() { return 2; }
+int bazzz();
+int test();
+static int stat_unused_();
+static int stat_used_();
+
+#pragma omp declare target
+
+#pragma omp declare variant(foo) match(device = {kind(CORRECT)})
+int bar() { return 1; }
+
+#pragma omp declare variant(bazzz) match(device = {kind(CORRECT)})
+int baz() { return 1; }

[clang] 4e8231b - [OPENMP50]Add device/kind context selector support.

2019-11-21 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2019-11-21T13:28:11-05:00
New Revision: 4e8231b5cf0f5f62c7a51a857e29f5be5cb55734

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

LOG: [OPENMP50]Add device/kind context selector support.

Summary: Added basic parsing/sema support for device/kind context selector.

Reviewers: jdoerfert

Subscribers: rampitec, aheejin, fedor.sergeev, simoncook, guansong, s.egerton, 
hfinkel, kkwli0, caomhin, cfe-commits

Tags: #clang

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

Added: 
clang/test/OpenMP/declare_variant_device_kind_codegen.cpp
clang/test/OpenMP/declare_variant_mixed_codegen.cpp
clang/test/OpenMP/nvptx_declare_variant_device_kind_codegen.cpp

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/OpenMPKinds.def
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
clang/test/OpenMP/declare_variant_ast_print.c
clang/test/OpenMP/declare_variant_ast_print.cpp
clang/test/OpenMP/declare_variant_messages.c
clang/test/OpenMP/declare_variant_messages.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 3e55104f7637..e155593760ff 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3337,7 +3337,8 @@ def OMPDeclareVariant : InheritableAttr {
 VariadicExprArgument<"Scores">,
 VariadicUnsignedArgument<"CtxSelectorSets">,
 VariadicUnsignedArgument<"CtxSelectors">,
-VariadicStringArgument<"ImplVendors">
+VariadicStringArgument<"ImplVendors">,
+VariadicStringArgument<"DeviceKinds">
   ];
   let AdditionalMembers = [{
 void printScore(raw_ostream & OS, const PrintingPolicy , unsigned 
I) const {
@@ -3377,6 +3378,27 @@ def OMPDeclareVariant : InheritableAttr {
 }
 OS << ")";
 break;
+  case OMP_CTX_kind:
+llvm_unreachable("Unexpected context selector in implementation 
set.");
+  case OMP_CTX_unknown:
+llvm_unreachable("Unknown context selector.");
+  }
+  OS << "}";
+  break;
+case OMP_CTX_SET_device:
+  OS << "device={";
+  switch (Ctx) {
+  case OMP_CTX_kind:
+OS << "kind(";
+if (deviceKinds_size() > 0) {
+  OS << *deviceKinds().begin();
+  for (StringRef KindName : llvm::drop_begin(deviceKinds(), 1))
+OS << ", " << KindName;
+}
+OS << ")";
+break;
+  case OMP_CTX_vendor:
+llvm_unreachable("Unexpected context selector in device set.");
   case OMP_CTX_unknown:
 llvm_unreachable("Unknown context selector.");
   }
@@ -3385,6 +3407,8 @@ def OMPDeclareVariant : InheritableAttr {
 case OMP_CTX_SET_unknown:
   llvm_unreachable("Unknown context selector set.");
 }
+if (I != E - 1)
+  OS << ",";
   }
   OS << ")";
 }

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index dc9f677ec5b6..c94d1b99d0e8 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1225,6 +1225,9 @@ def note_omp_declare_variant_ctx_used_here : Note<
 def warn_omp_more_one_device_type_clause : Warning<
   "more than one 'device_type' clause is specified">,
   InGroup;
+def err_omp_wrong_device_kind_trait : Error<
+  "unknown '%0' device kind trait in the 'device' context selector set, 
expected"
+  " one of 'host', 'nohost', 'cpu', 'gpu' or 'fpga'">;
 
 // Pragma loop support.
 def err_pragma_loop_missing_argument : Error<

diff  --git a/clang/include/clang/Basic/OpenMPKinds.def 
b/clang/include/clang/Basic/OpenMPKinds.def
index a0efd1675178..e79a6bf954da 100644
--- a/clang/include/clang/Basic/OpenMPKinds.def
+++ b/clang/include/clang/Basic/OpenMPKinds.def
@@ -221,9 +221,11 @@
 
 // OpenMP context selector sets.
 OPENMP_CONTEXT_SELECTOR_SET(implementation)
+OPENMP_CONTEXT_SELECTOR_SET(device)
 
 // OpenMP context selectors.
 OPENMP_CONTEXT_SELECTOR(vendor)
+OPENMP_CONTEXT_SELECTOR(kind)
 
 // OpenMP directives.
 OPENMP_DIRECTIVE(threadprivate)

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index df5e2d05d9a0..347606fc7461 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -20,6 +20,7 @@
 #include "clang/AST/StmtOpenMP.h"
 #include "clang/Basic/BitmaskEnum.h"
 #include "llvm/ADT/ArrayRef.h"
+#include 

[PATCH] D70544: Debug info: Emit objc_direct methods as members of their containing class

2019-11-21 Thread Jonas Devlieghere via Phabricator via cfe-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.

LGTM with two minor comments.




Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:4729
 
-  SmallVector EltTys;
-  auto CurrenetElts = InterfaceDecl->getElements();
-  EltTys.append(CurrenetElts.begin(), CurrenetElts.end());
-  for (auto  : P.second)
-EltTys.push_back(MD);
-  llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
-  DBuilder.replaceArrays(InterfaceDecl, Elements);
-}
+SmallVector EltTys;
+auto CurrentElts = InterfaceDecl->getElements();

You could move this down and use the `SmallVector` ctor that takes two 
iterators. Although it only saves one line I think it better expresses your 
intent. 



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:4733
+
+// For DWARF v.4 or earlier, only add objc_direct methods.
+for (auto  : P.second)

`s/v.4/v4/`


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

https://reviews.llvm.org/D70544



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


  1   2   >