[PATCH] D4784: [clang-tidy] Add check for possibly incomplete switch statements

2023-07-11 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta updated this revision to Diff 539390.
xgupta added a comment.

Update ReleaseNotes.rst


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

https://reviews.llvm.org/D4784

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
@@ -0,0 +1,27 @@
+// RUN: clang-tidy --checks='-*,misc-incomplete-switch' %s -- | FileCheck -implicit-check-not="{{warning|error}}:" %s
+
+void Positive() {
+  int i = 0;
+  // CHECK: [[@LINE+1]]:11: warning: switching on non-enum value without default case may not cover all cases [misc-incomplete-switch]
+  switch (i) {
+  case 0:
+break;
+  }
+}
+
+void Negative() {
+  enum E { eE1 };
+  E e = eE1;
+  switch (e) { // no-warning
+  case eE1:
+break;
+  }
+
+  int i = 0;
+  switch (i) { // no-warning
+  case 0:
+break;
+  default:
+break;
+  }
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -219,6 +219,11 @@
   Enforces consistent token representation for invoked binary, unary and
   overloaded operators in C++ code.
 
+- New :doc:`misc-incomplete-switch
+  ` check.
+
+  Detects incomplete switch statements without a default case.
+
 New check aliases
 ^
 
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "DefinitionsInHeadersCheck.h"
 #include "HeaderIncludeCycleCheck.h"
 #include "IncludeCleanerCheck.h"
+#include "IncompleteSwitchCheck.h"
 #include "MisleadingBidirectional.h"
 #include "MisleadingIdentifier.h"
 #include "MisplacedConstCheck.h"
@@ -46,6 +47,8 @@
 CheckFactories.registerCheck(
 "misc-header-include-cycle");
 CheckFactories.registerCheck("misc-include-cleaner");
+CheckFactories.registerCheck(
+"misc-incomplete-switch");
 CheckFactories.registerCheck(
 "misc-misleading-bidirectional");
 CheckFactories.registerCheck(
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
@@ -0,0 +1,29 @@
+//===--- IncompleteSwitchCheck.h - clang-tidy *- 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+namespace clang::tidy::misc {
+
+class IncompleteSwitchCheck : public ClangTidyCheck {
+public:
+  IncompleteSwitchCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace clang::tidy::misc
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
@@ -0,0 +1,36 @@
+//===--- IncompleteSwitchCheck.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 "IncompleteSwitchCheck.h"
+#include "clang/AST/ASTContext.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+
+void IncompleteSwitchCheck::registerMatchers(
+ast_matchers::MatchFinder *Finder) {
+  Finder->addMatcher(
+  switchStmt(has(implicitCastExpr().bind("cast")),
+ 

[PATCH] D153989: [compiler-rt] Move crt into builtins

2023-07-11 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added a comment.

I think reduplication of build logic makes sense but these are conceptually 
separate things. The compiler rt builtins are needed in many cases where the C 
start-up code isn't (e.g. baremetal OS code). Would moving it to a subdirectory 
of builtins/ work too? That way it's clearer which source files and tests are 
part of each component?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153989

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


[PATCH] D145302: [clangd] Add library for clangd main function

2023-07-11 Thread Khem Raj via Phabricator via cfe-commits
raj.khem added a comment.

indeed, broke my CI with same issue.

In D145302#4491973 , @glandium wrote:

> This broke building with `-DLLVM_LINK_LLVM_DYLIB=ON`:
>
>   /usr/bin/ld: 
> tools/clang/tools/extra/clangd/refactor/tweaks/CMakeFiles/obj.clangDaemonTweaks.dir/AddUsing.cpp.o:
>  in function `clang::clangd::(anonymous 
> namespace)::AddUsing::prepare(clang::clangd::Tweak::Selection const&)':
>   
> AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x1c):
>  undefined reference to `clang::clangd::ParsedAST::getASTContext()'
>   /usr/bin/ld: 
> AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x6d):
>  undefined reference to `clang::clangd::ParsedAST::getASTContext() const'
>   /usr/bin/ld: 
> AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x9a):
>  undefined reference to `clang::clangd::isHeaderFile(llvm::StringRef, 
> std::optional)'
>   /usr/bin/ld: 
> AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0xcc):
>  undefined reference to `clang::clangd::SelectionTree::commonAncestor() const'
>   /usr/bin/ld: 
> AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x391):
>  undefined reference to 
> `clang::clangd::printNamespaceScope[abi:cxx11](clang::DeclContext const&)'
>
> etc.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145302

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


[PATCH] D4784: [clang-tidy] Add check for possibly incomplete switch statements

2023-07-11 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta updated this revision to Diff 539389.
xgupta added a comment.

Address bkramer's comments except one for "checking that you're casting from an 
enum".


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

https://reviews.llvm.org/D4784

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
@@ -0,0 +1,27 @@
+// RUN: clang-tidy --checks='-*,misc-incomplete-switch' %s -- | FileCheck -implicit-check-not="{{warning|error}}:" %s
+
+void Positive() {
+  int i = 0;
+  // CHECK: [[@LINE+1]]:11: warning: switching on non-enum value without default case may not cover all cases [misc-incomplete-switch]
+  switch (i) {
+  case 0:
+break;
+  }
+}
+
+void Negative() {
+  enum E { eE1 };
+  E e = eE1;
+  switch (e) { // no-warning
+  case eE1:
+break;
+  }
+
+  int i = 0;
+  switch (i) { // no-warning
+  case 0:
+break;
+  default:
+break;
+  }
+}
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "DefinitionsInHeadersCheck.h"
 #include "HeaderIncludeCycleCheck.h"
 #include "IncludeCleanerCheck.h"
+#include "IncompleteSwitchCheck.h"
 #include "MisleadingBidirectional.h"
 #include "MisleadingIdentifier.h"
 #include "MisplacedConstCheck.h"
@@ -46,6 +47,8 @@
 CheckFactories.registerCheck(
 "misc-header-include-cycle");
 CheckFactories.registerCheck("misc-include-cleaner");
+CheckFactories.registerCheck(
+"misc-incomplete-switch");
 CheckFactories.registerCheck(
 "misc-misleading-bidirectional");
 CheckFactories.registerCheck(
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
@@ -0,0 +1,29 @@
+//===--- IncompleteSwitchCheck.h - clang-tidy *- 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+
+#include "../ClangTidyCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+namespace clang::tidy::misc {
+
+class IncompleteSwitchCheck : public ClangTidyCheck {
+public:
+  IncompleteSwitchCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace clang::tidy::misc
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
@@ -0,0 +1,36 @@
+//===--- IncompleteSwitchCheck.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 "IncompleteSwitchCheck.h"
+#include "clang/AST/ASTContext.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+
+void IncompleteSwitchCheck::registerMatchers(
+ast_matchers::MatchFinder *Finder) {
+  Finder->addMatcher(
+  switchStmt(has(implicitCastExpr().bind("cast")),
+ unless(hasAncestor(switchStmt(has(defaultStmt())
+  .bind("switch"),
+  this);
+}
+
+void IncompleteSwitchCheck::check(
+const ast_matchers::MatchFinder::MatchResult ) {
+  const auto *c = Result.Nodes.getNodeAs("cast");
+  if (c->getCastKind() == CK_IntegralCast)
+return;
+
+  const auto *s = Result.Nodes.getNodeAs("switch");
+  diag(s->getSwitchLoc(), "switching on non-enum value without "
+  "default case may not cover all cases");
+}
+
+} // 

[PATCH] D4784: [clang-tidy] Add check for possibly incomplete switch statements

2023-07-11 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta updated this revision to Diff 539383.
xgupta added a comment.

.


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

https://reviews.llvm.org/D4784

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
@@ -0,0 +1,27 @@
+// RUN: clang-tidy --checks='-*,misc-incomplete-switch' %s -- | FileCheck %s
+
+void Positive() {
+  int i = 0;
+  // CHECK: [[@LINE+1]]:11: warning: switching on non-enum value without default case may not cover all cases [misc-incomplete-switch]
+  switch (i) {
+  case 0:
+break;
+  }
+}
+
+void Negative() {
+  enum E { eE1 };
+  E e = eE1;
+  switch (e) { // no-warning
+  case eE1:
+break;
+  }
+
+  int i = 0;
+  switch (i) { // no-warning
+  case 0:
+break;
+  default:
+break;
+  }
+}
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "DefinitionsInHeadersCheck.h"
 #include "HeaderIncludeCycleCheck.h"
 #include "IncludeCleanerCheck.h"
+#include "IncompleteSwitchCheck.h"
 #include "MisleadingBidirectional.h"
 #include "MisleadingIdentifier.h"
 #include "MisplacedConstCheck.h"
@@ -46,6 +47,7 @@
 CheckFactories.registerCheck(
 "misc-header-include-cycle");
 CheckFactories.registerCheck("misc-include-cleaner");
+CheckFactories.registerCheck("misc-incomplete-switch");
 CheckFactories.registerCheck(
 "misc-misleading-bidirectional");
 CheckFactories.registerCheck(
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
@@ -0,0 +1,31 @@
+//===--- IncompleteSwitchCheck.h - clang-tidy *- 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+
+class IncompleteSwitchCheck : public ClangTidyCheck {
+public:
+  IncompleteSwitchCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
@@ -0,0 +1,35 @@
+//===--- IncompleteSwitchCheck.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 "IncompleteSwitchCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+
+void IncompleteSwitchCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
+  Finder->addMatcher(
+  switchStmt(hasDescendant(implicitCastExpr().bind("cast")),
+ unless(hasDescendant(defaultStmt(.bind("switch"),
+  this);
+}
+
+void IncompleteSwitchCheck::check(
+const ast_matchers::MatchFinder::MatchResult ) {
+  const auto *c = Result.Nodes.getNodeAs("cast");
+  if (c->getCastKind() == CK_IntegralCast)
+return;
+
+  const auto *s = Result.Nodes.getNodeAs("switch");
+  diag(s->getSwitchLoc(), "switching on non-enum value without "
+  "default case may not cover all cases");
+}
+
+} // namespace tidy
+} // namespace clang
Index: clang-tools-extra/clang-tidy/misc/CMakeLists.txt
===
--- 

[PATCH] D154969: [dataflow] document flow condition

2023-07-11 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfa689726768b: [dataflow] document flow condition (authored 
by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D154969?vs=539086=539381#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154969

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h


Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -22,6 +22,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Logger.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
@@ -524,16 +525,30 @@
 arena().makeEquals(LHS.formula(), RHS.formula()));
   }
 
-  /// Returns the token that identifies the flow condition of the environment.
+  /// Returns a boolean variable that identifies the flow condition (FC).
+  ///
+  /// The flow condition is a set of facts that are necessarily true when the
+  /// program reaches the current point, expressed as boolean formulas.
+  /// The flow condition token is equivalent to the AND of these facts.
+  ///
+  /// These may e.g. constrain the value of certain variables. A pointer
+  /// variable may have a consistent modeled PointerValue throughout, but at a
+  /// given point the Environment may tell us that the value must be non-null.
+  ///
+  /// The FC is necessary but not sufficient for this point to be reachable.
+  /// In particular, where the FC token appears in flow conditions of successor
+  /// environments, it means "point X may have been reached", not
+  /// "point X was reached".
   Atom getFlowConditionToken() const { return FlowConditionToken; }
 
-  /// Adds `Val` to the set of clauses that constitute the flow condition.
+  /// Record a fact that must be true if this point in the program is reached.
   void addToFlowCondition(const Formula &);
   /// Deprecated: Use Formula version instead.
   void addToFlowCondition(BoolValue );
 
-  /// Returns true if and only if the clauses that constitute the flow 
condition
-  /// imply that `Val` is true.
+  /// Returns true if the formula is always true when this point is reached.
+  /// Returns false if the formula may be false, or if the flow condition isn't
+  /// sufficiently precise to prove that it is true.
   bool flowConditionImplies(const Formula &) const;
   /// Deprecated: Use Formula version instead.
   bool flowConditionImplies(BoolValue ) const;


Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -22,6 +22,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Logger.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
@@ -524,16 +525,30 @@
 arena().makeEquals(LHS.formula(), RHS.formula()));
   }
 
-  /// Returns the token that identifies the flow condition of the environment.
+  /// Returns a boolean variable that identifies the flow condition (FC).
+  ///
+  /// The flow condition is a set of facts that are necessarily true when the
+  /// program reaches the current point, expressed as boolean formulas.
+  /// The flow condition token is equivalent to the AND of these facts.
+  ///
+  /// These may e.g. constrain the value of certain variables. A pointer
+  /// variable may have a consistent modeled PointerValue throughout, but at a
+  /// given point the Environment may tell us that the value must be non-null.
+  ///
+  /// The FC is necessary but not sufficient for this point to be reachable.
+  /// In particular, where the FC token appears in flow conditions of successor
+  /// environments, it means "point X may have been reached", not
+  /// "point X was reached".
   Atom getFlowConditionToken() const { return FlowConditionToken; }
 
-  /// Adds `Val` to the set of clauses that constitute the flow condition.
+  /// Record a fact that must be true if this point in the program is reached.
   void addToFlowCondition(const Formula &);
   /// 

[clang] fa68972 - [dataflow] document flow condition

2023-07-11 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2023-07-12T07:20:46+02:00
New Revision: fa689726768b7b5cae01970cce2e59a72a0229b4

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

LOG: [dataflow] document flow condition

There's some documentation of this concept at
https://clang.llvm.org/docs/DataFlowAnalysisIntro.html
but it would be nice to have it closer to the code.

I also was laboring under an obvious but wrong mental model that
the flow condition token represented "execution reached this point",
I'd like to explicitly call that out as wrong.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 5bd2e5518a5463..512f66073da457 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -22,6 +22,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Logger.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
@@ -524,16 +525,30 @@ class Environment {
 arena().makeEquals(LHS.formula(), RHS.formula()));
   }
 
-  /// Returns the token that identifies the flow condition of the environment.
+  /// Returns a boolean variable that identifies the flow condition (FC).
+  ///
+  /// The flow condition is a set of facts that are necessarily true when the
+  /// program reaches the current point, expressed as boolean formulas.
+  /// The flow condition token is equivalent to the AND of these facts.
+  ///
+  /// These may e.g. constrain the value of certain variables. A pointer
+  /// variable may have a consistent modeled PointerValue throughout, but at a
+  /// given point the Environment may tell us that the value must be non-null.
+  ///
+  /// The FC is necessary but not sufficient for this point to be reachable.
+  /// In particular, where the FC token appears in flow conditions of successor
+  /// environments, it means "point X may have been reached", not
+  /// "point X was reached".
   Atom getFlowConditionToken() const { return FlowConditionToken; }
 
-  /// Adds `Val` to the set of clauses that constitute the flow condition.
+  /// Record a fact that must be true if this point in the program is reached.
   void addToFlowCondition(const Formula &);
   /// Deprecated: Use Formula version instead.
   void addToFlowCondition(BoolValue );
 
-  /// Returns true if and only if the clauses that constitute the flow 
condition
-  /// imply that `Val` is true.
+  /// Returns true if the formula is always true when this point is reached.
+  /// Returns false if the formula may be false, or if the flow condition isn't
+  /// sufficiently precise to prove that it is true.
   bool flowConditionImplies(const Formula &) const;
   /// Deprecated: Use Formula version instead.
   bool flowConditionImplies(BoolValue ) const;



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


[PATCH] D4784: [clang-tidy] Add check for possibly incomplete switch statements

2023-07-11 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta updated this revision to Diff 539378.
xgupta retitled this revision from "[clang-tidy] Add check for possibly 
incomplete switch statements
" to "[clang-tidy] Add check for possibly incomplete switch statements".
xgupta added a reviewer: PiotrZSL.
xgupta added a comment.
Herald added a reviewer: njames93.
Herald added a project: clang-tools-extra.

Just updated the patch to trunk


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

https://reviews.llvm.org/D4784

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
  clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc/incomplete-switch.cpp
@@ -0,0 +1,27 @@
+// RUN: clang-tidy --checks='-*,misc-incomplete-switch' %s -- | FileCheck %s
+
+void Positive() {
+  int i = 0;
+  // CHECK: [[@LINE+1]]:11: warning: switching on non-enum value without default case may not cover all cases [misc-incomplete-switch]
+  switch (i) {
+  case 0:
+break;
+  }
+}
+
+void Negative() {
+  enum E { eE1 };
+  E e = eE1;
+  switch (e) { // no-warning
+  case eE1:
+break;
+  }
+
+  int i = 0;
+  switch (i) { // no-warning
+  case 0:
+break;
+  default:
+break;
+  }
+}
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "DefinitionsInHeadersCheck.h"
 #include "HeaderIncludeCycleCheck.h"
 #include "IncludeCleanerCheck.h"
+#include "IncompleteSwitchCheck.h"
 #include "MisleadingBidirectional.h"
 #include "MisleadingIdentifier.h"
 #include "MisplacedConstCheck.h"
@@ -46,6 +47,7 @@
 CheckFactories.registerCheck(
 "misc-header-include-cycle");
 CheckFactories.registerCheck("misc-include-cleaner");
+CheckFactories.registerCheck("misc-incomplete-switch");
 CheckFactories.registerCheck(
 "misc-misleading-bidirectional");
 CheckFactories.registerCheck(
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.h
@@ -0,0 +1,23 @@
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+
+class IncompleteSwitchCheck : public ClangTidyCheck {
+public:
+  IncompleteSwitchCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_INCOMPLETESWITCHCHECK_H
Index: clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/IncompleteSwitchCheck.cpp
@@ -0,0 +1,27 @@
+#include "IncompleteSwitchCheck.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+
+void IncompleteSwitchCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
+  Finder->addMatcher(
+  switchStmt(hasDescendant(implicitCastExpr().bind("cast")),
+ unless(hasDescendant(defaultStmt(.bind("switch"),
+  this);
+}
+
+void IncompleteSwitchCheck::check(
+const ast_matchers::MatchFinder::MatchResult ) {
+  const auto *c = Result.Nodes.getNodeAs("cast");
+  if (c->getCastKind() == CK_IntegralCast)
+return;
+
+  const auto *s = Result.Nodes.getNodeAs("switch");
+  diag(s->getSwitchLoc(), "switching on non-enum value without "
+  "default case may not cover all cases");
+}
+
+} // namespace tidy
+} // namespace clang
Index: clang-tools-extra/clang-tidy/misc/CMakeLists.txt
===
--- clang-tools-extra/clang-tidy/misc/CMakeLists.txt
+++ clang-tools-extra/clang-tidy/misc/CMakeLists.txt
@@ -22,6 +22,7 @@
   ConfusableIdentifierCheck.cpp
   HeaderIncludeCycleCheck.cpp
   IncludeCleanerCheck.cpp
+  IncompleteSwitchCheck.cpp
   MiscTidyModule.cpp
   MisleadingBidirectional.cpp
   MisleadingIdentifier.cpp
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D153701: [WIP][Clang] Implement P2718R0 "Lifetime extension in range-based for loops"

2023-07-11 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:8901-8914
+  // [P2718R0] Lifetime extension in range-based for loops.
+  //
+  // 6.7.7 [class.temporary] p5:
+  // There are four contexts in which temporaries are destroyed at a different
+  // point than the end of the full-expression.
+  //
+  // 6.7.7 [class.temporary] p6:

yronglin wrote:
> rsmith wrote:
> > This isn't the right way to model the behavior here -- the presence or 
> > absence of an `ExprWithCleanups` is just a convenience to tell consumers of 
> > the AST whether they should expect to see cleanups later or not, and 
> > doesn't carry an implication of affecting the actual temporary lifetimes 
> > and storage durations.
> > 
> > The outcome that we should be aiming to reach is that all 
> > `MaterializeTemporaryExpr`s created as part of processing the 
> > for-range-initializer are marked as being lifetime-extended by the 
> > for-range variable. Probably the simplest way to handle that would be to 
> > track the current enclosing for-range-initializer variable in the 
> > `ExpressionEvaluationContextRecord`, and whenever a 
> > `MaterializeTemporaryExpr` is created, if there is a current enclosing 
> > for-range-initializer, mark that `MaterializeTemporaryExpr` as being 
> > lifetime-extended by it.
> Awesome! Thanks a lot for your advice, this is very helpful! I want to take a 
> longer look at it.
As mentioned in D139586, `CXXDefaultArgExpr`s may need additional handling. 
Similarly for `CXXDefaultInitExpr`s.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153701

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


[PATCH] D154965: [clang][dataflow] Fix initializing a reference field with an `InitListExpr`.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbd9b57de4ff7: [clang][dataflow] Fix initializing a reference 
field with an `InitListExpr`. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154965

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2912,6 +2912,34 @@
   }
 }
 
+TEST(TransferTest, AggregateInitializationReferenceField) {
+  std::string Code = R"(
+struct S {
+  int 
+};
+
+void target(int i) {
+  S s = { i };
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> ,
+ ASTContext ) {
+const Environment  = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");
+
+auto  = getLocForDecl(ASTCtx, Env, "i");
+auto  = getLocForDecl(ASTCtx, Env, "s");
+
+auto  =
+*cast(getFieldValue(, *RefFieldDecl, Env));
+EXPECT_EQ((), );
+  });
+}
+
 TEST(TransferTest, AssignToUnionMember) {
   std::string Code = R"(
 union A {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -717,14 +717,15 @@
 if (Type->isStructureOrClassType()) {
   std::vector Fields =
   getFieldsForInitListExpr(Type->getAsRecordDecl());
-  for (auto It : llvm::zip(Fields, S->inits())) {
-const FieldDecl *Field = std::get<0>(It);
+  for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
 assert(Field != nullptr);
-
-const Expr *Init = std::get<1>(It);
 assert(Init != nullptr);
 
-if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
+if (Field->getType()->isReferenceType()) {
+  if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
+cast(Val)->setChild(*Field,
+ Env.create(*Loc));
+} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
   cast(Val)->setChild(*Field, *InitVal);
   }
 }


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2912,6 +2912,34 @@
   }
 }
 
+TEST(TransferTest, AggregateInitializationReferenceField) {
+  std::string Code = R"(
+struct S {
+  int 
+};
+
+void target(int i) {
+  S s = { i };
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> ,
+ ASTContext ) {
+const Environment  = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");
+
+auto  = getLocForDecl(ASTCtx, Env, "i");
+auto  = getLocForDecl(ASTCtx, Env, "s");
+
+auto  =
+*cast(getFieldValue(, *RefFieldDecl, Env));
+EXPECT_EQ((), );
+  });
+}
+
 TEST(TransferTest, AssignToUnionMember) {
   std::string Code = R"(
 union A {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -717,14 +717,15 @@
 if (Type->isStructureOrClassType()) {
   std::vector Fields =
   getFieldsForInitListExpr(Type->getAsRecordDecl());
-  for (auto It : llvm::zip(Fields, S->inits())) {
-const FieldDecl *Field = std::get<0>(It);
+  for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
 assert(Field != nullptr);
-
-const Expr *Init = std::get<1>(It);
 assert(Init != nullptr);
 
-if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
+if (Field->getType()->isReferenceType()) {
+  if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
+cast(Val)->setChild(*Field,
+ Env.create(*Loc));
+} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
   cast(Val)->setChild(*Field, *InitVal);
   }
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154961: [clang][dataflow] Include fields initialized in an `InitListExpr` in `getModeledFields()`.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb47bdcbc7207: [clang][dataflow] Include fields initialized 
in an `InitListExpr` in… (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154961

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2833,6 +2833,7 @@
 
 void target(int BarArg, int FooArg, int QuxArg) {
   B Quux{BarArg, {FooArg}, QuxArg};
+  B OtherB;
   /*[[p]]*/
 }
   )";
@@ -2849,6 +2850,7 @@
 
 void target(int BarArg, int FooArg, int QuxArg) {
   B Quux = {BarArg, FooArg, QuxArg};
+  B OtherB;
   /*[[p]]*/
 }
   )";
@@ -2898,6 +2900,14 @@
   EXPECT_EQ(getFieldValue(QuuxVal, *BarDecl, Env), BarArgVal);
   EXPECT_EQ(getFieldValue(BazVal, *FooDecl, Env), FooArgVal);
   EXPECT_EQ(getFieldValue(QuuxVal, *QuxDecl, Env), QuxArgVal);
+
+  // Check that fields initialized in an initializer list are always
+  // modeled in other instances of the same type.
+  const auto  =
+  getValueForDecl(ASTCtx, Env, "OtherB");
+  EXPECT_THAT(OtherBVal.getChild(*BarDecl), NotNull());
+  EXPECT_THAT(OtherBVal.getChild(*BazDecl), NotNull());
+  EXPECT_THAT(OtherBVal.getChild(*QuxDecl), NotNull());
 });
   }
 }
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -715,14 +715,8 @@
 Env.setValue(Loc, *Val);
 
 if (Type->isStructureOrClassType()) {
-  // Unnamed bitfields are only used for padding and are not appearing in
-  // `InitListExpr`'s inits. However, those fields do appear in RecordDecl's
-  // field list, and we thus need to remove them before mapping inits to
-  // fields to avoid mapping inits to the wrongs fields.
-  std::vector Fields;
-  llvm::copy_if(
-  Type->getAsRecordDecl()->fields(), std::back_inserter(Fields),
-  [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
+  std::vector Fields =
+  getFieldsForInitListExpr(Type->getAsRecordDecl());
   for (auto It : llvm::zip(Fields, S->inits())) {
 const FieldDecl *Field = std::get<0>(It);
 assert(Field != nullptr);
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -215,6 +215,10 @@
 insertIfFunction(*VD, Funcs);
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
+  } else if (auto *InitList = dyn_cast()) {
+if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
+  for (const auto *FD : getFieldsForInitListExpr(RD))
+Fields.insert(FD);
   }
 }
 
@@ -958,5 +962,17 @@
   return cast(Loc);
 }
 
+std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
+  // Unnamed bitfields are only used for padding and do not appear in
+  // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
+  // field list, and we thus need to remove them before mapping inits to
+  // fields to avoid mapping inits to the wrongs fields.
+  std::vector Fields;
+  llvm::copy_if(
+  RD->fields(), std::back_inserter(Fields),
+  [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
+  return Fields;
+}
+
 } // namespace dataflow
 } // namespace clang
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -644,6 +644,10 @@
 AggregateStorageLocation *getBaseObjectLocation(const MemberExpr ,
 const Environment );
 
+/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in the
+/// order in which they appear in `InitListExpr::inits()`.
+std::vector getFieldsForInitListExpr(const RecordDecl *RD);
+
 } // namespace dataflow
 } // namespace clang
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D154952: [clang][dataflow] Various refactorings in TypeErasedDataflowAnalysisTest.cpp

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1e9b4fc1dcf2: [clang][dataflow] Various refactorings in 
TypeErasedDataflowAnalysisTest.cpp (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154952

Files:
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -370,6 +370,13 @@
   // FIXME: Called functions at point `p` should contain only "foo".
 }
 
+StructValue (AggregateStorageLocation ,
+  Environment ) {
+  auto  = *cast(Env.createValue(Loc.getType()));
+  Env.setValue(Loc, Val);
+  return Val;
+}
+
 // Models an analysis that uses flow conditions.
 class SpecialBoolAnalysis final
 : public DataflowAnalysis {
@@ -390,23 +397,18 @@
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), 
*S,
   getASTContext( {
-  auto  = *Env.createValue(E->getType());
-  ConstructorVal.setProperty("is_set", Env.getBoolLiteralValue(false));
-  Env.setValue(*Env.getStorageLocation(*E, SkipPast::None), 
ConstructorVal);
+  cast(Env.getValueStrict(*E))
+  ->setProperty("is_set", Env.getBoolLiteralValue(false));
 } else if (const auto *E = selectFirst(
"call", 
match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(

SpecialBoolRecordDecl
  .bind("call"),
  *S, getASTContext( {
-  auto *Object = E->getImplicitObjectArgument();
-  assert(Object != nullptr);
-
-  auto *ObjectLoc = getImplicitObjectLocation(*E, Env);
-  assert(ObjectLoc != nullptr);
+  auto  =
+  *cast(getImplicitObjectLocation(*E, Env));
 
-  auto  = *Env.createValue(Object->getType());
-  ConstructorVal.setProperty("is_set", Env.getBoolLiteralValue(true));
-  Env.setValue(*ObjectLoc, ConstructorVal);
+  createNewStructValue(ObjectLoc, Env)
+  .setProperty("is_set", Env.getBoolLiteralValue(true));
 }
   }
 
@@ -551,21 +553,19 @@
 *S, getASTContext());
 if (const auto *E = selectFirst(
 "construct", Matches)) {
-  auto  = *Env.createValue(E->getType());
-  ConstructorVal.setProperty("has_value", Env.getBoolLiteralValue(false));
-  Env.setValue(*Env.getStorageLocation(*E, SkipPast::None), 
ConstructorVal);
+  cast(Env.getValueStrict(*E))
+  ->setProperty("has_value", Env.getBoolLiteralValue(false));
 } else if (const auto *E =
selectFirst("operator", Matches)) {
   assert(E->getNumArgs() > 0);
   auto *Object = E->getArg(0);
   assert(Object != nullptr);
 
-  auto *ObjectLoc = Env.getStorageLocation(*Object, SkipPast::Reference);
-  assert(ObjectLoc != nullptr);
+  auto  = *cast(
+  Env.getStorageLocation(*Object, SkipPast::Reference));
 
-  auto  = *Env.createValue(Object->getType());
-  ConstructorVal.setProperty("has_value", Env.getBoolLiteralValue(true));
-  Env.setValue(*ObjectLoc, ConstructorVal);
+  createNewStructValue(ObjectLoc, Env)
+  .setProperty("has_value", Env.getBoolLiteralValue(true));
 }
   }
 
@@ -1227,9 +1227,7 @@
 match(callExpr(callee(functionDecl(hasName("makeTop".bind("top"),
   *S, getASTContext());
 if (const auto *E = selectFirst("top", Matches)) {
-  auto  = Env.createStorageLocation(*E);
-  Env.setValue(Loc, Env.makeTopBoolValue());
-  Env.setStorageLocation(*E, Loc);
+  Env.setValueStrict(*E, Env.makeTopBoolValue());
 }
   }
 


Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -370,6 +370,13 @@
   // FIXME: Called functions at point `p` should contain only "foo".
 }
 
+StructValue (AggregateStorageLocation ,
+  Environment ) {
+  auto  = *cast(Env.createValue(Loc.getType()));
+  Env.setValue(Loc, Val);
+  return Val;
+}
+
 // Models an analysis that uses flow conditions.
 class SpecialBoolAnalysis final
 : public DataflowAnalysis {
@@ -390,23 +397,18 @@
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), *S,
  

[PATCH] D154949: [clang][dataflow] Use `getFieldValue()` in TransferTest.cpp.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG103a0fc08460: [clang][dataflow] Use `getFieldValue()` in 
TransferTest.cpp. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154949

Files:
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -262,7 +262,8 @@
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -310,7 +311,8 @@
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -357,7 +359,8 @@
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -470,37 +473,37 @@
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
-const auto *FooReferentVal = cast(Env.getValue(*FooLoc));
+const auto  =
+*cast(Env.getStorageLocation(*FooDecl));
+const auto  = *cast(Env.getValue(FooLoc));
 
-const auto *BarVal =
-cast(FooReferentVal->getChild(*BarDecl));
-const auto *BarReferentVal =
-cast(Env.getValue(BarVal->getReferentLoc()));
+const auto  =
+*cast(FooReferentVal.getChild(*BarDecl));
+const auto  =
+*cast(Env.getValue(BarVal.getReferentLoc()));
 
-const auto *FooRefVal =
-cast(BarReferentVal->getChild(*FooRefDecl));
+const auto  =
+*cast(getFieldValue(, *FooRefDecl, Env));
 const auto  =
-cast(FooRefVal->getReferentLoc());
+cast(FooRefVal.getReferentLoc());
 EXPECT_THAT(Env.getValue(FooReferentLoc), NotNull());
-EXPECT_THAT(Env.getValue(FooReferentLoc.getChild(*BarDecl)), IsNull());
+EXPECT_THAT(getFieldValue(, *BarDecl, Env), IsNull());
 
-const auto *FooPtrVal =
-cast(BarReferentVal->getChild(*FooPtrDecl));
+const auto  =
+*cast(getFieldValue(, *FooPtrDecl, Env));
 const auto  =
-cast(FooPtrVal->getPointeeLoc());
+cast(FooPtrVal.getPointeeLoc());
 EXPECT_THAT(Env.getValue(FooPtrPointeeLoc), NotNull());
-EXPECT_THAT(Env.getValue(FooPtrPointeeLoc.getChild(*BarDecl)), IsNull());
+EXPECT_THAT(getFieldValue(, *BarDecl, Env), IsNull());
 
-const auto *BazRefVal =
-cast(BarReferentVal->getChild(*BazRefDecl));
-const StorageLocation  = BazRefVal->getReferentLoc();
+const auto  =
+*cast(getFieldValue(, *BazRefDecl, Env));
+const StorageLocation  = BazRefVal.getReferentLoc();
 EXPECT_THAT(Env.getValue(BazReferentLoc), NotNull());
 
-const auto *BazPtrVal =
-cast(BarReferentVal->getChild(*BazPtrDecl));
-const StorageLocation  = BazPtrVal->getPointeeLoc();
+const auto  =
+*cast(getFieldValue(, *BazPtrDecl, Env));
+const StorageLocation  = BazPtrVal.getPointeeLoc();
 EXPECT_THAT(Env.getValue(BazPtrPointeeLoc), NotNull());
   });
 }
@@ -630,35 +633,36 @@
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
-const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *FooPointeeVal =
-cast(Env.getValue(FooVal->getPointeeLoc()));
-
-const auto *BarVal =
-cast(FooPointeeVal->getChild(*BarDecl));
-const auto *BarPointeeVal =
-cast(Env.getValue(BarVal->getPointeeLoc()));
-
-const auto *FooRefVal =
-cast(BarPointeeVal->getChild(*FooRefDecl));
-const StorageLocation  = FooRefVal->getReferentLoc();
+const auto  =
+*cast(Env.getStorageLocation(*FooDecl));
+const auto  = *cast(Env.getValue(FooLoc));
+const auto  =
+*cast(Env.getValue(FooVal.getPointeeLoc()));
+
+const auto  =
+*cast(getFieldValue(, *BarDecl, Env));
+const auto  =
+

[PATCH] D154935: [clang][dataflow] Introduce `getFieldValue()` test helpers.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2902ea3d817b: [clang][dataflow] Introduce `getFieldValue()` 
test helpers. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154935

Files:
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -451,6 +451,28 @@
   return *cast(Env.getValue(*VD));
 }
 
+/// Returns the value of a `Field` on the record referenced by `Loc.`
+/// Returns null if `Loc` is null.
+inline Value *getFieldValue(const AggregateStorageLocation *Loc,
+const ValueDecl , const Environment ) {
+  if (Loc == nullptr)
+return nullptr;
+  return Env.getValue(Loc->getChild(Field));
+}
+
+/// Returns the value of a `Field` on a `Struct.
+/// Returns null if `Struct` is null.
+///
+/// Note: This function currently does not use the `Env` parameter, but it will
+/// soon be needed to look up the `Value` when `setChild()` changes to return a
+/// `StorageLocation *`.
+inline Value *getFieldValue(const StructValue *Struct, const ValueDecl ,
+const Environment ) {
+  if (Struct == nullptr)
+return nullptr;
+  return Struct->getChild(Field);
+}
+
 /// Creates and owns constraints which are boolean values.
 class ConstraintContext {
   unsigned NextAtom = 0;
Index: clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
@@ -63,12 +63,12 @@
 auto  = cast(S1.getChild(*InnerDecl));
 auto  = cast(S2.getChild(*InnerDecl));
 
-EXPECT_NE(Env.getValue(S1.getChild(*OuterIntDecl)),
-  Env.getValue(S2.getChild(*OuterIntDecl)));
+EXPECT_NE(getFieldValue(, *OuterIntDecl, Env),
+  getFieldValue(, *OuterIntDecl, Env));
 EXPECT_NE(Env.getValue(S1.getChild(*RefDecl)),
   Env.getValue(S2.getChild(*RefDecl)));
-EXPECT_NE(Env.getValue(Inner1.getChild(*InnerIntDecl)),
-  Env.getValue(Inner2.getChild(*InnerIntDecl)));
+EXPECT_NE(getFieldValue(, *InnerIntDecl, Env),
+  getFieldValue(, *InnerIntDecl, Env));
 
 auto *S1Val = cast(Env.getValue(S1));
 auto *S2Val = cast(Env.getValue(S2));
@@ -78,12 +78,12 @@
 
 copyRecord(S1, S2, Env);
 
-EXPECT_EQ(Env.getValue(S1.getChild(*OuterIntDecl)),
-  Env.getValue(S2.getChild(*OuterIntDecl)));
+EXPECT_EQ(getFieldValue(, *OuterIntDecl, Env),
+  getFieldValue(, *OuterIntDecl, Env));
 EXPECT_EQ(Env.getValue(S1.getChild(*RefDecl)),
   Env.getValue(S2.getChild(*RefDecl)));
-EXPECT_EQ(Env.getValue(Inner1.getChild(*InnerIntDecl)),
-  Env.getValue(Inner2.getChild(*InnerIntDecl)));
+EXPECT_EQ(getFieldValue(, *InnerIntDecl, Env),
+  getFieldValue(, *InnerIntDecl, Env));
 
 S1Val = cast(Env.getValue(S1));
 S2Val = cast(Env.getValue(S2));
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "TestingSupport.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -23,6 +24,7 @@
 
 using namespace clang;
 using namespace dataflow;
+using ::clang::dataflow::test::getFieldValue;
 using ::testing::ElementsAre;
 using ::testing::NotNull;
 using ::testing::Pair;
@@ -89,14 +91,9 @@
   // Verify that the struct and the field (`R`) with first appearance of the
   // type is created successfully.
   Environment Env(DAContext, *Fun);
-  Value *Val = Env.createValue(Ty);
-  ASSERT_NE(Val, nullptr);
-  StructValue *SVal = clang::dyn_cast(Val);
-  ASSERT_NE(SVal, nullptr);
-  Val = SVal->getChild(*R);
-  ASSERT_NE(Val, nullptr);
-  PointerValue *PV = clang::dyn_cast(Val);
-  EXPECT_NE(PV, nullptr);
+  StructValue *SVal = cast(Env.createValue(Ty));
+  PointerValue *PV = cast_or_null(getFieldValue(SVal, *R, Env));
+  

[PATCH] D154934: [clang][dataflow] Use `IntegerValue` instead of `StructValue` in `ValueTest`.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0014aab2d588: [clang][dataflow] Use `IntegerValue` instead 
of `StructValue` in `ValueTest`. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154934

Files:
  clang/unittests/Analysis/FlowSensitive/ValueTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
@@ -19,10 +19,16 @@
 using namespace dataflow;
 
 TEST(ValueTest, EquivalenceReflexive) {
-  StructValue V;
+  IntegerValue V;
   EXPECT_TRUE(areEquivalentValues(V, V));
 }
 
+TEST(ValueTest, DifferentIntegerValuesNotEquivalent) {
+  IntegerValue V1;
+  IntegerValue V2;
+  EXPECT_FALSE(areEquivalentValues(V1, V2));
+}
+
 TEST(ValueTest, AliasedReferencesEquivalent) {
   auto L = ScalarStorageLocation(QualType());
   ReferenceValue V1(L);


Index: clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
@@ -19,10 +19,16 @@
 using namespace dataflow;
 
 TEST(ValueTest, EquivalenceReflexive) {
-  StructValue V;
+  IntegerValue V;
   EXPECT_TRUE(areEquivalentValues(V, V));
 }
 
+TEST(ValueTest, DifferentIntegerValuesNotEquivalent) {
+  IntegerValue V1;
+  IntegerValue V2;
+  EXPECT_FALSE(areEquivalentValues(V1, V2));
+}
+
 TEST(ValueTest, AliasedReferencesEquivalent) {
   auto L = ScalarStorageLocation(QualType());
   ReferenceValue V1(L);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bd9b57d - [clang][dataflow] Fix initializing a reference field with an `InitListExpr`.

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:30Z
New Revision: bd9b57de4ff7c65be0d69179232ba2d5fe832195

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

LOG: [clang][dataflow] Fix initializing a reference field with an 
`InitListExpr`.

I added a test for this as the ongoing migration to strict handling of value 
categories (see https://discourse.llvm.org/t/70086) will change the code that 
handles this case. It turns out we already didn't handle this correctly, so I 
fixed the existing implementation.

Depends On D154961

Reviewed By: xazax.hun

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index e1a2606de81033..4c97e81184bba3 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -717,14 +717,15 @@ class TransferVisitor : public 
ConstStmtVisitor {
 if (Type->isStructureOrClassType()) {
   std::vector Fields =
   getFieldsForInitListExpr(Type->getAsRecordDecl());
-  for (auto It : llvm::zip(Fields, S->inits())) {
-const FieldDecl *Field = std::get<0>(It);
+  for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
 assert(Field != nullptr);
-
-const Expr *Init = std::get<1>(It);
 assert(Init != nullptr);
 
-if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
+if (Field->getType()->isReferenceType()) {
+  if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
+cast(Val)->setChild(*Field,
+ Env.create(*Loc));
+} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
   cast(Val)->setChild(*Field, *InitVal);
   }
 }

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 254226fd6d3ee9..a89ff8e7bc5ab5 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2912,6 +2912,34 @@ TEST(TransferTest, AggregateInitialization) {
   }
 }
 
+TEST(TransferTest, AggregateInitializationReferenceField) {
+  std::string Code = R"(
+struct S {
+  int 
+};
+
+void target(int i) {
+  S s = { i };
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> ,
+ ASTContext ) {
+const Environment  = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");
+
+auto  = getLocForDecl(ASTCtx, Env, "i");
+auto  = getLocForDecl(ASTCtx, Env, "s");
+
+auto  =
+*cast(getFieldValue(, *RefFieldDecl, Env));
+EXPECT_EQ((), );
+  });
+}
+
 TEST(TransferTest, AssignToUnionMember) {
   std::string Code = R"(
 union A {



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


[clang] b47bdcb - [clang][dataflow] Include fields initialized in an `InitListExpr` in `getModeledFields()`.

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:29Z
New Revision: b47bdcbc7207aac617d3c35dfc029f79b0a46fd8

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

LOG: [clang][dataflow] Include fields initialized in an `InitListExpr` in 
`getModeledFields()`.

Previously, we were including these fields only in the specific instance that 
was initialized by the `InitListExpr`, but not in other instances of the same 
type. This is inconsistent and error-prone.

Depends On D154952

Reviewed By: xazax.hun, gribozavr2

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 7c1d01ce816e2b..5bd2e5518a5463 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -644,6 +644,10 @@ getImplicitObjectLocation(const CXXMemberCallExpr , 
const Environment );
 AggregateStorageLocation *getBaseObjectLocation(const MemberExpr ,
 const Environment );
 
+/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
+/// order in which they appear in `InitListExpr::inits()`.
+std::vector getFieldsForInitListExpr(const RecordDecl *RD);
+
 } // namespace dataflow
 } // namespace clang
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 73e20705cff501..9b1fca41e911cc 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -215,6 +215,10 @@ getFieldsGlobalsAndFuncs(const Stmt , FieldSet ,
 insertIfFunction(*VD, Funcs);
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
+  } else if (auto *InitList = dyn_cast()) {
+if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
+  for (const auto *FD : getFieldsForInitListExpr(RD))
+Fields.insert(FD);
   }
 }
 
@@ -958,5 +962,17 @@ AggregateStorageLocation *getBaseObjectLocation(const 
MemberExpr ,
   return cast(Loc);
 }
 
+std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
+  // Unnamed bitfields are only used for padding and do not appear in
+  // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
+  // field list, and we thus need to remove them before mapping inits to
+  // fields to avoid mapping inits to the wrongs fields.
+  std::vector Fields;
+  llvm::copy_if(
+  RD->fields(), std::back_inserter(Fields),
+  [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
+  return Fields;
+}
+
 } // namespace dataflow
 } // namespace clang

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index ac971f69150f1e..e1a2606de81033 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -715,14 +715,8 @@ class TransferVisitor : public 
ConstStmtVisitor {
 Env.setValue(Loc, *Val);
 
 if (Type->isStructureOrClassType()) {
-  // Unnamed bitfields are only used for padding and are not appearing in
-  // `InitListExpr`'s inits. However, those fields do appear in 
RecordDecl's
-  // field list, and we thus need to remove them before mapping inits to
-  // fields to avoid mapping inits to the wrongs fields.
-  std::vector Fields;
-  llvm::copy_if(
-  Type->getAsRecordDecl()->fields(), std::back_inserter(Fields),
-  [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
+  std::vector Fields =
+  getFieldsForInitListExpr(Type->getAsRecordDecl());
   for (auto It : llvm::zip(Fields, S->inits())) {
 const FieldDecl *Field = std::get<0>(It);
 assert(Field != nullptr);

diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index 3ae3106bca4673..254226fd6d3ee9 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2833,6 +2833,7 @@ TEST(TransferTest, AggregateInitialization) {
 
 void target(int BarArg, int FooArg, int QuxArg) {
   B Quux{BarArg, {FooArg}, QuxArg};
+  B OtherB;
   /*[[p]]*/
 }
   )";
@@ -2849,6 +2850,7 @@ TEST(TransferTest, AggregateInitialization) {
 
  

[clang] 1e9b4fc - [clang][dataflow] Various refactorings in TypeErasedDataflowAnalysisTest.cpp

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:27Z
New Revision: 1e9b4fc1dcf27ae43477efe0329f738e4419871b

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

LOG: [clang][dataflow] Various refactorings in 
TypeErasedDataflowAnalysisTest.cpp

These simplify the code in their own right, but they are also useful in that 
they minimize the number of changes that will need to be made when then API of 
`AggregateStorageLocation` and `StructValue` changes as part of the migration 
to strict handling of value categories (see https://discourse.llvm.org/t/70086).

Depends On D154949

Reviewed By: xazax.hun, gribozavr2

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

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Removed: 




diff  --git 
a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
index 473750ad7a6cb4..d811aed8fddd99 100644
--- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -370,6 +370,13 @@ TEST_F(NoreturnDestructorTest, 
ConditionalOperatorNestedBranchReturns) {
   // FIXME: Called functions at point `p` should contain only "foo".
 }
 
+StructValue (AggregateStorageLocation ,
+  Environment ) {
+  auto  = *cast(Env.createValue(Loc.getType()));
+  Env.setValue(Loc, Val);
+  return Val;
+}
+
 // Models an analysis that uses flow conditions.
 class SpecialBoolAnalysis final
 : public DataflowAnalysis {
@@ -390,23 +397,18 @@ class SpecialBoolAnalysis final
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), 
*S,
   getASTContext( {
-  auto  = *Env.createValue(E->getType());
-  ConstructorVal.setProperty("is_set", Env.getBoolLiteralValue(false));
-  Env.setValue(*Env.getStorageLocation(*E, SkipPast::None), 
ConstructorVal);
+  cast(Env.getValueStrict(*E))
+  ->setProperty("is_set", Env.getBoolLiteralValue(false));
 } else if (const auto *E = selectFirst(
"call", 
match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(

SpecialBoolRecordDecl
  .bind("call"),
  *S, getASTContext( {
-  auto *Object = E->getImplicitObjectArgument();
-  assert(Object != nullptr);
-
-  auto *ObjectLoc = getImplicitObjectLocation(*E, Env);
-  assert(ObjectLoc != nullptr);
+  auto  =
+  *cast(getImplicitObjectLocation(*E, Env));
 
-  auto  = *Env.createValue(Object->getType());
-  ConstructorVal.setProperty("is_set", Env.getBoolLiteralValue(true));
-  Env.setValue(*ObjectLoc, ConstructorVal);
+  createNewStructValue(ObjectLoc, Env)
+  .setProperty("is_set", Env.getBoolLiteralValue(true));
 }
   }
 
@@ -551,21 +553,19 @@ class OptionalIntAnalysis final
 *S, getASTContext());
 if (const auto *E = selectFirst(
 "construct", Matches)) {
-  auto  = *Env.createValue(E->getType());
-  ConstructorVal.setProperty("has_value", Env.getBoolLiteralValue(false));
-  Env.setValue(*Env.getStorageLocation(*E, SkipPast::None), 
ConstructorVal);
+  cast(Env.getValueStrict(*E))
+  ->setProperty("has_value", Env.getBoolLiteralValue(false));
 } else if (const auto *E =
selectFirst("operator", Matches)) {
   assert(E->getNumArgs() > 0);
   auto *Object = E->getArg(0);
   assert(Object != nullptr);
 
-  auto *ObjectLoc = Env.getStorageLocation(*Object, SkipPast::Reference);
-  assert(ObjectLoc != nullptr);
+  auto  = *cast(
+  Env.getStorageLocation(*Object, SkipPast::Reference));
 
-  auto  = *Env.createValue(Object->getType());
-  ConstructorVal.setProperty("has_value", Env.getBoolLiteralValue(true));
-  Env.setValue(*ObjectLoc, ConstructorVal);
+  createNewStructValue(ObjectLoc, Env)
+  .setProperty("has_value", Env.getBoolLiteralValue(true));
 }
   }
 
@@ -1227,9 +1227,7 @@ class TopAnalysis final : public 
DataflowAnalysis {
 match(callExpr(callee(functionDecl(hasName("makeTop".bind("top"),
   *S, getASTContext());
 if (const auto *E = selectFirst("top", Matches)) {
-  auto  = Env.createStorageLocation(*E);
-  Env.setValue(Loc, Env.makeTopBoolValue());
-  Env.setStorageLocation(*E, Loc);
+  Env.setValueStrict(*E, Env.makeTopBoolValue());
 }
   }
 



___
cfe-commits mailing list

[clang] 0014aab - [clang][dataflow] Use `IntegerValue` instead of `StructValue` in `ValueTest`.

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:22Z
New Revision: 0014aab2d5882525c23130108e17fbbb5a2120f1

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

LOG: [clang][dataflow] Use `IntegerValue` instead of `StructValue` in 
`ValueTest`.

Soon, it will no longer be possible to default-construct `StructValue`. For 
details, see https://discourse.llvm.org/t/70086.

For completeness, also add a test that `areEquivalentValues()` on different 
`IntegerValue`s returns false.

Reviewed By: xazax.hun, gribozavr2

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

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/ValueTest.cpp

Removed: 




diff  --git a/clang/unittests/Analysis/FlowSensitive/ValueTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
index 02f3adeaeda756..19ea7a04928f28 100644
--- a/clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
@@ -19,10 +19,16 @@ using namespace clang;
 using namespace dataflow;
 
 TEST(ValueTest, EquivalenceReflexive) {
-  StructValue V;
+  IntegerValue V;
   EXPECT_TRUE(areEquivalentValues(V, V));
 }
 
+TEST(ValueTest, DifferentIntegerValuesNotEquivalent) {
+  IntegerValue V1;
+  IntegerValue V2;
+  EXPECT_FALSE(areEquivalentValues(V1, V2));
+}
+
 TEST(ValueTest, AliasedReferencesEquivalent) {
   auto L = ScalarStorageLocation(QualType());
   ReferenceValue V1(L);



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


[clang] 103a0fc - [clang][dataflow] Use `getFieldValue()` in TransferTest.cpp.

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:25Z
New Revision: 103a0fc0846050dd671e6485ab52491042f905c6

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

LOG: [clang][dataflow] Use `getFieldValue()` in TransferTest.cpp.

For context, see https://reviews.llvm.org/D154935.

Depends On D154935

Reviewed By: ymandel, xazax.hun

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

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
index baadea57e43751..3ae3106bca4673 100644
--- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -262,7 +262,8 @@ TEST(TransferTest, StructVarDecl) {
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -310,7 +311,8 @@ TEST(TransferTest, StructVarDeclWithInit) {
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -357,7 +359,8 @@ TEST(TransferTest, ClassVarDecl) {
 cast(>getChild(*BarDecl));
 
 const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *BarVal = cast(FooVal->getChild(*BarDecl));
+const auto *BarVal =
+cast(getFieldValue(FooVal, *BarDecl, Env));
 EXPECT_EQ(Env.getValue(*BarLoc), BarVal);
   });
 }
@@ -470,37 +473,37 @@ TEST(TransferTest, SelfReferentialReferenceVarDecl) {
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
-const auto *FooReferentVal = cast(Env.getValue(*FooLoc));
+const auto  =
+*cast(Env.getStorageLocation(*FooDecl));
+const auto  = *cast(Env.getValue(FooLoc));
 
-const auto *BarVal =
-cast(FooReferentVal->getChild(*BarDecl));
-const auto *BarReferentVal =
-cast(Env.getValue(BarVal->getReferentLoc()));
+const auto  =
+*cast(FooReferentVal.getChild(*BarDecl));
+const auto  =
+*cast(Env.getValue(BarVal.getReferentLoc()));
 
-const auto *FooRefVal =
-cast(BarReferentVal->getChild(*FooRefDecl));
+const auto  =
+*cast(getFieldValue(, *FooRefDecl, 
Env));
 const auto  =
-cast(FooRefVal->getReferentLoc());
+cast(FooRefVal.getReferentLoc());
 EXPECT_THAT(Env.getValue(FooReferentLoc), NotNull());
-EXPECT_THAT(Env.getValue(FooReferentLoc.getChild(*BarDecl)), IsNull());
+EXPECT_THAT(getFieldValue(, *BarDecl, Env), IsNull());
 
-const auto *FooPtrVal =
-cast(BarReferentVal->getChild(*FooPtrDecl));
+const auto  =
+*cast(getFieldValue(, *FooPtrDecl, Env));
 const auto  =
-cast(FooPtrVal->getPointeeLoc());
+cast(FooPtrVal.getPointeeLoc());
 EXPECT_THAT(Env.getValue(FooPtrPointeeLoc), NotNull());
-EXPECT_THAT(Env.getValue(FooPtrPointeeLoc.getChild(*BarDecl)), IsNull());
+EXPECT_THAT(getFieldValue(, *BarDecl, Env), IsNull());
 
-const auto *BazRefVal =
-cast(BarReferentVal->getChild(*BazRefDecl));
-const StorageLocation  = BazRefVal->getReferentLoc();
+const auto  =
+*cast(getFieldValue(, *BazRefDecl, 
Env));
+const StorageLocation  = BazRefVal.getReferentLoc();
 EXPECT_THAT(Env.getValue(BazReferentLoc), NotNull());
 
-const auto *BazPtrVal =
-cast(BarReferentVal->getChild(*BazPtrDecl));
-const StorageLocation  = BazPtrVal->getPointeeLoc();
+const auto  =
+*cast(getFieldValue(, *BazPtrDecl, Env));
+const StorageLocation  = BazPtrVal.getPointeeLoc();
 EXPECT_THAT(Env.getValue(BazPtrPointeeLoc), NotNull());
   });
 }
@@ -630,35 +633,36 @@ TEST(TransferTest, SelfReferentialPointerVarDecl) {
 ASSERT_THAT(BazRefDecl, NotNull());
 ASSERT_THAT(BazPtrDecl, NotNull());
 
-const auto *FooLoc =
-cast(Env.getStorageLocation(*FooDecl));
-const auto *FooVal = cast(Env.getValue(*FooLoc));
-const auto *FooPointeeVal =
-cast(Env.getValue(FooVal->getPointeeLoc()));
-
-const auto *BarVal =
-cast(FooPointeeVal->getChild(*BarDecl));
-const auto *BarPointeeVal =
-

[clang] 2902ea3 - [clang][dataflow] Introduce `getFieldValue()` test helpers.

2023-07-11 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-07-12T04:52:23Z
New Revision: 2902ea3d817bf381817ff76228c3212f4dc87d47

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

LOG: [clang][dataflow] Introduce `getFieldValue()` test helpers.

These insulate tests against changes to the `getChild()` functions of 
`AggregateStorageLocation` and `StructValue` that will happen as part of the 
migration to strict handling of value categories (see 
https://discourse.llvm.org/t/70086 for details):

- `AggregateStorageLocation::getChild()` will soon return a `StorageLocation *`
  instead of a `StorageLocation &`. When this happens, `getFieldValue()` will be
  changed to return null if `AggregateStorageLocation::getChild()` returns null;
  test code will not need to change as it should already be checking whether the
  return value of `getFieldValue()` is null.

- `StructValue::getChild()` will soon return a `StorageLocation *` instead of a
  `Value *`. When this happens, `getFieldValue()` will be changed to look up the
  `Value *` in the `Environment`. Again, test code will not need to change.

The test helpers will continue to serve a useful purpose once the API changes 
are complete, so the intent is to leave them in place.

This patch changes DataflowEnvironmentTest.cpp and RecordOpsTest.cpp to use the 
test helpers. TransferTest.cpp will be changed in an upcoming patch to help 
keep patch sizes manageable for review.

Depends On D154934

Reviewed By: ymandel, xazax.hun, gribozavr2

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

Added: 


Modified: 
clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Removed: 




diff  --git 
a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index 1c78dd380c7742..17c0f7b16c1c71 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "TestingSupport.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -23,6 +24,7 @@ namespace {
 
 using namespace clang;
 using namespace dataflow;
+using ::clang::dataflow::test::getFieldValue;
 using ::testing::ElementsAre;
 using ::testing::NotNull;
 using ::testing::Pair;
@@ -89,14 +91,9 @@ TEST_F(EnvironmentTest, CreateValueRecursiveType) {
   // Verify that the struct and the field (`R`) with first appearance of the
   // type is created successfully.
   Environment Env(DAContext, *Fun);
-  Value *Val = Env.createValue(Ty);
-  ASSERT_NE(Val, nullptr);
-  StructValue *SVal = clang::dyn_cast(Val);
-  ASSERT_NE(SVal, nullptr);
-  Val = SVal->getChild(*R);
-  ASSERT_NE(Val, nullptr);
-  PointerValue *PV = clang::dyn_cast(Val);
-  EXPECT_NE(PV, nullptr);
+  StructValue *SVal = cast(Env.createValue(Ty));
+  PointerValue *PV = cast_or_null(getFieldValue(SVal, *R, Env));
+  EXPECT_THAT(PV, NotNull());
 }
 
 TEST_F(EnvironmentTest, InitGlobalVarsFun) {
@@ -175,8 +172,7 @@ TEST_F(EnvironmentTest, 
IncludeFieldsFromDefaultInitializers) {
   // constructor, even though it is not referenced directly in the constructor.
   Environment Env(DAContext, *Constructor);
   auto *Val = cast(Env.createValue(QTy));
-  ASSERT_THAT(Val, NotNull());
-  EXPECT_THAT(Val->getChild(*XDecl), NotNull());
+  EXPECT_THAT(getFieldValue(Val, *XDecl, Env), NotNull());
 }
 
 TEST_F(EnvironmentTest, InitGlobalVarsFieldFun) {
@@ -221,8 +217,7 @@ TEST_F(EnvironmentTest, InitGlobalVarsFieldFun) {
   const auto *GlobalLoc =
   cast(Env.getStorageLocation(*GlobalDecl));
   const auto *GlobalVal = cast(Env.getValue(*GlobalLoc));
-  const auto *BarVal = GlobalVal->getChild(*BarDecl);
-  ASSERT_THAT(BarVal, NotNull());
+  auto *BarVal = getFieldValue(GlobalVal, *BarDecl, Env);
   EXPECT_TRUE(isa(BarVal));
 }
 

diff  --git a/clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
index 1f5fce1f2dd467..dc81e9594b6914 100644
--- a/clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
@@ -63,12 +63,12 @@ TEST(RecordOpsTest, CopyRecord) {
 auto  = cast(S1.getChild(*InnerDecl));
 auto  = cast(S2.getChild(*InnerDecl));
 
-EXPECT_NE(Env.getValue(S1.getChild(*OuterIntDecl)),
-  Env.getValue(S2.getChild(*OuterIntDecl)));
+

[PATCH] D154965: [clang][dataflow] Fix initializing a reference field with an `InitListExpr`.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 539366.
mboehme added a comment.

Changes in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154965

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2912,6 +2912,34 @@
   }
 }
 
+TEST(TransferTest, AggregateInitializationReferenceField) {
+  std::string Code = R"(
+struct S {
+  int 
+};
+
+void target(int i) {
+  S s = { i };
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> ,
+ ASTContext ) {
+const Environment  = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");
+
+auto  = getLocForDecl(ASTCtx, Env, "i");
+auto  = getLocForDecl(ASTCtx, Env, "s");
+
+auto  =
+*cast(getFieldValue(, *RefFieldDecl, Env));
+EXPECT_EQ((), );
+  });
+}
+
 TEST(TransferTest, AssignToUnionMember) {
   std::string Code = R"(
 union A {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -717,14 +717,15 @@
 if (Type->isStructureOrClassType()) {
   std::vector Fields =
   getFieldsForInitListExpr(Type->getAsRecordDecl());
-  for (auto It : llvm::zip(Fields, S->inits())) {
-const FieldDecl *Field = std::get<0>(It);
+  for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
 assert(Field != nullptr);
-
-const Expr *Init = std::get<1>(It);
 assert(Init != nullptr);
 
-if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
+if (Field->getType()->isReferenceType()) {
+  if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
+cast(Val)->setChild(*Field,
+ Env.create(*Loc));
+} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
   cast(Val)->setChild(*Field, *InitVal);
   }
 }


Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2912,6 +2912,34 @@
   }
 }
 
+TEST(TransferTest, AggregateInitializationReferenceField) {
+  std::string Code = R"(
+struct S {
+  int 
+};
+
+void target(int i) {
+  S s = { i };
+  /*[[p]]*/
+}
+  )";
+  runDataflow(
+  Code,
+  [](const llvm::StringMap> ,
+ ASTContext ) {
+const Environment  = getEnvironmentAtAnnotation(Results, "p");
+
+const ValueDecl *RefFieldDecl = findValueDecl(ASTCtx, "RefField");
+
+auto  = getLocForDecl(ASTCtx, Env, "i");
+auto  = getLocForDecl(ASTCtx, Env, "s");
+
+auto  =
+*cast(getFieldValue(, *RefFieldDecl, Env));
+EXPECT_EQ((), );
+  });
+}
+
 TEST(TransferTest, AssignToUnionMember) {
   std::string Code = R"(
 union A {
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -717,14 +717,15 @@
 if (Type->isStructureOrClassType()) {
   std::vector Fields =
   getFieldsForInitListExpr(Type->getAsRecordDecl());
-  for (auto It : llvm::zip(Fields, S->inits())) {
-const FieldDecl *Field = std::get<0>(It);
+  for (auto [Field, Init] : llvm::zip(Fields, S->inits())) {
 assert(Field != nullptr);
-
-const Expr *Init = std::get<1>(It);
 assert(Init != nullptr);
 
-if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
+if (Field->getType()->isReferenceType()) {
+  if (StorageLocation *Loc = Env.getStorageLocationStrict(*Init))
+cast(Val)->setChild(*Field,
+ Env.create(*Loc));
+} else if (Value *InitVal = Env.getValue(*Init, SkipPast::None))
   cast(Val)->setChild(*Field, *InitVal);
   }
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154935: [clang][dataflow] Introduce `getFieldValue()` test helpers.

2023-07-11 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 539365.
mboehme added a comment.

Changes in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154935

Files:
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h

Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -451,6 +451,28 @@
   return *cast(Env.getValue(*VD));
 }
 
+/// Returns the value of a `Field` on the record referenced by `Loc.`
+/// Returns null if `Loc` is null.
+inline Value *getFieldValue(const AggregateStorageLocation *Loc,
+const ValueDecl , const Environment ) {
+  if (Loc == nullptr)
+return nullptr;
+  return Env.getValue(Loc->getChild(Field));
+}
+
+/// Returns the value of a `Field` on a `Struct.
+/// Returns null if `Struct` is null.
+///
+/// Note: This function currently does not use the `Env` parameter, but it will
+/// soon be needed to look up the `Value` when `setChild()` changes to return a
+/// `StorageLocation *`.
+inline Value *getFieldValue(const StructValue *Struct, const ValueDecl ,
+const Environment ) {
+  if (Struct == nullptr)
+return nullptr;
+  return Struct->getChild(Field);
+}
+
 /// Creates and owns constraints which are boolean values.
 class ConstraintContext {
   unsigned NextAtom = 0;
Index: clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/RecordOpsTest.cpp
@@ -63,12 +63,12 @@
 auto  = cast(S1.getChild(*InnerDecl));
 auto  = cast(S2.getChild(*InnerDecl));
 
-EXPECT_NE(Env.getValue(S1.getChild(*OuterIntDecl)),
-  Env.getValue(S2.getChild(*OuterIntDecl)));
+EXPECT_NE(getFieldValue(, *OuterIntDecl, Env),
+  getFieldValue(, *OuterIntDecl, Env));
 EXPECT_NE(Env.getValue(S1.getChild(*RefDecl)),
   Env.getValue(S2.getChild(*RefDecl)));
-EXPECT_NE(Env.getValue(Inner1.getChild(*InnerIntDecl)),
-  Env.getValue(Inner2.getChild(*InnerIntDecl)));
+EXPECT_NE(getFieldValue(, *InnerIntDecl, Env),
+  getFieldValue(, *InnerIntDecl, Env));
 
 auto *S1Val = cast(Env.getValue(S1));
 auto *S2Val = cast(Env.getValue(S2));
@@ -78,12 +78,12 @@
 
 copyRecord(S1, S2, Env);
 
-EXPECT_EQ(Env.getValue(S1.getChild(*OuterIntDecl)),
-  Env.getValue(S2.getChild(*OuterIntDecl)));
+EXPECT_EQ(getFieldValue(, *OuterIntDecl, Env),
+  getFieldValue(, *OuterIntDecl, Env));
 EXPECT_EQ(Env.getValue(S1.getChild(*RefDecl)),
   Env.getValue(S2.getChild(*RefDecl)));
-EXPECT_EQ(Env.getValue(Inner1.getChild(*InnerIntDecl)),
-  Env.getValue(Inner2.getChild(*InnerIntDecl)));
+EXPECT_EQ(getFieldValue(, *InnerIntDecl, Env),
+  getFieldValue(, *InnerIntDecl, Env));
 
 S1Val = cast(Env.getValue(S1));
 S2Val = cast(Env.getValue(S2));
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "TestingSupport.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -23,6 +24,7 @@
 
 using namespace clang;
 using namespace dataflow;
+using ::clang::dataflow::test::getFieldValue;
 using ::testing::ElementsAre;
 using ::testing::NotNull;
 using ::testing::Pair;
@@ -89,14 +91,9 @@
   // Verify that the struct and the field (`R`) with first appearance of the
   // type is created successfully.
   Environment Env(DAContext, *Fun);
-  Value *Val = Env.createValue(Ty);
-  ASSERT_NE(Val, nullptr);
-  StructValue *SVal = clang::dyn_cast(Val);
-  ASSERT_NE(SVal, nullptr);
-  Val = SVal->getChild(*R);
-  ASSERT_NE(Val, nullptr);
-  PointerValue *PV = clang::dyn_cast(Val);
-  EXPECT_NE(PV, nullptr);
+  StructValue *SVal = cast(Env.createValue(Ty));
+  PointerValue *PV = cast_or_null(getFieldValue(SVal, *R, Env));
+  EXPECT_THAT(PV, NotNull());
 }
 
 TEST_F(EnvironmentTest, InitGlobalVarsFun) {
@@ -175,8 +172,7 @@
   // constructor, even though it is not 

[PATCH] D143241: [Clang] Reset FP options before function instantiations

2023-07-11 Thread Sam James via Phabricator via cfe-commits
thesamesam added a comment.

During our regular snapshot testing, we've hit this in Gentoo on 32-bit Linux 
x86: https://github.com/llvm/llvm-project/issues/63704#issuecomment-1631791518.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143241

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


[PATCH] D154701: [clang] Overridden CXXMethodDecl::isVirtual() assertion failed before fully imported.

2023-07-11 Thread Ding Fei via Phabricator via cfe-commits
danix800 added inline comments.



Comment at: clang/test/Analysis/ctu-astimport-virtual-assertion/main.cpp:22
+
+#include "Inputs/input.h"

balazske wrote:
> Such tests are not in the //Analysis// folder but in the //ASTMerge// folder 
> instead. I would say that this test is not necessary if the other test (in my 
> added note) is inserted.
Thanks for the testcase! The orignal one will be removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154701

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


[PATCH] D154822: [clang] Support '-fgpu-default-stream=per-thread' for NVIDIA CUDA

2023-07-11 Thread boxu.zhang via Phabricator via cfe-commits
boxu-zhang added a comment.

I don't have the permission to push to main branch. Can anyone push this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154822

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


[PATCH] D154290: [Clang] Implement P2741R3 - user-generated static_assert messages

2023-07-11 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/test/SemaCXX/static-assert-cxx26.cpp:1
+// RUN: %clang_cc1 -std=c++2c -fsyntax-only %s -verify
+

How about a test case w/ `data()` and or `size()` has default arguments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154290

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


[PATCH] D154290: [Clang] Implement P2741R3 - user-generated static_assert messages

2023-07-11 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/test/SemaCXX/static-assert-cxx26.cpp:167
+static_assert(false, MessageInvalidSize{});  // expected-error {{static 
assertion failed}} \
+ // expected-error {{the message 
in a static_assert declaration must be a string literal or an object with 
data() and size() member functions}}
+static_assert(false, MessageInvalidData{});  // expected-error {{static 
assertion failed}} \

I feel like this diagnostic could be more detailed. Looking at the 
implementation you could at least point out which one is invalid if not both 
and you could probably add more details on top of that but I think at least 
pointing out which is invalid would be helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154290

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


[PATCH] D145302: [clangd] Add library for clangd main function

2023-07-11 Thread Mike Hommey via Phabricator via cfe-commits
glandium added a comment.

This broke building with `-DLLVM_LINK_LLVM_DYLIB=ON`:

  /usr/bin/ld: 
tools/clang/tools/extra/clangd/refactor/tweaks/CMakeFiles/obj.clangDaemonTweaks.dir/AddUsing.cpp.o:
 in function `clang::clangd::(anonymous 
namespace)::AddUsing::prepare(clang::clangd::Tweak::Selection const&)':
  
AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x1c):
 undefined reference to `clang::clangd::ParsedAST::getASTContext()'
  /usr/bin/ld: 
AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x6d):
 undefined reference to `clang::clangd::ParsedAST::getASTContext() const'
  /usr/bin/ld: 
AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x9a):
 undefined reference to `clang::clangd::isHeaderFile(llvm::StringRef, 
std::optional)'
  /usr/bin/ld: 
AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0xcc):
 undefined reference to `clang::clangd::SelectionTree::commonAncestor() const'
  /usr/bin/ld: 
AddUsing.cpp:(.text._ZN5clang6clangd12_GLOBAL__N_18AddUsing7prepareERKNS0_5Tweak9SelectionE+0x391):
 undefined reference to 
`clang::clangd::printNamespaceScope[abi:cxx11](clang::DeclContext const&)'

etc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145302

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


[PATCH] D146777: [clang] Preliminary fat-lto-object support

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:623
+if (Args.hasArg(options::OPT_ffat_lto_objects))
+  CmdArgs.push_back("-fat-lto-objects");
   }

New lld long options only allow `--` form. So use two dashes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146777

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


[PATCH] D146777: [clang] Preliminary fat-lto-object support

2023-07-11 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth updated this revision to Diff 539346.
paulkirth added a comment.

Rebase and try to accomodate Unified LTO changes.

Based on the Unified LTO patches, I think this is the correct handling for
FatLTO, but I'd like to get a second opinion before landing this.

CC: @ormris


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146777

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/CodeGen/embed-fat-lto-objects.c
  clang/test/Driver/clang_f_opts.c
  clang/test/Driver/fat-lto-objects.c

Index: clang/test/Driver/fat-lto-objects.c
===
--- /dev/null
+++ clang/test/Driver/fat-lto-objects.c
@@ -0,0 +1,19 @@
+// RUN: %clang --target=x86_64-unknown-linux-gnu -flto -ffat-lto-objects -### %s -c 2>&1 | FileCheck %s -check-prefix=CHECK-CC
+// CHECK-CC: -cc1
+// CHECK-CC-SAME: -emit-obj
+// CHECK-CC-SAME: -ffat-lto-objects
+
+// RUN: %clang --target=x86_64-unknown-linux-gnu -ffat-lto-objects -### %s -c 2>&1 | FileCheck %s -check-prefix=CHECK-CC-NOLTO
+// CHECK-CC-NOLTO: -cc1
+// CHECK-CC-NOLTO-SAME: -emit-obj
+// CHECK-CC-NOLTO-NOT: -ffat-lto-objects
+// CHECK-CC-NOLTO-NOT: warning: argument unused during compilation: '-ffat-lto-objects'
+
+/// We need to pass an additional flag to lld when linking w/ -flto -ffat-lto-objects
+/// But it should not be there when LTO is disabled w/ -fno-lto
+// RUN: %clang --target=x86_64-unknown-linux-gnu --sysroot=%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -flto -ffat-lto-objects -### 2>&1 | FileCheck --check-prefix=LTO %s
+// RUN: %clang --target=x86_64-unknown-linux-gnu --sysroot=%S/Inputs/basic_cross_linux_tree %s \
+// RUN:   -fuse-ld=lld -fno-lto -ffat-lto-objects -### 2>&1 | FileCheck --check-prefix=NOLTO %s
+// LTO: "-fat-lto-objects"
+// NOLTO-NOT: "-fat-lto-objects"
Index: clang/test/Driver/clang_f_opts.c
===
--- clang/test/Driver/clang_f_opts.c
+++ clang/test/Driver/clang_f_opts.c
@@ -424,7 +424,6 @@
 // CHECK-WARNING-DAG: optimization flag '-fwhole-program' is not supported
 // CHECK-WARNING-DAG: optimization flag '-fcaller-saves' is not supported
 // CHECK-WARNING-DAG: optimization flag '-freorder-blocks' is not supported
-// CHECK-WARNING-DAG: optimization flag '-ffat-lto-objects' is not supported
 // CHECK-WARNING-DAG: optimization flag '-fmerge-constants' is not supported
 // CHECK-WARNING-DAG: optimization flag '-finline-small-functions' is not supported
 // CHECK-WARNING-DAG: optimization flag '-ftree-dce' is not supported
Index: clang/test/CodeGen/embed-fat-lto-objects.c
===
--- /dev/null
+++ clang/test/CodeGen/embed-fat-lto-objects.c
@@ -0,0 +1,17 @@
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full -ffat-lto-objects -fsplit-lto-unit -emit-llvm < %s  | FileCheck %s --check-prefixes=FULL,SPLIT
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full -ffat-lto-objects -emit-llvm < %s  | FileCheck %s --check-prefixes=FULL,SPLIT
+
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=thin -fsplit-lto-unit -ffat-lto-objects -emit-llvm < %s  | FileCheck %s --check-prefixes=THIN,SPLIT
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=thin -ffat-lto-objects -emit-llvm < %s  | FileCheck %s --check-prefixes=THIN,NOSPLIT
+
+/// Check that the ThinLTO metadata is only set false for full LTO.
+// FULL: ![[#]] = !{i32 1, !"ThinLTO", i32 0}
+// THIN-NOT: ![[#]] = !{i32 1, !"ThinLTO", i32 0}
+
+/// Be sure we enable split LTO unints correctly under -ffat-lto-objects.
+// SPLIT: ![[#]] = !{i32 1, !"EnableSplitLTOUnit", i32 1}
+// NOSPLIT: ![[#]] = !{i32 1, !"EnableSplitLTOUnit", i32 0}
+
+int test(void) {
+  return 0xabcd;
+}
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -617,6 +617,10 @@
 PluginName + Suffix,
 Plugin);
 CmdArgs.push_back(Args.MakeArgString(Twine(PluginPrefix) + Plugin));
+  } else {
+// For LLD we need to enable fat object support
+if (Args.hasArg(options::OPT_ffat_lto_objects))
+  CmdArgs.push_back("-fat-lto-objects");
   }
 
   const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=";
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7353,6 +7353,22 @@
   if (SplitLTOUnit)
 

[clang] 875b881 - [clang-format][NFC] Remove redundant parentheses in the source code

2023-07-11 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-07-11T17:05:00-07:00
New Revision: 875b881186c4eb146e77e76ad72ee0a356d7c69f

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

LOG: [clang-format][NFC] Remove redundant parentheses in the source code

Reformat the source code with RemoveParentheses set to ReturnStatement.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/DefinitionBlockSeparator.cpp
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 66e66cc6856d8c..0ca297a5f95768 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -617,10 +617,10 @@ unsigned ContinuationIndenter::addTokenToState(LineState 
, bool Newline,
   assert(!State.Stack.empty());
   State.NoContinuation = false;
 
-  if ((Current.is(TT_ImplicitStringLiteral) &&
-   (!Previous.Tok.getIdentifierInfo() ||
-Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
-tok::pp_not_keyword))) {
+  if (Current.is(TT_ImplicitStringLiteral) &&
+  (!Previous.Tok.getIdentifierInfo() ||
+   Previous.Tok.getIdentifierInfo()->getPPKeywordID() ==
+   tok::pp_not_keyword)) {
 unsigned EndColumn =
 SourceMgr.getSpellingColumnNumber(Current.WhitespaceRange.getEnd());
 if (Current.LastNewlineOffset != 0) {

diff  --git a/clang/lib/Format/DefinitionBlockSeparator.cpp 
b/clang/lib/Format/DefinitionBlockSeparator.cpp
index 5c006e2d037b29..576c6597b27afe 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -52,10 +52,10 @@ void DefinitionBlockSeparator::separateBlocks(
 for (const FormatToken *CurrentToken = Line->First; CurrentToken;
  CurrentToken = CurrentToken->Next) {
   if (BracketLevel == 0) {
-if ((CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
-   tok::kw_union) ||
- (Style.isJavaScript() &&
-  CurrentToken->is(ExtraKeywords.kw_function {
+if (CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
+  tok::kw_union) ||
+(Style.isJavaScript() &&
+ CurrentToken->is(ExtraKeywords.kw_function))) {
   return true;
 }
 if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
@@ -164,7 +164,7 @@ void DefinitionBlockSeparator::separateBlocks(
 }
   }
 
-  if ((Style.isCSharp() && OperateLine->First->is(TT_AttributeSquare)))
+  if (Style.isCSharp() && OperateLine->First->is(TT_AttributeSquare))
 return true;
   return false;
 };

diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 2e3b21cfda79eb..86f62dc2eec91a 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -618,7 +618,7 @@ bool 
LeftRightQualifierAlignmentFixer::isPossibleMacro(const FormatToken *Tok) {
 return false;
   if (Tok->TokenText.upper() == Tok->TokenText.str()) {
 // T,K,U,V likely could be template arguments
-return (Tok->TokenText.size() != 1);
+return Tok->TokenText.size() != 1;
   }
   return false;
 }

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7bec899754362d..52973a3ec95171 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2955,8 +2955,8 @@ class ExpressionParser {
 Tok = Next;
 if (Tok)
   Tok = Tok->getNextNonComment();
-  } else if ((Keywords.isVerilogQualifier(*Tok) ||
-  Keywords.isVerilogIdentifier(*Tok))) {
+  } else if (Keywords.isVerilogQualifier(*Tok) ||
+ Keywords.isVerilogIdentifier(*Tok)) {
 First = Tok;
 Tok = Next;
 // The name may have dots like `interface_foo.modport_foo`.

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 3eacd0201df326..9413dbe59553bd 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -116,8 +116,8 @@ class LevelIndentTracker {
 return true;
   }
   // Handle Qt signals.
-  else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-RootToken.Next && RootToken.Next->is(tok::colon))) {
+  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+   RootToken.Next && RootToken.Next->is(tok::colon)) {
 return true;
 

[clang] b10899d - [clang] Fix -Wlogical-op-parentheses in Clang.cpp (NFC)

2023-07-11 Thread Jie Fu via cfe-commits

Author: Jie Fu
Date: 2023-07-12T07:53:50+08:00
New Revision: b10899d869954e1426684cbc20a43d7303075d49

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

LOG: [clang] Fix -Wlogical-op-parentheses in Clang.cpp (NFC)

/Users/jiefu/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp:7345:56: error: 
'&&' within '||' [-Werror,-Wlogical-op-parentheses]
  (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
  ~^~
/Users/jiefu/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp:7345:56: note: 
place parentheses around the '&&' expression to silence this warning
  (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
   ^
  (
1 error generated.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 796c60f0739285..bf09fc859a16df 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7342,8 +7342,8 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   }
 
   bool DefaultsSplitLTOUnit =
-  (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
-  (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit()) ||
+  ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
+  (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
   (!Triple.isPS4() && UnifiedLTO);
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,



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


[clang] fd2254b - clang: Update test for strict minnum/maxnum fix

2023-07-11 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-07-11T19:51:38-04:00
New Revision: fd2254b7358d0f78a79784688bd8012c1a52b9cf

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

LOG: clang: Update test for strict minnum/maxnum fix

Added: 


Modified: 
clang/test/CodeGen/strictfp-elementwise-bulitins.cpp

Removed: 




diff  --git a/clang/test/CodeGen/strictfp-elementwise-bulitins.cpp 
b/clang/test/CodeGen/strictfp-elementwise-bulitins.cpp
index a2062f31da154b..3417d531c92bb3 100644
--- a/clang/test/CodeGen/strictfp-elementwise-bulitins.cpp
+++ b/clang/test/CodeGen/strictfp-elementwise-bulitins.cpp
@@ -28,9 +28,9 @@ float4 strict_elementwise_abs(float4 a) {
 }
 
 // CHECK-LABEL: define dso_local noundef <4 x float> 
@_Z22strict_elementwise_maxDv4_fS_
-// CHECK-SAME: (<4 x float> noundef [[A:%.*]], <4 x float> noundef [[B:%.*]]) 
local_unnamed_addr #[[ATTR2]] {
+// CHECK-SAME: (<4 x float> noundef [[A:%.*]], <4 x float> noundef [[B:%.*]]) 
local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[ELT_MAX:%.*]] = tail call <4 x float> 
@llvm.maxnum.v4f32(<4 x float> [[A]], <4 x float> [[B]]) #[[ATTR4]]
+// CHECK-NEXT:[[ELT_MAX:%.*]] = tail call <4 x float> 
@llvm.experimental.constrained.maxnum.v4f32(<4 x float> [[A]], <4 x float> 
[[B]], metadata !"fpexcept.strict") #[[ATTR4]]
 // CHECK-NEXT:ret <4 x float> [[ELT_MAX]]
 //
 float4 strict_elementwise_max(float4 a, float4 b) {
@@ -38,9 +38,9 @@ float4 strict_elementwise_max(float4 a, float4 b) {
 }
 
 // CHECK-LABEL: define dso_local noundef <4 x float> 
@_Z22strict_elementwise_minDv4_fS_
-// CHECK-SAME: (<4 x float> noundef [[A:%.*]], <4 x float> noundef [[B:%.*]]) 
local_unnamed_addr #[[ATTR2]] {
+// CHECK-SAME: (<4 x float> noundef [[A:%.*]], <4 x float> noundef [[B:%.*]]) 
local_unnamed_addr #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[ELT_MIN:%.*]] = tail call <4 x float> 
@llvm.minnum.v4f32(<4 x float> [[A]], <4 x float> [[B]]) #[[ATTR4]]
+// CHECK-NEXT:[[ELT_MIN:%.*]] = tail call <4 x float> 
@llvm.experimental.constrained.minnum.v4f32(<4 x float> [[A]], <4 x float> 
[[B]], metadata !"fpexcept.strict") #[[ATTR4]]
 // CHECK-NEXT:ret <4 x float> [[ELT_MIN]]
 //
 float4 strict_elementwise_min(float4 a, float4 b) {



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


[PATCH] D151730: [RISCV] Support target attribute for function

2023-07-11 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D151730#4491773 , @jrtc27 wrote:

> Isn't multiversioning a separate thing that builds on top of per-function 
> target attributes?

That's what I thought. The supportsMultiVersioning call was in an earlier 
version of the patch that I asked about.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151730

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


[PATCH] D151730: [RISCV] Support target attribute for function

2023-07-11 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Isn't multiversioning a separate thing that builds on top of per-function 
target attributes?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151730

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


[PATCH] D151730: [RISCV] Support target attribute for function

2023-07-11 Thread Philip Reames via Phabricator via cfe-commits
reames added a comment.

FYI, this change appears to be a partial diff.  Locally, I need to add RISCV to 
supportsMultiVersioning() to get this to work at all.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151730

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


[PATCH] D154484: [clang-format] Add an option to remove redundant parentheses

2023-07-11 Thread Owen Pan via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3a6a0702c2a4: [clang-format] Add an option to remove 
redundant parentheses (authored by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D154484?vs=538470=539332#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154484

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/ConfigParseTest.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -25973,6 +25973,56 @@
getGoogleStyle());
 }
 
+TEST_F(FormatTest, RemoveParentheses) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.RemoveParentheses, FormatStyle::RPS_Leave);
+
+  Style.RemoveParentheses = FormatStyle::RPS_MultipleParentheses;
+  verifyFormat("int x __attribute__((aligned(16))) = 0;", Style);
+  verifyFormat("class __declspec(dllimport) X {};",
+   "class __declspec((dllimport)) X {};", Style);
+  verifyFormat("int x = (({ 0; }));", "int x = ((({ 0; })));", Style);
+  verifyFormat("while (a)\n"
+   "  b;",
+   "while (((a)))\n"
+   "  b;",
+   Style);
+  verifyFormat("while ((a = b))\n"
+   "  c;",
+   "while (((a = b)))\n"
+   "  c;",
+   Style);
+  verifyFormat("if (a)\n"
+   "  b;",
+   "if (((a)))\n"
+   "  b;",
+   Style);
+  verifyFormat("if constexpr ((a = b))\n"
+   "  c;",
+   "if constexpr (((a = b)))\n"
+   "  c;",
+   Style);
+  verifyFormat("if (({ a; }))\n"
+   "  b;",
+   "if ((({ a; })))\n"
+   "  b;",
+   Style);
+  verifyFormat("return (0);", "return (((0)));", Style);
+  verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style);
+
+  Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+  verifyFormat("return 0;", "return (0);", Style);
+  verifyFormat("co_return 0;", "co_return ((0));", Style);
+  verifyFormat("return 0;", "return (((0)));", Style);
+  verifyFormat("return ({ 0; });", "return ((({ 0; })));", Style);
+
+  Style.ColumnLimit = 25;
+  verifyFormat("return (a + b) - (c + d);",
+   "return (((a + b)) -\n"
+   "((c + d)));",
+   Style);
+}
+
 } // namespace
 } // namespace test
 } // namespace format
Index: clang/unittests/Format/ConfigParseTest.cpp
===
--- clang/unittests/Format/ConfigParseTest.cpp
+++ clang/unittests/Format/ConfigParseTest.cpp
@@ -917,6 +917,13 @@
   LineEnding, FormatStyle::LE_CRLF);
   Style.LineEnding = DefaultLineEnding;
   CHECK_PARSE("UseCRLF: true", LineEnding, FormatStyle::LE_DeriveCRLF);
+
+  CHECK_PARSE("RemoveParentheses: MultipleParentheses", RemoveParentheses,
+  FormatStyle::RPS_MultipleParentheses);
+  CHECK_PARSE("RemoveParentheses: ReturnStatement", RemoveParentheses,
+  FormatStyle::RPS_ReturnStatement);
+  CHECK_PARSE("RemoveParentheses: Leave", RemoveParentheses,
+  FormatStyle::RPS_Leave);
 }
 
 TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -156,7 +156,7 @@
   bool tryToParseBracedList();
   bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
tok::TokenKind ClosingBraceKind = tok::r_brace);
-  void parseParens(TokenType AmpAmpTokenType = TT_Unknown);
+  bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2432,22 +2432,50 @@
 /// \brief Parses a pair of parentheses (and everything between them).
 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all
 /// double ampersands. This applies for all nested scopes as well.
-void UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) {
+///
+/// Returns whether there is a `=` token between the parentheses.
+bool 

[clang] 3a6a070 - [clang-format] Add an option to remove redundant parentheses

2023-07-11 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-07-11T16:33:19-07:00
New Revision: 3a6a0702c2a4c2290f0b55b0451a9f97d7592baf

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

LOG: [clang-format] Add an option to remove redundant parentheses

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 866bf0910898b3..8965b20e62c641 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -4357,6 +4357,50 @@ the configuration (without a prefix: ``Auto``).
   }
 }
 
+.. _RemoveParentheses:
+
+**RemoveParentheses** (``RemoveParenthesesStyle``) :versionbadge:`clang-format 
17` :ref:`¶ `
+  Remove redundant parentheses.
+
+  .. warning::
+
+   Setting this option to any value other than ``Leave`` could lead to
+   incorrect code formatting due to clang-format's lack of complete semantic
+   information. As such, extra care should be taken to review code changes
+   made by this option.
+
+  Possible values:
+
+  * ``RPS_Leave`` (in configuration: ``Leave``)
+Do not remove parentheses.
+
+.. code-block:: c++
+
+  class __declspec((dllimport)) X {};
+  co_return (((0)));
+  return ((a + b) - ((c + d)));
+
+  * ``RPS_MultipleParentheses`` (in configuration: ``MultipleParentheses``)
+Replace multiple parentheses with single parentheses.
+
+.. code-block:: c++
+
+  class __declspec(dllimport) X {};
+  co_return (0);
+  return ((a + b) - (c + d));
+
+  * ``RPS_ReturnStatement`` (in configuration: ``ReturnStatement``)
+Also remove parentheses enclosing the expression in a
+``return``/``co_return`` statement.
+
+.. code-block:: c++
+
+  class __declspec(dllimport) X {};
+  co_return 0;
+  return (a + b) - (c + d);
+
+
+
 .. _RemoveSemicolon:
 
 **RemoveSemicolon** (``Boolean``) :versionbadge:`clang-format 16` :ref:`¶ 
`

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1f025097babc95..b7babe3ddc3f41 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -821,6 +821,7 @@ clang-format
 - Add ``BracedInitializerIndentWidth`` which can be used to configure
   the indentation level of the contents of braced init lists.
 - Add ``KeepEmptyLinesAtEOF`` to keep empty lines at end of file.
+- Add ``RemoveParentheses`` to remove redundant parentheses.
 
 libclang
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 3992dd89fb950d..71948027fbe3ed 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3383,6 +3383,42 @@ struct FormatStyle {
   /// \version 14
   bool RemoveBracesLLVM;
 
+  /// Types of redundant parentheses to remove.
+  enum RemoveParenthesesStyle : int8_t {
+/// Do not remove parentheses.
+/// \code
+///   class __declspec((dllimport)) X {};
+///   co_return (((0)));
+///   return ((a + b) - ((c + d)));
+/// \endcode
+RPS_Leave,
+/// Replace multiple parentheses with single parentheses.
+/// \code
+///   class __declspec(dllimport) X {};
+///   co_return (0);
+///   return ((a + b) - (c + d));
+/// \endcode
+RPS_MultipleParentheses,
+/// Also remove parentheses enclosing the expression in a
+/// ``return``/``co_return`` statement.
+/// \code
+///   class __declspec(dllimport) X {};
+///   co_return 0;
+///   return (a + b) - (c + d);
+/// \endcode
+RPS_ReturnStatement,
+  };
+
+  /// Remove redundant parentheses.
+  /// \warning
+  ///  Setting this option to any value other than ``Leave`` could lead to
+  ///  incorrect code formatting due to clang-format's lack of complete 
semantic
+  ///  information. As such, extra care should be taken to review code changes
+  ///  made by this option.
+  /// \endwarning
+  /// \version 17
+  RemoveParenthesesStyle RemoveParentheses;
+
   /// Remove semicolons after the closing brace of a non-empty function.
   /// \warning
   ///  Setting this option to `true` could lead to incorrect code formatting 
due
@@ -4416,6 +4452,7 @@ struct FormatStyle {
RawStringFormats == R.RawStringFormats &&
ReferenceAlignment == R.ReferenceAlignment &&
RemoveBracesLLVM == R.RemoveBracesLLVM &&
+   RemoveParentheses == R.RemoveParentheses &&

[PATCH] D123971: [clang][PS4] Enable SplitLTOUnits by default

2023-07-11 Thread Matthew Voss via Phabricator via cfe-commits
ormris added a comment.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123971

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


[PATCH] D123971: [clang][PS4] Enable SplitLTOUnits by default

2023-07-11 Thread Matthew Voss via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG392b30680752: [clang][PS4] Enable SplitLTOUnits and Unified 
LTO by default (authored by ormris).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D123971?vs=530117=539331#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123971

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/split-lto-unit.c
  clang/test/CodeGenCXX/unified-cfi-lto.cpp
  clang/test/Driver/lto-unit.c
  clang/test/Driver/split-lto-unit.c


Index: clang/test/Driver/split-lto-unit.c
===
--- clang/test/Driver/split-lto-unit.c
+++ clang/test/Driver/split-lto-unit.c
@@ -7,6 +7,10 @@
 // RUN: %clang --target=x86_64-apple-darwin13.3.0 -### %s 
-fwhole-program-vtables -flto=thin 2>&1 | FileCheck --check-prefix=NOUNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -fwhole-program-vtables 
-flto=full 2>&1 | FileCheck --check-prefix=UNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -fwhole-program-vtables 
-flto=thin 2>&1 | FileCheck --check-prefix=NOUNIT %s
+// RUN: %clang --target=x86_64-sie-ps5 -### %s -fwhole-program-vtables 
-flto=full 2>&1 | FileCheck --check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-sie-ps5 -### %s -fwhole-program-vtables 
-flto=thin 2>&1 | FileCheck --check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-unknown-linux -### %s -fwhole-program-vtables 
-flto=full -funified-lto 2>&1 | FileCheck --check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-unknown-linux -### %s -fwhole-program-vtables 
-flto=thin -funified-lto 2>&1 | FileCheck --check-prefix=UNIT %s
 
 // UNIT: "-fsplit-lto-unit"
 // NOUNIT-NOT: "-fsplit-lto-unit"
Index: clang/test/Driver/lto-unit.c
===
--- clang/test/Driver/lto-unit.c
+++ clang/test/Driver/lto-unit.c
@@ -4,5 +4,10 @@
 // RUN: %clang --target=x86_64-apple-darwin13.3.0 -### %s -flto=thin 2>&1 | 
FileCheck --check-prefix=UNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=full 2>&1 | FileCheck 
--check-prefix=UNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=thin 2>&1 | FileCheck 
--check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=full -funified-lto 2>&1 
| FileCheck --check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=thin -funified-lto 2>&1 
| FileCheck --check-prefix=NOUNIT %s
+// RUN: %clang --target=x86_64-unknown-linux -### %s -flto=full -funified-lto 
2>&1 | FileCheck --check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-unknown-linux -### %s -flto=thin -funified-lto 
2>&1 | FileCheck --check-prefix=UNIT %s
 
 // UNIT: "-flto-unit"
+// NOUNIT-NOT: "-flto-unit"
Index: clang/test/CodeGenCXX/unified-cfi-lto.cpp
===
--- clang/test/CodeGenCXX/unified-cfi-lto.cpp
+++ clang/test/CodeGenCXX/unified-cfi-lto.cpp
@@ -1,6 +1,6 @@
 // Ensure that the frontend adds the proper metadata when CFI is
 // enabled.
-// RUN: %clang --target=x86_64-scei-ps4 -funified-lto -flto -fsanitize=cfi 
-fvisibility=hidden -c %s -o %t.o
+// RUN: %clang --target=x86_64-scei-ps4 -funified-lto -flto -fsanitize=cfi 
-fvisibility=hidden -fno-sanitize-ignorelist -c %s -o %t.o
 // RUN: llvm-dis %t.o -o %t1
 // RUN: FileCheck <%t1.0 %s
 
Index: clang/test/CodeGen/split-lto-unit.c
===
--- clang/test/CodeGen/split-lto-unit.c
+++ clang/test/CodeGen/split-lto-unit.c
@@ -1,6 +1,7 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
 // RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -funified-lto -triple=x86_64-scei-ps4 
-emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
@@ -12,4 +13,9 @@
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
+// ; Check that regular LTO has EnableSplitLTOUnit = 1, if using distinct 
pipelines. For unified pipelines, use EnableSplitLTOUnit = 0.
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -funified-lto -triple x86_64-scei-ps4 -emit-llvm-bc < 
%s | llvm-dis -o 

[clang] 392b306 - [clang][PS4] Enable SplitLTOUnits and Unified LTO by default

2023-07-11 Thread Matthew Voss via cfe-commits

Author: Matthew Voss
Date: 2023-07-11T16:25:07-07:00
New Revision: 392b3068075279c7e321583c4d426edf15c935ca

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

LOG: [clang][PS4] Enable SplitLTOUnits and Unified LTO by default

  - Unified LTO default for all PlayStation targets
  - Add default case to tests
  - SplitLTOUnit not default for PS4
  - Remove ignorelist requirement to address buildbot failures

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/CodeGen/split-lto-unit.c
clang/test/CodeGenCXX/unified-cfi-lto.cpp
clang/test/Driver/lto-unit.c
clang/test/Driver/split-lto-unit.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 890b99d916f116..796c60f0739285 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4776,7 +4776,7 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   // Select the appropriate action.
   RewriteKind rewriteKind = RK_None;
 
-  bool UnifiedLTO = false;
+  bool UnifiedLTO =  Triple.isPS();;
   if (IsUsingLTO) {
 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
   options::OPT_fno_unified_lto, false);
@@ -7343,7 +7343,8 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 
   bool DefaultsSplitLTOUnit =
   (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
-  (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
+  (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit()) ||
+  (!Triple.isPS4() && UnifiedLTO);
   bool SplitLTOUnit =
   Args.hasFlag(options::OPT_fsplit_lto_unit,
options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);

diff  --git a/clang/test/CodeGen/split-lto-unit.c 
b/clang/test/CodeGen/split-lto-unit.c
index b1560b61f3e30b..aaa3511d183bcf 100644
--- a/clang/test/CodeGen/split-lto-unit.c
+++ b/clang/test/CodeGen/split-lto-unit.c
@@ -1,6 +1,7 @@
 // ; Check that -flto=thin without -fsplit-lto-unit has EnableSplitLTOUnit = 0
 // RUN: %clang_cc1 -flto=thin -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
 // RUN: %clang_cc1 -flto=thin -emit-llvm < %s | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -funified-lto -triple=x86_64-scei-ps4 
-emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s
 // CHECK: !{i32 1, !"EnableSplitLTOUnit", i32 0}
 //
 // ; Check that -flto=thin with -fsplit-lto-unit has EnableSplitLTOUnit = 1
@@ -12,4 +13,9 @@
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
 // RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm < %s | 
FileCheck %s --implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
 
+// ; Check that regular LTO has EnableSplitLTOUnit = 1, if using distinct 
pipelines. For unified pipelines, use EnableSplitLTOUnit = 0.
+// RUN: %clang_cc1 -flto -triple x86_64-pc-linux-gnu -emit-llvm-bc < %s | 
llvm-dis -o - | FileCheck %s --implicit-check-not="EnableSplitLTOUnit" 
--check-prefix=SPLIT
+// RUN: %clang_cc1 -flto -funified-lto -triple x86_64-scei-ps4 -emit-llvm-bc < 
%s | llvm-dis -o - | FileCheck %s
+// RUN: %clang_cc1 -flto=thin -funified-lto -fsplit-lto-unit -triple 
x86_64-pc-linux-gnu -emit-llvm-bc < %s | llvm-dis -o - | FileCheck %s 
--implicit-check-not="EnableSplitLTOUnit" --check-prefix=SPLIT
+
 int main(void) {}

diff  --git a/clang/test/CodeGenCXX/unified-cfi-lto.cpp 
b/clang/test/CodeGenCXX/unified-cfi-lto.cpp
index cc3f594533ae1b..2c518e8e014c44 100644
--- a/clang/test/CodeGenCXX/unified-cfi-lto.cpp
+++ b/clang/test/CodeGenCXX/unified-cfi-lto.cpp
@@ -1,6 +1,6 @@
 // Ensure that the frontend adds the proper metadata when CFI is
 // enabled.
-// RUN: %clang --target=x86_64-scei-ps4 -funified-lto -flto -fsanitize=cfi 
-fvisibility=hidden -c %s -o %t.o
+// RUN: %clang --target=x86_64-scei-ps4 -funified-lto -flto -fsanitize=cfi 
-fvisibility=hidden -fno-sanitize-ignorelist -c %s -o %t.o
 // RUN: llvm-dis %t.o -o %t1
 // RUN: FileCheck <%t1.0 %s
 

diff  --git a/clang/test/Driver/lto-unit.c b/clang/test/Driver/lto-unit.c
index 43a9c24088ed11..14eadaf8ad4d26 100644
--- a/clang/test/Driver/lto-unit.c
+++ b/clang/test/Driver/lto-unit.c
@@ -4,5 +4,10 @@
 // RUN: %clang --target=x86_64-apple-darwin13.3.0 -### %s -flto=thin 2>&1 | 
FileCheck --check-prefix=UNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=full 2>&1 | FileCheck 
--check-prefix=UNIT %s
 // RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=thin 2>&1 | FileCheck 
--check-prefix=UNIT %s
+// RUN: %clang --target=x86_64-scei-ps4 -### %s -flto=full -funified-lto 2>&1 
| FileCheck --check-prefix=UNIT %s
+// RUN: 

[PATCH] D154923: [CodeGen] Support bitcode input containing multiple modules

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D154923#4491411 , @efriedma wrote:

> If I follow correctly, this is basically undoing the splitting that was done 
> by the command that produced the bitcode file?

Yes, undoing `llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp` change that 
would make the output bitcode file not usable as an input for non-LTO use cases.

> I guess that could be useful.  But it requires either renaming your object 
> files from the default ".o" to ".bc", or explicitly passing "-x ir"?  That 
> seems unintuitive.  Maybe it's better to put this behind some explicit flag?

Yes, specify `-x ir` or let the driver deduce the file type with the predefined 
extension `.bc`.

I think this is a less common operation (compiling with LTO but then using as 
non-LTO), so I think adding another option seems not necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154923

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


[PATCH] D150803: [WebAssembly] Support `annotate` clang attributes for marking functions.

2023-07-11 Thread Derek Schuff via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG220fe00a7c0f: [WebAssembly] Support `annotate` clang 
attributes for marking functions. (authored by brendandahl, committed by 
dschuff).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150803

Files:
  lld/test/wasm/func-attr-tombstone.s
  lld/test/wasm/func-attr.s
  lld/test/wasm/merge-func-attr-section.s
  lld/wasm/InputChunks.cpp
  lld/wasm/InputFiles.cpp
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/BinaryFormat/WasmRelocs.def
  llvm/include/llvm/MC/MCExpr.h
  llvm/lib/MC/MCExpr.cpp
  llvm/lib/MC/WasmObjectWriter.cpp
  llvm/lib/Object/WasmObjectFile.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
  llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
  llvm/test/MC/WebAssembly/func-attr.s

Index: llvm/test/MC/WebAssembly/func-attr.s
===
--- /dev/null
+++ llvm/test/MC/WebAssembly/func-attr.s
@@ -0,0 +1,21 @@
+# RUN: llvm-mc -triple=wasm32-unknown-unknown < %s | FileCheck %s
+# Check that it also comiled to object for format.
+# RUN: llvm-mc -triple=wasm32-unknown-unknown -filetype=obj -o - < %s | obj2yaml | FileCheck -check-prefix=CHECK-OBJ %s
+
+foo:
+.globl foo
+.functype foo () -> ()
+end_function
+
+.section.custom_section.llvm.func_attr.custom0,"",@
+.int32  foo@FUNCINDEX
+
+# CHECK:   .section .custom_section.llvm.func_attr.custom0,"",@
+# CHECK-NEXT: .int32  foo@FUNCINDEX
+
+# CHECK-OBJ:- Type:CUSTOM
+# CHECK-OBJ-NEXT: Relocations:
+# CHECK-OBJ-NEXT:- Type:R_WASM_FUNCTION_INDEX_I32
+# CHECK-OBJ-NEXT:  Index:   0
+# CHECK-OBJ-NEXT:  Offset:  0x0
+# CHECK-OBJ-NEXT: Name:llvm.func_attr.custom0
Index: llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
@@ -0,0 +1,31 @@
+; RUN: llc < %s -asm-verbose=false -wasm-keep-registers | FileCheck %s
+
+target triple = "wasm32-unknown-unknown"
+
+@.str = private unnamed_addr constant [8 x i8] c"custom0\00", section "llvm.metadata"
+@.str.1 = private unnamed_addr constant [7 x i8] c"main.c\00", section "llvm.metadata"
+@.str.2 = private unnamed_addr constant [8 x i8] c"custom1\00", section "llvm.metadata"
+@.str.3 = private unnamed_addr constant [8 x i8] c"custom2\00", section "llvm.metadata"
+@llvm.global.annotations = appending global [3 x { ptr, ptr, ptr, i32, ptr }] [{ ptr, ptr, ptr, i32, ptr } { ptr @test0, ptr @.str, ptr @.str.1, i32 4, ptr null }, { ptr, ptr, ptr, i32, ptr } { ptr @test1, ptr @.str, ptr @.str.1, i32 5, ptr null }, { ptr, ptr, ptr, i32, ptr } { ptr @test2, ptr @.str.2, ptr @.str.1, i32 6, ptr null }], section "llvm.metadata"
+
+define void @test0() {
+  ret void
+}
+
+define void @test1() {
+  ret void
+}
+
+define void @test2() {
+  ret void
+}
+
+define void @test3() {
+  ret void
+}
+
+; CHECK:  .section.custom_section.llvm.func_attr.annotate.custom0,"",@
+; CHECK-NEXT: .int32  test0@FUNCINDEX
+; CHECK-NEXT: .int32  test1@FUNCINDEX
+; CHECK:  .section.custom_section.llvm.func_attr.annotate.custom1,"",@
+; CHECK-NEXT: .int32  test2@FUNCINDEX
Index: llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
===
--- llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
+++ llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
@@ -66,6 +66,7 @@
   void emitEndOfAsmFile(Module ) override;
   void EmitProducerInfo(Module );
   void EmitTargetFeatures(Module );
+  void EmitFunctionAttributes(Module );
   void emitSymbolType(const MCSymbolWasm *Sym);
   void emitGlobalVariable(const GlobalVariable *GV) override;
   void emitJumpTableInfo() override;
Index: llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
@@ -27,6 +27,8 @@
 #include "WebAssemblyTargetMachine.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/BinaryFormat/Wasm.h"
 #include "llvm/CodeGen/Analysis.h"
 #include "llvm/CodeGen/AsmPrinter.h"
@@ -438,6 +440,7 @@
 
   EmitProducerInfo(M);
   EmitTargetFeatures(M);
+  EmitFunctionAttributes(M);
 }
 
 void WebAssemblyAsmPrinter::EmitProducerInfo(Module ) {
@@ -556,6 +559,49 @@
   OutStreamer->popSection();
 }
 
+void WebAssemblyAsmPrinter::EmitFunctionAttributes(Module ) {
+  

[PATCH] D153906: [clang] Allow disassembly of multi-module bitcode files

2023-07-11 Thread Matthew Voss via Phabricator via cfe-commits
ormris added a comment.

Thanks! Pushed as 048a0c246908291c82d2f4531d3df45a4c4a8a18 
.


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

https://reviews.llvm.org/D153906

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


[clang] 048a0c2 - [clang] Support Unified LTO Bitcode Frontend

2023-07-11 Thread Matthew Voss via cfe-commits

Author: Matthew Voss
Date: 2023-07-11T15:13:57-07:00
New Revision: 048a0c246908291c82d2f4531d3df45a4c4a8a18

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

LOG: [clang] Support Unified LTO Bitcode Frontend

The unified LTO pipeline creates a single LTO bitcode structure that can
be used by Thin or Full LTO. This means that the LTO mode can be chosen
at link time and that all LTO bitcode produced by the pipeline is
compatible, from an optimization perspective. This makes the behavior of
LTO a bit more predictable by normalizing the set of LTO features
supported by each LTO bitcode file.

Example usage:

  # Compile and link. Select regular LTO at link time.
  clang -flto -funified-lto -fuse-ld=lld foo.c

  # Compile and link. Select ThinLTO at link time.
  clang -flto=thin -funified-lto -fuse-ld=lld foo.c

  # Link separately, using ThinLTO.
  clang -c -flto -funified-lto foo.c  # -flto={full,thin} are identical in
  terms of compilation actions
  clang -flto=thin -fuse-ld=lld foo.o  # pass --lto=thin to ld.lld

  # Link separately, using regular LTO.
  clang -c -flto -funified-lto foo.c
  clang -flto -fuse-ld=lld foo.o  # pass --lto=full to ld.lld

The RFC discussing the details and rational for this change is here:
https://discourse.llvm.org/t/rfc-a-unified-lto-bitcode-frontend/61774

Added: 
clang/test/CodeGen/asan-unified-lto.ll
clang/test/CodeGen/unified-lto-pipeline.c
clang/test/CodeGenCXX/unified-cfi-lto.cpp
clang/test/Driver/unified-lto.c

Modified: 
clang/include/clang/Basic/CodeGenOptions.def
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/PS4CPU.cpp
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/CodeGen/emit-summary-index.c
clang/test/Driver/whole-program-vtables.c

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 5b18f45a04ab1a..a03447ca2931e2 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -168,6 +168,7 @@ CODEGENOPT(EnableSplitLTOUnit, 1, 0) ///< Enable LTO unit 
splitting to support
 /// CFI and traditional whole program
 /// devirtualization that require whole
 /// program IR support.
+CODEGENOPT(UnifiedLTO, 1, 0) ///< Use the unified LTO pipeline.
 CODEGENOPT(IncrementalLinkerCompatible, 1, 0) ///< Emit an object file which 
can
   ///< be used with an incremental
   ///< linker.

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c5230d11baeddf..aacdf09bec1e6f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2341,6 +2341,11 @@ def flto_EQ_auto : Flag<["-"], "flto=auto">, 
Group,
   Alias, AliasArgs<["full"]>, HelpText<"Enable LTO in 'full' mode">;
 def flto : Flag<["-"], "flto">, Flags<[CoreOption, CC1Option, FC1Option, 
FlangOption]>, Group,
   Alias, AliasArgs<["full"]>, HelpText<"Enable LTO in 'full' mode">;
+defm unified_lto : BoolFOption<"unified-lto",
+  CodeGenOpts<"UnifiedLTO">, DefaultFalse,
+  PosFlag,
+  NegFlag,
+  BothFlags<[CC1Option], "">>;
 def fno_lto : Flag<["-"], "fno-lto">, Flags<[CoreOption, CC1Option]>, 
Group,
   HelpText<"Disable LTO mode (default)">;
 def foffload_lto_EQ : Joined<["-"], "foffload-lto=">, Flags<[CoreOption]>, 
Group,

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 06af08023d1be9..1b0c249f440899 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -831,6 +831,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   // Only enable CGProfilePass when using integrated assembler, since
   // non-integrated assemblers don't recognize .cgprofile section.
   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
+  PTO.UnifiedLTO = CodeGenOpts.UnifiedLTO;
 
   LoopAnalysisManager LAM;
   FunctionAnalysisManager FAM;
@@ -1010,7 +1011,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   });
 }
 
-if (IsThinLTO) {
+if (IsThinLTO || (IsLTO && CodeGenOpts.UnifiedLTO)) {
   MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
 } else if (IsLTO) {
   MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
@@ -1036,8 +1037,10 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   if (!ThinLinkOS)
 return;
 }
-MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? 
>os()
- 

[PATCH] D154923: [CodeGen] Support bitcode input containing multiple modules

2023-07-11 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

If I follow correctly, this is basically undoing the splitting that was done by 
the command that produced the bitcode file?  I guess that could be useful.  But 
it requires either renaming your object files from the default ".o" to ".bc", 
or explicitly passing "-x ir"?  That seems unintuitive.  Maybe it's better to 
put this behind some explicit flag?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154923

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


[PATCH] D154290: [Clang] Implement P2741R3 - user-generated static_assert messages

2023-07-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

(Not a full review, I ran out of steam -- I wanted to get you some feedback 
that I already found though.)




Comment at: clang/include/clang/AST/Expr.h:766-767
+  bool EvaluateCharPointerAsString(std::string ,
+   const Expr *SizeExpression,
+   const Expr *PtrExpression, ASTContext ,
+   EvalResult ) const;

The function name confuses me a bit because a char pointer doesn't have a size 
expression. I was thinking "EvaluateCharArrayAsString" but that's also not 
right.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:86
   "%select{case value|enumerator value|non-type template argument|"
-  "array size|explicit specifier argument|noexcept specifier argument}0 "
+  "array size|explicit specifier argument|noexcept specifier argument|call to 
size()|call to data()}0 "
   "is not a constant expression">;

This should also be re-flowed to 80 columns.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:1545-1546
   "expression evaluates to '%0 %1 %2'">;
+def err_static_assert_invalid_message : Error<"the message in a static_assert "
+  "declaration must be a string literal or an object with data() and size() 
member functions">;
+def err_static_assert_invalid_size : Error<"the message in a static_assert 
declaration "

And re-flow to 80 columns. You should make similar changes in the other new 
diagnostics as well. (Use single quotes around syntax elements, start the 
string on its own line rather inline with the `def`, use "static assertion" 
instead of "static_assert" (The last point is largely because C has both 
_Static_assert and static_assert and we're avoiding figuring out which one was 
used. It may be moot as this is C++-only functionality, but it is more 
consistent with other static assert diagnostics.)



Comment at: clang/lib/AST/ExprConstant.cpp:16417-16418
+  }
+  if (!Scope.destroy())
+return false;
+

Rather than use an RAII object and destroy it manually, let's use `{}` to scope 
the RAII object appropriately.



Comment at: clang/lib/AST/ExprConstant.cpp:16413
+APSInt C = Char.getInt();
+Result.push_back(static_cast(C.getExtValue()));
+if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))

barannikov88 wrote:
> This relies on host's CHAR_BIT >= target's CHAR_BIT, which isn't true for my 
> target. Could you add an assertion?
> 
Wouldn't adding the assertion cause you problems then? (FWIW, we only support 
`CHAR_BIT == 8` currently.)



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:16922-16927
+  std::optional SizeMember = FindMember("size");
+  std::optional DataMember = FindMember("data");
+  if (!SizeMember || !DataMember) {
+Diag(Message->getBeginLoc(), diag::err_static_assert_invalid_message);
+return false;
+  }

It might be more friendly to tell the user which was missing, `size` or `data`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154290

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


[PATCH] D153621: [Clang] Correctly handle $, @, and ` when represented as UCN

2023-07-11 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann accepted this revision.
tahonermann added a comment.
This revision is now accepted and ready to land.

> I'll probably merge that EoW unless you scream!

Why wait? :) Looks good!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153621

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


[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin added inline comments.



Comment at: clang/unittests/Driver/ToolChainTest.cpp:371
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang", "-gdwarf-4", 
"-gsplit-dwarf=single", "-c", "foo.cpp"};
+  CreateInvocationOptions CIOpts;

MaskRay wrote:
> DmitryPolukhin wrote:
> > MaskRay wrote:
> > > Without a concrete target triple, the default is used. If the default 
> > > target triple uses an object file format not supporting -gsplit-dwarf, 
> > > this will fail.
> > Oh, could you please advise how to select right target triple for the test 
> > or limit it to the case when triple I specify here is supported? I had 
> > issue in the past with triples and it was tricky to select something that 
> > makes all llvm bots happy. I added `-target arm-linux-gnueabi` and test 
> > seems to be working if only x86 arch is enabled.
> `-target ` has been deprecated since Clang 3.4. Use 
> `--target=arm-linux-gnueabi`.
> 
> If you just run the driver, you don't need a target in 
> `LLVM_TARGETS_TO_BUILD`.
> If you do code generation, `LLVM_TARGETS_TO_BUILD` is needed.
> This is tricky, you likely need two build directories to check this...
> 
> ```
> % /tmp/out/custom1/bin/clang --target=aarch64 -c a.cc
> error: unable to create target: 'No available targets are compatible with 
> triple "aarch64"'
> 1 error generated.
> ```
Yes, my driver test works fine regardless `LLVM_TARGETS_TO_BUILD`, also tested 
with `-###`
Will wait for build bots completion just in case and push tomorrow. Thank you 
for review and the detailed explanation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

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


[PATCH] D145302: [clangd] Add library for clangd main function

2023-07-11 Thread Ivan Murashko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG56ac9d46a7c1: [clangd] Add library for clangd main function 
(authored by ivanmurashko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145302

Files:
  clang-tools-extra/clangd/tool/CMakeLists.txt
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/tool/ClangdMain.h
  clang-tools-extra/clangd/tool/ClangdToolMain.cpp

Index: clang-tools-extra/clangd/tool/ClangdToolMain.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/tool/ClangdToolMain.cpp
@@ -0,0 +1,13 @@
+//===--- ClangdToolMain.cpp - clangd main function ===//
+//
+// 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 "ClangdMain.h"
+
+int main(int argc, char **argv) {
+  return clang::clangd::clangdMain(argc, argv);
+}
Index: clang-tools-extra/clangd/tool/ClangdMain.h
===
--- /dev/null
+++ clang-tools-extra/clangd/tool/ClangdMain.h
@@ -0,0 +1,19 @@
+//===--- ClangdMain.h - clangd main function ===//
+//
+// 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H
+
+namespace clang {
+namespace clangd {
+// clangd main function (clangd server loop)
+int clangdMain(int argc, char *argv[]);
+} // namespace clangd
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -6,6 +6,7 @@
 //
 //===--===//
 
+#include "ClangdMain.h"
 #include "ClangdLSPServer.h"
 #include "CodeComplete.h"
 #include "Compiler.h"
@@ -710,8 +711,6 @@
   }
 };
 } // namespace
-} // namespace clangd
-} // namespace clang
 
 enum class ErrorResultCode : int {
   NoShutdownRequest = 1,
@@ -719,10 +718,7 @@
   CheckFailed = 3
 };
 
-int main(int argc, char *argv[]) {
-  using namespace clang;
-  using namespace clang::clangd;
-
+int clangdMain(int argc, char *argv[]) {
   llvm::InitializeAllTargetInfos();
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::sys::AddSignalHandler(
@@ -1041,3 +1037,6 @@
 
   return ExitCode;
 }
+
+} // namespace clangd
+} // namespace clang
Index: clang-tools-extra/clangd/tool/CMakeLists.txt
===
--- clang-tools-extra/clangd/tool/CMakeLists.txt
+++ clang-tools-extra/clangd/tool/CMakeLists.txt
@@ -1,6 +1,13 @@
-add_clang_tool(clangd
+# Needed by LLVM's CMake checks because this file defines multiple targets.
+set(LLVM_OPTIONAL_SOURCES ClangdToolMain.cpp)
+
+add_clang_library(clangdMain
   ClangdMain.cpp
   Check.cpp
+  )
+
+add_clang_tool(clangd
+  ClangdToolMain.cpp
   $
   )
 
@@ -13,7 +20,7 @@
   list(APPEND CLANGD_XPC_LIBS "clangdXpcJsonConversions" "clangdXpcTransport")
 endif()
 
-clang_target_link_libraries(clangd
+clang_target_link_libraries(clangdMain
   PRIVATE
   clangAST
   clangBasic
@@ -25,14 +32,14 @@
   clangToolingCore
   clangToolingRefactoring
   clangToolingSyntax
-  )
-
-target_link_libraries(clangd
-  PRIVATE
   clangTidy
-
   clangDaemon
   clangdRemoteIndex
   clangdSupport
   ${CLANGD_XPC_LIBS}
   )
+
+clang_target_link_libraries(clangd
+  PRIVATE
+  clangdMain
+  )
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 56ac9d4 - [clangd] Add library for clangd main function

2023-07-11 Thread Ivan Murashko via cfe-commits

Author: Ivan Murashko
Date: 2023-07-11T21:48:50+01:00
New Revision: 56ac9d46a7c1468d587ccec02a781e52d0bb298a

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

LOG: [clangd] Add library for clangd main function

The diff adds a library and header for clangd main function. That change allows 
to create custom builds for clangd outside the main LLVM repo. The diff also 
allows to use build system different from CMake to build clangd. The main 
reason for such change is an ability to use custom clang-tidy modules (created 
outside LLVM repo).

Test Plan:
```
ninja clangd
```
also check that necessary libs are installed aka
```
ninja install
...
ls /lib/libclangdMain.a
```

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

Added: 
clang-tools-extra/clangd/tool/ClangdMain.h
clang-tools-extra/clangd/tool/ClangdToolMain.cpp

Modified: 
clang-tools-extra/clangd/tool/CMakeLists.txt
clang-tools-extra/clangd/tool/ClangdMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/CMakeLists.txt 
b/clang-tools-extra/clangd/tool/CMakeLists.txt
index 5a1556b813b595..223bd7c606f7d1 100644
--- a/clang-tools-extra/clangd/tool/CMakeLists.txt
+++ b/clang-tools-extra/clangd/tool/CMakeLists.txt
@@ -1,6 +1,13 @@
-add_clang_tool(clangd
+# Needed by LLVM's CMake checks because this file defines multiple targets.
+set(LLVM_OPTIONAL_SOURCES ClangdToolMain.cpp)
+
+add_clang_library(clangdMain
   ClangdMain.cpp
   Check.cpp
+  )
+
+add_clang_tool(clangd
+  ClangdToolMain.cpp
   $
   )
 
@@ -13,7 +20,7 @@ if(CLANGD_BUILD_XPC)
   list(APPEND CLANGD_XPC_LIBS "clangdXpcJsonConversions" "clangdXpcTransport")
 endif()
 
-clang_target_link_libraries(clangd
+clang_target_link_libraries(clangdMain
   PRIVATE
   clangAST
   clangBasic
@@ -25,14 +32,14 @@ clang_target_link_libraries(clangd
   clangToolingCore
   clangToolingRefactoring
   clangToolingSyntax
-  )
-
-target_link_libraries(clangd
-  PRIVATE
   clangTidy
-
   clangDaemon
   clangdRemoteIndex
   clangdSupport
   ${CLANGD_XPC_LIBS}
   )
+
+clang_target_link_libraries(clangd
+  PRIVATE
+  clangdMain
+  )

diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index ab5169171e3d87..27f70a527cd3cb 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -6,6 +6,7 @@
 //
 
//===--===//
 
+#include "ClangdMain.h"
 #include "ClangdLSPServer.h"
 #include "CodeComplete.h"
 #include "Compiler.h"
@@ -710,8 +711,6 @@ class FlagsConfigProvider : public config::Provider {
   }
 };
 } // namespace
-} // namespace clangd
-} // namespace clang
 
 enum class ErrorResultCode : int {
   NoShutdownRequest = 1,
@@ -719,10 +718,7 @@ enum class ErrorResultCode : int {
   CheckFailed = 3
 };
 
-int main(int argc, char *argv[]) {
-  using namespace clang;
-  using namespace clang::clangd;
-
+int clangdMain(int argc, char *argv[]) {
   llvm::InitializeAllTargetInfos();
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::sys::AddSignalHandler(
@@ -1041,3 +1037,6 @@ clangd accepts flags on the commandline, and in the 
CLANGD_FLAGS environment var
 
   return ExitCode;
 }
+
+} // namespace clangd
+} // namespace clang

diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.h 
b/clang-tools-extra/clangd/tool/ClangdMain.h
new file mode 100644
index 00..bd0f51aac83bb3
--- /dev/null
+++ b/clang-tools-extra/clangd/tool/ClangdMain.h
@@ -0,0 +1,19 @@
+//===--- ClangdMain.h - clangd main function ===//
+//
+// 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
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H
+
+namespace clang {
+namespace clangd {
+// clangd main function (clangd server loop)
+int clangdMain(int argc, char *argv[]);
+} // namespace clangd
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_TOOL_CLANGDMAIN_H

diff  --git a/clang-tools-extra/clangd/tool/ClangdToolMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdToolMain.cpp
new file mode 100644
index 00..b62ff362bd2a96
--- /dev/null
+++ b/clang-tools-extra/clangd/tool/ClangdToolMain.cpp
@@ -0,0 +1,13 @@
+//===--- ClangdToolMain.cpp - clangd main function 
===//
+//
+// 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: 

[PATCH] D154300: [CUDA][HIP] Fix template argument deduction

2023-07-11 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Sema/SemaOverload.cpp:12758-12764
+std::optional MorePreferableByCUDA =
+CheckCUDAPreference(FD, Result);
+// If FD has different CUDA preference than Result.
+if (MorePreferableByCUDA) {
+  // FD is less preferable than Result.
+  if (!*MorePreferableByCUDA)
+continue;

Maybe `CheckCUDAPreference` should return -1/0/1 or an enum. std::optional does 
not seem to be very readable here.

E.g. `if(MorePreferableByCUDA)` sounds like it's going to be satisfied when FD 
is a better choice than Result, but it's not the case.
I think this would be easier to follow:
```
if (CheckCUDAPreference(FD, Result) <= 0) // or `!= CP_BETTER`
 continue;
```



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

https://reviews.llvm.org/D154300

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


[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 539283.
DmitryPolukhin added a comment.

Run clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/unittests/Driver/ToolChainTest.cpp


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,16 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {
+  "clang", "--target=arm-linux-gnueabi",
+  "-gdwarf-4", "-gsplit-dwarf=single",
+  "-c","foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,16 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {
+  "clang", "--target=arm-linux-gnueabi",
+  "-gdwarf-4", "-gsplit-dwarf=single",
+  "-c","foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 539281.
DmitryPolukhin added a comment.

Use --target=arm-linux-gnueabi


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/unittests/Driver/ToolChainTest.cpp


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,18 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang",
+ "--target=arm-linux-gnueabi",
+ "-gdwarf-4",
+ "-gsplit-dwarf=single",
+ "-c",
+ "foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,18 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang",
+ "--target=arm-linux-gnueabi",
+ "-gdwarf-4",
+ "-gsplit-dwarf=single",
+ "-c",
+ "foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155012: Fix types of arm64 MSVC __readx18/__writex18 intrinsics

2023-07-11 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak created this revision.
ahatanak added reviewers: ravikandhadai, Bigcheese, steplong.
ahatanak added a project: clang.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
ahatanak requested review of this revision.
Herald added a subscriber: wangpc.

Using `L` for type `long` results in clang passing 64-bit integers to these 
intrinsics on LP64 operating systems. This isn't correct as the intrinsics 
accept 32-bit integers.

Use `N` instead of `L` so that 32-bit integers are passed to the intrinsics on 
LP64 operating systems too. This is the same fix as the following two commits:

33703fb9f908113f93bd9af83a79eb56f5131735
afa47c91ce5085d446ebb5ac1312dc98b6a68a6c


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155012

Files:
  clang/include/clang/Basic/BuiltinsAArch64.def
  clang/test/CodeGen/arm64-microsoft-intrinsics.c

Index: clang/test/CodeGen/arm64-microsoft-intrinsics.c
===
--- clang/test/CodeGen/arm64-microsoft-intrinsics.c
+++ clang/test/CodeGen/arm64-microsoft-intrinsics.c
@@ -1,9 +1,12 @@
 // RUN: %clang_cc1 -triple arm64-windows -Wno-implicit-function-declaration -fms-compatibility -emit-llvm -o - %s \
-// RUN:| FileCheck %s -check-prefix CHECK-MSVC
+// RUN:| FileCheck %s --check-prefix=CHECK-MSVC --check-prefix=CHECK-MSCOMPAT
 
 // RUN: not %clang_cc1 -triple arm64-linux -Werror -S -o /dev/null %s 2>&1 \
 // RUN:| FileCheck %s -check-prefix CHECK-LINUX
 
+// RUN: %clang_cc1 -triple arm64-darwin -Wno-implicit-function-declaration -fms-compatibility -emit-llvm -o - %s \
+// RUN:| FileCheck %s -check-prefix CHECK-MSCOMPAT
+
 long test_InterlockedAdd(long volatile *Addend, long Value) {
   return _InterlockedAdd(Addend, Value);
 }
@@ -117,128 +120,150 @@
   return reg;
 }
 
-// CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD2:.*]])
-// CHECK-MSVC: call i64 @llvm.read_register.i64(metadata ![[MD3:.*]])
+// CHECK-MSCOMPAT: call i64 @llvm.read_register.i64(metadata ![[MD2:.*]])
+// CHECK-MSCOMPAT: call i64 @llvm.read_register.i64(metadata ![[MD3:.*]])
+
+#ifdef __LP64__
+#define LONG __int32
+#else
+#define LONG long
+#endif
 
-void check__writex18byte(unsigned long offset, unsigned char data) {
+#ifdef __LP64__
+void check__writex18byte(unsigned char data, unsigned LONG offset) {
+#else
+void check__writex18byte(unsigned LONG offset, unsigned char data) {
+#endif
   __writex18byte(offset, data);
 }
 
-// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i8, align 1
-// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
-// CHECK-MSVC: store i8 %data, ptr %[[DATA_ADDR]], align 1
-// CHECK-MSVC: store i32 %offset, ptr %[[OFFSET_ADDR]], align 4
-// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
-// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to ptr
-// CHECK-MSVC: %[[OFFSET:.*]] = load i32, ptr %[[OFFSET_ADDR]], align 4
-// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
-// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, ptr %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
-// CHECK-MSVC: %[[DATA:.*]] = load i8, ptr %[[DATA_ADDR]], align 1
-// CHECK-MSVC: store i8 %[[DATA]], ptr %[[PTR]], align 1
-
-void check__writex18word(unsigned long offset, unsigned short data) {
+// CHECK-MSCOMPAT: %[[DATA_ADDR:.*]] = alloca i8, align 1
+// CHECK-MSCOMPAT: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
+// CHECK-MSCOMPAT: store i8 %data, ptr %[[DATA_ADDR]], align 1
+// CHECK-MSCOMPAT: store i32 %offset, ptr %[[OFFSET_ADDR]], align 4
+// CHECK-MSCOMPAT: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
+// CHECK-MSCOMPAT: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to ptr
+// CHECK-MSCOMPAT: %[[OFFSET:.*]] = load i32, ptr %[[OFFSET_ADDR]], align 4
+// CHECK-MSCOMPAT: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
+// CHECK-MSCOMPAT: %[[PTR:.*]] = getelementptr i8, ptr %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
+// CHECK-MSCOMPAT: %[[DATA:.*]] = load i8, ptr %[[DATA_ADDR]], align 1
+// CHECK-MSCOMPAT: store i8 %[[DATA]], ptr %[[PTR]], align 1
+
+#ifdef __LP64__
+void check__writex18word(unsigned short data, unsigned LONG offset) {
+#else
+void check__writex18word(unsigned LONG offset, unsigned short data) {
+#endif
   __writex18word(offset, data);
 }
 
-// CHECK-MSVC: %[[DATA_ADDR:.*]] = alloca i16, align 2
-// CHECK-MSVC: %[[OFFSET_ADDR:.*]] = alloca i32, align 4
-// CHECK-MSVC: store i16 %data, ptr %[[DATA_ADDR]], align 2
-// CHECK-MSVC: store i32 %offset, ptr %[[OFFSET_ADDR]], align 4
-// CHECK-MSVC: %[[X18:.*]] = call i64 @llvm.read_register.i64(metadata ![[MD2]])
-// CHECK-MSVC: %[[X18_AS_PTR:.*]] = inttoptr i64 %[[X18]] to ptr
-// CHECK-MSVC: %[[OFFSET:.*]] = load i32, ptr %[[OFFSET_ADDR]], align 4
-// CHECK-MSVC: %[[ZEXT_OFFSET:.*]] = zext i32 %[[OFFSET]] to i64
-// CHECK-MSVC: %[[PTR:.*]] = getelementptr i8, ptr %[[X18_AS_PTR]], i64 %[[ZEXT_OFFSET]]
-// CHECK-MSVC: %[[DATA:.*]] = load i16, ptr %[[DATA_ADDR]], align 2
-// 

[clang] 546ec64 - Restore "[MemProf] Use new option/pass for profile feedback and matching"

2023-07-11 Thread Teresa Johnson via cfe-commits

Author: Teresa Johnson
Date: 2023-07-11T13:16:20-07:00
New Revision: 546ec641b4b1bbbf9e66a53983b635fe85d365e6

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

LOG: Restore "[MemProf] Use new option/pass for profile feedback and matching"

This restores commit b4a82b62258c5f650a1cccf5b179933e6bae4867, reverted
in 3ab7ef28eebf9019eb3d3c4efd7ebfd160106bb1 because it was thought to
cause a bot failure, which ended up being unrelated to this patch set.

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.h
clang/include/clang/Driver/Options.td
clang/lib/CodeGen/BackendUtil.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/CodeGen/memprof.cpp
clang/test/Driver/fmemprof.cpp
llvm/include/llvm/Support/PGOOptions.h
llvm/include/llvm/Transforms/Instrumentation/MemProfiler.h
llvm/lib/LTO/LTOBackend.cpp
llvm/lib/Passes/PassBuilder.cpp
llvm/lib/Passes/PassBuilderPipelines.cpp
llvm/lib/Passes/PassRegistry.def
llvm/lib/Support/PGOOptions.cpp
llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
llvm/lib/Transforms/Instrumentation/PGOInstrumentation.cpp
llvm/test/Transforms/PGOProfile/memprof.ll
llvm/test/Transforms/PGOProfile/memprofmissingfunc.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index b0f22411e1ad20..fadfff48582eea 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -282,6 +282,9 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// Name of the profile file to use as output for with -fmemory-profile.
   std::string MemoryProfileOutput;
 
+  /// Name of the profile file to use as input for -fmemory-profile-use.
+  std::string MemoryProfileUsePath;
+
   /// Name of the profile file to use as input for -fprofile-instr-use
   std::string ProfileInstrumentUsePath;
 

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index a34eab4064997a..c5230d11baeddf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1772,6 +1772,10 @@ defm memory_profile : OptInCC1FFlag<"memory-profile", 
"Enable", "Disable", " hea
 def fmemory_profile_EQ : Joined<["-"], "fmemory-profile=">,
 Group, Flags<[CC1Option]>, MetaVarName<"">,
 HelpText<"Enable heap memory profiling and dump results into ">;
+def fmemory_profile_use_EQ : Joined<["-"], "fmemory-profile-use=">,
+Group, Flags<[CC1Option, CoreOption]>, MetaVarName<"">,
+HelpText<"Use memory profile for profile-guided memory optimization">,
+MarshallingInfoString>;
 
 // Begin sanitizer flags. These should all be core options exposed in all 
driver
 // modes.

diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 458756509b3a3d..06af08023d1be9 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -762,31 +762,37 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 PGOOpt = PGOOptions(
 CodeGenOpts.InstrProfileOutput.empty() ? getDefaultProfileGenName()
: 
CodeGenOpts.InstrProfileOutput,
-"", "", nullptr, PGOOptions::IRInstr, PGOOptions::NoCSAction,
-CodeGenOpts.DebugInfoForProfiling);
+"", "", CodeGenOpts.MemoryProfileUsePath, nullptr, PGOOptions::IRInstr,
+PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
   else if (CodeGenOpts.hasProfileIRUse()) {
 // -fprofile-use.
 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
 : PGOOptions::NoCSAction;
-PGOOpt =
-PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
-   CodeGenOpts.ProfileRemappingFile, VFS, PGOOptions::IRUse,
-   CSAction, CodeGenOpts.DebugInfoForProfiling);
+PGOOpt = PGOOptions(
+CodeGenOpts.ProfileInstrumentUsePath, "",
+CodeGenOpts.ProfileRemappingFile, CodeGenOpts.MemoryProfileUsePath, 
VFS,
+PGOOptions::IRUse, CSAction, CodeGenOpts.DebugInfoForProfiling);
   } else if (!CodeGenOpts.SampleProfileFile.empty())
 // -fprofile-sample-use
 PGOOpt = PGOOptions(
 CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
-VFS, PGOOptions::SampleUse, PGOOptions::NoCSAction,
-CodeGenOpts.DebugInfoForProfiling, 
CodeGenOpts.PseudoProbeForProfiling);
+CodeGenOpts.MemoryProfileUsePath, VFS, PGOOptions::SampleUse,
+PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling,
+CodeGenOpts.PseudoProbeForProfiling);
+  

[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added inline comments.



Comment at: clang/unittests/Driver/ToolChainTest.cpp:371
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang", "-gdwarf-4", 
"-gsplit-dwarf=single", "-c", "foo.cpp"};
+  CreateInvocationOptions CIOpts;

DmitryPolukhin wrote:
> MaskRay wrote:
> > Without a concrete target triple, the default is used. If the default 
> > target triple uses an object file format not supporting -gsplit-dwarf, this 
> > will fail.
> Oh, could you please advise how to select right target triple for the test or 
> limit it to the case when triple I specify here is supported? I had issue in 
> the past with triples and it was tricky to select something that makes all 
> llvm bots happy. I added `-target arm-linux-gnueabi` and test seems to be 
> working if only x86 arch is enabled.
`-target ` has been deprecated since Clang 3.4. Use 
`--target=arm-linux-gnueabi`.

If you just run the driver, you don't need a target in `LLVM_TARGETS_TO_BUILD`.
If you do code generation, `LLVM_TARGETS_TO_BUILD` is needed.
This is tricky, you likely need two build directories to check this...

```
% /tmp/out/custom1/bin/clang --target=aarch64 -c a.cc
error: unable to create target: 'No available targets are compatible with 
triple "aarch64"'
1 error generated.
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

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


[PATCH] D152924: [libLTO][AIX] Respect `-f[no]-integrated-as` on AIX

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.

Some nits about testing, otherwise LG

In D152924#4490950 , @qiongsiwu1 
wrote:

> In D152924#4490581 , @MaskRay wrote:
>
>> We have `TargetOptions::DisableIntegratedAS` (your llc.cpp change). Do you 
>> know why it is not feasible for the places you want to check?
>
> I am checking/using `TargetOptions::DisableIntegratedAS` in 
> `LTOCodeGenerator::useAIXSystemAssembler()` to determine if the system 
> assembler should be used. `NoIntegratedAssembler` is moved from an `llc` only 
> option to a codegen option so LTO can use it as well.

Sorry, my question was not clear. Anyway, I figured it out.
We need to pass `lto::Config` to `lto::backend` with the correct `CGFileType` 
information.  `TargetOptions::DisableIntegratedAS` is already present, but we 
don't initialize it in `llvm/lib/CodeGen/CommandFlags.cpp`.
Thanks. This looks good to me.




Comment at: llvm/test/tools/llvm-lto/aix-sys-as.ll:1
+; REQUIRES: system-aix
+; RUN: llvm-as < %s > %t1

I suggest that you merge this test into aix.ll.

You can use

```
RUN: %if system-aix %{ ... %}
```
to only run a RUN line when the lit feature `system-aix` is available.



Comment at: llvm/test/tools/llvm-lto/aix.ll:3
 ; RUN: llvm-as < %s > %t1
 ; RUN: llvm-lto %t1 | FileCheck %s
 

It seems that with or without `-o`, the behavior may be different?

In some lit configurations (e.g., Google's internal lit runner), the current 
working directory if a test invocation is read-only. We need to ensure that the 
directory is writable.

You can do
```
RUN: rm -rf %t && mkdir %t && cd %t`
RUN: llvm-as < %s -o a.bc
RUN: llvm-lto a.bc
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152924

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


[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

2023-07-11 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

Thanks for the review :D


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

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


[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

2023-07-11 Thread Corentin Jabot via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
cor3ntin marked 2 inline comments as done.
Closed by commit rGb0cc947b5d0a: [Clang] Diagnose jumps into statement 
expressions (authored by cor3ntin).

Changed prior to commit:
  https://reviews.llvm.org/D154696?vs=538252=539251#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/JumpDiagnostics.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
  clang/test/Sema/asm-goto.cpp
  clang/test/Sema/scope-check.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaObjC/scope-check.m

Index: clang/test/SemaObjC/scope-check.m
===
--- clang/test/SemaObjC/scope-check.m
+++ clang/test/SemaObjC/scope-check.m
@@ -15,7 +15,7 @@
   } @finally {// expected-note {{jump bypasses initialization of @finally block}}
 L3: ;
   }
-  
+
   @try {
 goto L4; // expected-error{{cannot jump}}
 goto L5; // expected-error{{cannot jump}}
@@ -27,8 +27,8 @@
   } @finally { // expected-note {{jump bypasses initialization of @finally block}}
   L4: ;
   }
- 
-  
+
+
   @try { // expected-note 2 {{jump bypasses initialization of @try block}}
   L7: ;
   } @catch (C *c) {
@@ -36,20 +36,19 @@
   } @finally {
 goto L7; // expected-error{{cannot jump}}
   }
-  
+
   goto L8;  // expected-error{{cannot jump}}
-  @try { 
+  @try {
   } @catch (A *c) {
   } @catch (B *c) {
   } @catch (C *c) { // expected-note {{jump bypasses initialization of @catch block}}
   L8: ;
   }
-  
+
   id X;
   goto L9;// expected-error{{cannot jump}}
-  goto L10;   // ok
-  @synchronized// expected-note {{jump bypasses initialization of @synchronized block}}
-  ( ({ L10: ; X; })) {
+  @synchronized (X)  // expected-note {{jump bypasses initialization of @synchronized block}}
+  {
   L9:
 ;
   }
@@ -88,7 +87,7 @@
 goto L0; // expected-error {{cannot jump}}
 typedef int A[n];  // expected-note {{jump bypasses initialization of VLA typedef}}
   L0:
-
+
 goto L1;  // expected-error {{cannot jump}}
 A b, c[10];// expected-note 2 {{jump bypasses initialization of variable length array}}
   L1:
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -831,8 +831,9 @@
 case 0:
   return 0;
 
-  ({
-case 1: // expected-note {{not supported}}
+  ({  // expected-note {{jump enters a statement expression}}
+case 1:// expected-error {{cannot jump from switch statement to this case label}} \
+   // expected-note  {{not supported}}
   return 1;
   });
 }
Index: clang/test/Sema/scope-check.c
===
--- clang/test/Sema/scope-check.c
+++ clang/test/Sema/scope-check.c
@@ -65,7 +65,8 @@
 
   // Statement expressions.
   goto L3;   // expected-error {{cannot jump from this goto statement to its label}}
-  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}} \
+  // expected-note {{jump enters a statement expression}}
L3: 4; });
   
   goto L4; // expected-error {{cannot jump from this goto statement to its label}}
@@ -107,25 +108,25 @@
4; })];
   L10:; // bad
   }
-  
+
   {
 // FIXME: Crashes goto checker.
 //goto L11;// ok
 //int A[({   L11: 4; })];
   }
-  
+
   {
 goto L12;
-
+
 int y = 4;   // fixme-warn: skips initializer.
   L12:
 ;
   }
-  
+
   // Statement expressions 2.
   goto L1; // expected-error {{cannot jump from this goto statement to its label}}
-  return x == ({
- int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  return x == ({ // expected-note {{jump enters a statement expression}}
+ int a[x];   // expected-note {{jump bypasses initialization of variable length array}}
L1:
  42; });
 }
@@ -231,3 +232,27 @@
 }
 
 int test16(int [sizeof &]); // expected-error {{use of address-of-label extension outside of a function body}}
+
+void GH63682() {
+  {
+goto L; // expected-error {{cannot jump from this goto statement to its label}}
+(void)sizeof (int){({ L:; 1; })}; // expected-note {{jump enters a statement expression}}
+  }
+  {
+goto M; // expected-error {{cannot jump from this goto statement to its label}}
+(void)({ M:; 1; }); 

[clang] b0cc947 - [Clang] Diagnose jumps into statement expressions

2023-07-11 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2023-07-11T21:41:14+02:00
New Revision: b0cc947b5d0a74f4ffe63c53b32978b21498e72e

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

LOG: [Clang] Diagnose jumps into statement expressions

Such jumps are not allowed by GCC and allowing them
can lead to situations where we jumps into unevaluated
statements.

Fixes #63682

Reviewed By: aaron.ballman, #clang-language-wg

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/JumpDiagnostics.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
clang/test/Sema/asm-goto.cpp
clang/test/Sema/scope-check.c
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaObjC/scope-check.m

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6a1e2fc3ea0e64..1f025097babc95 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -582,6 +582,9 @@ Bug Fixes in This Version
   (`#50243 `_),
   (`#48636 `_),
   (`#50320 `_).
+- Correcly diagnose jumps into statement expressions.
+  This ensures the behavior of Clang is consistent with GCC.
+  (`#63682 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index eea4d4961c077a..695cf9bce93e87 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6196,6 +6196,8 @@ def note_enters_block_captures_non_trivial_c_struct : 
Note<
   "to destroy">;
 def note_enters_compound_literal_scope : Note<
   "jump enters lifetime of a compound literal that is non-trivial to 
destruct">;
+def note_enters_statement_expression : Note<
+  "jump enters a statement expression">;
 
 def note_exits_cleanup : Note<
   "jump exits scope of variable with __attribute__((cleanup))">;

diff  --git a/clang/lib/Sema/JumpDiagnostics.cpp 
b/clang/lib/Sema/JumpDiagnostics.cpp
index bd2ce9a93e7e03..45e3cc2b00f0e8 100644
--- a/clang/lib/Sema/JumpDiagnostics.cpp
+++ b/clang/lib/Sema/JumpDiagnostics.cpp
@@ -477,6 +477,21 @@ void JumpScopeChecker::BuildScopeInformation(Stmt *S,
 return;
   }
 
+  case Stmt::StmtExprClass: {
+// [GNU]
+// Jumping into a statement expression with goto or using
+// a switch statement outside the statement expression with
+// a case or default label inside the statement expression is not 
permitted.
+// Jumping out of a statement expression is permitted.
+StmtExpr *SE = cast(S);
+unsigned NewParentScope = Scopes.size();
+Scopes.push_back(GotoScope(ParentScope,
+   diag::note_enters_statement_expression,
+   /*OutDiag=*/0, SE->getBeginLoc()));
+BuildScopeInformation(SE->getSubStmt(), NewParentScope);
+return;
+  }
+
   case Stmt::ObjCAtTryStmtClass: {
 // Disallow jumps into any part of an @try statement by pushing a scope and
 // walking all sub-stmts in that scope.

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 56e9c4ca133278..6cebb7e2dd540d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -16490,6 +16490,8 @@ ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 
SourceLocation LabLoc,
 
 void Sema::ActOnStartStmtExpr() {
   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
+  // Make sure we diagnose jumping into a statement expression.
+  setFunctionHasBranchProtectedScope();
 }
 
 void Sema::ActOnStmtExprError() {

diff  --git a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp 
b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
index 0c357db764a92a..55af13bfc0ef3a 100644
--- a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
+++ b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
@@ -153,7 +153,8 @@ a:  if constexpr(sizeof(n) == 4) // expected-error 
{{redefinition}} expected-not
 
   void evil_things() {
 goto evil_label; // expected-error {{cannot jump}}
-if constexpr (true || ({evil_label: false;})) {} // expected-note 
{{constexpr if}}
+if constexpr (true || ({evil_label: false;})) {} // expected-note 
{{constexpr if}} \
+ // expected-note {{jump 
enters a statement expression}}
 
 if constexpr (true) // expected-note {{constexpr if}}
   goto surprise; // expected-error {{cannot 

[PATCH] D152924: [libLTO][AIX] Respect `-f[no]-integrated-as` on AIX

2023-07-11 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added a comment.

In D152924#4490581 , @MaskRay wrote:

> We have `TargetOptions::DisableIntegratedAS` (your llc.cpp change). Do you 
> know why it is not feasible for the places you want to check?

I am checking/using `TargetOptions::DisableIntegratedAS` in 
`LTOCodeGenerator::useAIXSystemAssembler()` to determine if the system 
assembler should be used. `NoIntegratedAssembler` is moved from an `llc` only 
option to a codegen option so LTO can use it as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152924

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


[PATCH] D153536: [Clang] Implement P2169 A nice placeholder with no name

2023-07-11 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

@dblaikie Would you be willing to look at the debugger side of things in a 
subsequent patch? I'm not familiar with debug symbol code gen so I'm not sure 
I'd be able to improve thing the right way.




Comment at: clang/test/SemaCXX/cxx2c-placeholder-vars.cpp:2
+// RUN: %clang -cc1 -fsyntax-only -verify -std=c++2c -Wunused-parameter 
-Wunused %s
+
+void static_var() {

hubert.reinterpretcast wrote:
> hubert.reinterpretcast wrote:
> > hubert.reinterpretcast wrote:
> > > cor3ntin wrote:
> > > > cor3ntin wrote:
> > > > > cor3ntin wrote:
> > > > > > hubert.reinterpretcast wrote:
> > > > > > > hubert.reinterpretcast wrote:
> > > > > > > > hubert.reinterpretcast wrote:
> > > > > > > > > hubert.reinterpretcast wrote:
> > > > > > > > > > Can we have tests for:
> > > > > > > > > > ```
> > > > > > > > > > struct { int _, _; } a = { ._ = 0 };
> > > > > > > > > > ```
> > > > > > > > > > 
> > > > > > > > > > and
> > > > > > > > > > 
> > > > > > > > > > ```
> > > > > > > > > > struct A {
> > > > > > > > > >   A();
> > > > > > > > > >   int _, _;
> > > > > > > > > > };
> > > > > > > > > > 
> > > > > > > > > > A::A() : _(0) {}
> > > > > > > > > > ```
> > > > > > > > > Codegen test for
> > > > > > > > > ```
> > > > > > > > > static union { int _ = 42; };
> > > > > > > > > int  = _;
> > > > > > > > > int foo() { return 13; }
> > > > > > > > > static union { int _ = foo(); };
> > > > > > > > > int main(void) { return ref; }
> > > > > > > > > ```
> > > > > > > > > might be interesting.
> > > > > > > > > 
> > > > > > > > > I suspect that this case was missed in the committee 
> > > > > > > > > discussion of the paper @cor3ntin.
> > > > > > > > Less controversial tests to consider:
> > > > > > > > ```
> > > > > > > > struct A {
> > > > > > > >   int _;
> > > > > > > >   union { int _; };
> > > > > > > > };
> > > > > > > > struct B { union { int _, _; }; };
> > > > > > > > ```
> > > > > > > > 
> > > > > > > In a similar vein, a codegen test for:
> > > > > > > ```
> > > > > > > struct A { A(); };
> > > > > > > inline void f [[gnu::used]]() {
> > > > > > >   static union { A _{}; };
> > > > > > >   static union { A _{}; };
> > > > > > > }
> > > > > > > ```
> > > > > > > 
> > > > > > > Perhaps not intended to be allowed though (premise was no symbols 
> > > > > > > with "linkage"?)
> > > > > > What's interesting about 
> > > > > > 
> > > > > > ```
> > > > > > static union { int _ = 42; };
> > > > > > int  = _;
> > > > > > int foo() { return 13; }
> > > > > > static union { int _ = foo(); };
> > > > > > int main(void) { return ref; }
> > > > > > ```
> > > > > > ?
> > > > > > It's already supported by clang https://godbolt.org/z/6j89EdnEo
> > > > > > 
> > > > > > 
> > > > > > I'm adding the other tests (and fixing the associated bugs, of 
> > > > > > which there were a few...)
> > > > > > 
> > > > > > Perhaps not intended to be allowed though (premise was no symbols 
> > > > > > with "linkage"?)
> > > > > 
> > > > > 
> > > > > Yes, this should be ill-formed, anything where we would have to 
> > > > > mangle  multiple `_` should be ill-formed.
> > > > > I do believe that's covered though, `_` does not have storage 
> > > > > duration.
> > > > > What's interesting about 
> > > > > 
> > > > > ```
> > > > > static union { int _ = 42; };
> > > > > int  = _;
> > > > > int foo() { return 13; }
> > > > > static union { int _ = foo(); };
> > > > > int main(void) { return ref; }
> > > > > ```
> > > > > ?
> > > > > It's already supported by clang https://godbolt.org/z/6j89EdnEo
> > > > > 
> > > > > 
> > > > > I'm adding the other tests (and fixing the associated bugs, of which 
> > > > > there were a few...)
> > > > > 
> > > > 
> > > > I see it now. Thanks, I hate it. There is apparently a preexisting bug.
> > > > And yes, i think we should say something about members of anonymous 
> > > > union declared at namespace scope in the standard I realize now 
> > > > this is missing
> > > > Thanks for catching that.
> > > > Thanks for catching that.
> > > 
> > > Glad to be of help!
> > > I do believe that's covered though, `_` does not have storage duration.
> > 
> > It's not covered by the wording: `_` //is// a non-static data member.
> > 
> > 
> @cor3ntin, it seems the designated initializer case has not been added.
Thanks for noticing!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153536

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


[PATCH] D153621: [Clang] Correctly handle $, @, and ` when represented as UCN

2023-07-11 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

@tahonermann I'll probably merge that EoW unless you scream!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153621

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


[PATCH] D154884: [clang-tidy] Make MatchesAnyListedNameMatcher cope with unnamed Decl

2023-07-11 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb389a62518ad: [clang-tidy] Make MatchesAnyListedNameMatcher 
cope with unnamed Decl (authored by mikecrowe, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154884

Files:
  clang-tools-extra/clang-tidy/utils/Matchers.h
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
@@ -3,7 +3,7 @@
 // RUN: [ \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.PrintfLikeFunctions, \
-// RUN:   value: '::myprintf; mynamespace::myprintf2' \
+// RUN:   value: 'unqualified_printf;::myprintf; 
mynamespace::myprintf2' \
 // RUN:  }, \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.FprintfLikeFunctions, \
@@ -14,7 +14,7 @@
 // RUN:   -- -isystem %clang_tidy_headers
 
 #include 
-#include 
+#include 
 
 int myprintf(const char *, ...);
 int myfprintf(FILE *fp, const char *, ...);
@@ -85,3 +85,10 @@
   // CHECK-MESSAGES-NOT: [[@LINE-1]]:10: warning: use 'std::println' instead 
of 'myprintf' [modernize-use-std-print]
   // CHECK-FIXES-NOT: std::println(stderr, "return value {}", i);
 }
+
+// Ensure that MatchesAnyListedNameMatcher::NameMatcher::match() can cope with 
a
+// NamedDecl that has no name when we're trying to match unqualified_printf.
+void no_name(const std::string )
+{
+  "A" + in;
+}
Index: clang-tools-extra/clang-tidy/utils/Matchers.h
===
--- clang-tools-extra/clang-tidy/utils/Matchers.h
+++ clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -112,7 +112,9 @@
   case MatchMode::MatchFullyQualified:
 return Regex.match("::" + ND.getQualifiedNameAsString());
   default:
-return Regex.match(ND.getName());
+if (const IdentifierInfo *II = ND.getIdentifier())
+  return Regex.match(II->getName());
+return false;
   }
 }
 


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
@@ -3,7 +3,7 @@
 // RUN: [ \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.PrintfLikeFunctions, \
-// RUN:   value: '::myprintf; mynamespace::myprintf2' \
+// RUN:   value: 'unqualified_printf;::myprintf; mynamespace::myprintf2' \
 // RUN:  }, \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.FprintfLikeFunctions, \
@@ -14,7 +14,7 @@
 // RUN:   -- -isystem %clang_tidy_headers
 
 #include 
-#include 
+#include 
 
 int myprintf(const char *, ...);
 int myfprintf(FILE *fp, const char *, ...);
@@ -85,3 +85,10 @@
   // CHECK-MESSAGES-NOT: [[@LINE-1]]:10: warning: use 'std::println' instead of 'myprintf' [modernize-use-std-print]
   // CHECK-FIXES-NOT: std::println(stderr, "return value {}", i);
 }
+
+// Ensure that MatchesAnyListedNameMatcher::NameMatcher::match() can cope with a
+// NamedDecl that has no name when we're trying to match unqualified_printf.
+void no_name(const std::string )
+{
+  "A" + in;
+}
Index: clang-tools-extra/clang-tidy/utils/Matchers.h
===
--- clang-tools-extra/clang-tidy/utils/Matchers.h
+++ clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -112,7 +112,9 @@
   case MatchMode::MatchFullyQualified:
 return Regex.match("::" + ND.getQualifiedNameAsString());
   default:
-return Regex.match(ND.getName());
+if (const IdentifierInfo *II = ND.getIdentifier())
+  return Regex.match(II->getName());
+return false;
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154788: [clang-tidy] Don't split \r\n in modernize-use-std-print check

2023-07-11 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2ce765eb2f4f: [clang-tidy] Dont split \r\n in 
modernize-use-std-print check (authored by mikecrowe, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154788

Files:
  clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
  clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
  clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -44,6 +44,16 @@
   // CHECK-FIXES: std::println("Hello");
 }
 
+void printf_crlf_newline() {
+  printf("Hello\r\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 
'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\n");
+
+  printf("Hello\r\\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 
'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\\n");
+}
+
 // std::print returns nothing, so any callers that use the return
 // value cannot be automatically translated.
 int printf_uses_return_value(int choice) {
Index: clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
+++ clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
@@ -70,8 +70,10 @@
   `FprintfLikeFunctions` are replaced with the function specified by the
   `ReplacementPrintlnFunction` option if the format string ends with ``\n``
   or `ReplacementPrintFunction` otherwise.
-- the format string is rewritten to use the ``std::formatter`` language and
-  a ``\n`` is removed from the end.
+- the format string is rewritten to use the ``std::formatter`` language. If
+  a ``\n`` is found at the end of the format string not preceded by ``r``
+  then it is removed and `ReplacementPrintlnFunction` is used rather than
+  `ReplacementPrintFunction`.
 - any arguments that corresponded to ``%p`` specifiers that
   ``std::formatter`` wouldn't accept are wrapped in a ``static_cast``
   to ``const void *``.
Index: clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
===
--- clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
+++ clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
@@ -623,8 +623,11 @@
 PrintfFormatString.size() - PrintfFormatStringPos));
   PrintfFormatStringPos = PrintfFormatString.size();
 
+  // It's clearer to convert printf("Hello\r\n"); to std::print("Hello\r\n")
+  // than to std::println("Hello\r");
   if (StringRef(StandardFormatString).ends_with("\\n") &&
-  !StringRef(StandardFormatString).ends_with("n")) {
+  !StringRef(StandardFormatString).ends_with("n") &&
+  !StringRef(StandardFormatString).ends_with("\\r\\n")) {
 UsePrintNewlineFunction = true;
 FormatStringNeededRewriting = true;
 StandardFormatString.erase(StandardFormatString.end() - 2,


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -44,6 +44,16 @@
   // CHECK-FIXES: std::println("Hello");
 }
 
+void printf_crlf_newline() {
+  printf("Hello\r\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\n");
+
+  printf("Hello\r\\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\\n");
+}
+
 // std::print returns nothing, so any callers that use the return
 // value cannot be automatically translated.
 int printf_uses_return_value(int choice) {
Index: clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
+++ clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
@@ -70,8 +70,10 @@
   `FprintfLikeFunctions` are replaced with the function specified by the
   `ReplacementPrintlnFunction` option if the format string ends with ``\n``
   or `ReplacementPrintFunction` otherwise.
-- the format string is rewritten to use the ``std::formatter`` language and
-  a ``\n`` is removed from the end.
+- the format string is 

[clang-tools-extra] b389a62 - [clang-tidy] Make MatchesAnyListedNameMatcher cope with unnamed Decl

2023-07-11 Thread Piotr Zegar via cfe-commits

Author: Mike Crowe
Date: 2023-07-11T19:22:32Z
New Revision: b389a62518ad54ae5a183efa43f8408571b2b8cb

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

LOG: [clang-tidy] Make MatchesAnyListedNameMatcher cope with unnamed Decl

If MatchesAnyListedNameMatcher::NameMatcher::match() is called in
MatchMode::MatchUnqualified mode with a NamedDecl that has no name then
calling NamedDecl::getName() will assert with:
 `Name.isIdentifier() && "Name is not a simple identifier"'

It seems unfair to force all matchers using
matchers::matchesAnyListedName to defend against this, particularly
since test cases are unlikely to provoke the problem. Let's just check
whether the identifier has a name before attempting to use it instead.

Add test case that reproduces the problem to the
use-std-print-custom.cpp lit check.

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/Matchers.h

clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/Matchers.h 
b/clang-tools-extra/clang-tidy/utils/Matchers.h
index 1e085f59b69ede..b2faf788d687ad 100644
--- a/clang-tools-extra/clang-tidy/utils/Matchers.h
+++ b/clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -112,7 +112,9 @@ class MatchesAnyListedNameMatcher
   case MatchMode::MatchFullyQualified:
 return Regex.match("::" + ND.getQualifiedNameAsString());
   default:
-return Regex.match(ND.getName());
+if (const IdentifierInfo *II = ND.getIdentifier())
+  return Regex.match(II->getName());
+return false;
   }
 }
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
index a8dda40651b7b3..c6077a46b6e000 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print-custom.cpp
@@ -3,7 +3,7 @@
 // RUN: [ \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.PrintfLikeFunctions, \
-// RUN:   value: '::myprintf; mynamespace::myprintf2' \
+// RUN:   value: 'unqualified_printf;::myprintf; 
mynamespace::myprintf2' \
 // RUN:  }, \
 // RUN:  { \
 // RUN:   key: modernize-use-std-print.FprintfLikeFunctions, \
@@ -14,7 +14,7 @@
 // RUN:   -- -isystem %clang_tidy_headers
 
 #include 
-#include 
+#include 
 
 int myprintf(const char *, ...);
 int myfprintf(FILE *fp, const char *, ...);
@@ -85,3 +85,10 @@ int fprintf_uses_return_value(int i) {
   // CHECK-MESSAGES-NOT: [[@LINE-1]]:10: warning: use 'std::println' instead 
of 'myprintf' [modernize-use-std-print]
   // CHECK-FIXES-NOT: std::println(stderr, "return value {}", i);
 }
+
+// Ensure that MatchesAnyListedNameMatcher::NameMatcher::match() can cope with 
a
+// NamedDecl that has no name when we're trying to match unqualified_printf.
+void no_name(const std::string )
+{
+  "A" + in;
+}



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


[clang-tools-extra] 2ce765e - [clang-tidy] Don't split \r\n in modernize-use-std-print check

2023-07-11 Thread Piotr Zegar via cfe-commits

Author: Mike Crowe
Date: 2023-07-11T19:22:31Z
New Revision: 2ce765eb2f4feb7555d1416842c542743990b004

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

LOG: [clang-tidy] Don't split \r\n in modernize-use-std-print check

When given:
 printf("Hello\r\n");

it's clearer to leave the CRLF intact and convert this to:
 std::print("Hello\r\n");

than to remove the trailing newline and convert it to:
 std::println("Hello\r");

Update the documentation to match, and clarify the situations for using
println vs print which weren't previously explained.

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index 3e6442c5fd63c1..951e0acf79b1ae 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
@@ -623,8 +623,11 @@ void FormatStringConverter::finalizeFormatText() {
 PrintfFormatString.size() - PrintfFormatStringPos));
   PrintfFormatStringPos = PrintfFormatString.size();
 
+  // It's clearer to convert printf("Hello\r\n"); to std::print("Hello\r\n")
+  // than to std::println("Hello\r");
   if (StringRef(StandardFormatString).ends_with("\\n") &&
-  !StringRef(StandardFormatString).ends_with("n")) {
+  !StringRef(StandardFormatString).ends_with("n") &&
+  !StringRef(StandardFormatString).ends_with("\\r\\n")) {
 UsePrintNewlineFunction = true;
 FormatStringNeededRewriting = true;
 StandardFormatString.erase(StandardFormatString.end() - 2,

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst 
b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
index ec17b6fbd48f20..378caccf611bb8 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst
@@ -70,8 +70,10 @@ If the call is deemed suitable for conversion then:
   `FprintfLikeFunctions` are replaced with the function specified by the
   `ReplacementPrintlnFunction` option if the format string ends with ``\n``
   or `ReplacementPrintFunction` otherwise.
-- the format string is rewritten to use the ``std::formatter`` language and
-  a ``\n`` is removed from the end.
+- the format string is rewritten to use the ``std::formatter`` language. If
+  a ``\n`` is found at the end of the format string not preceded by ``r``
+  then it is removed and `ReplacementPrintlnFunction` is used rather than
+  `ReplacementPrintFunction`.
 - any arguments that corresponded to ``%p`` specifiers that
   ``std::formatter`` wouldn't accept are wrapped in a ``static_cast``
   to ``const void *``.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
index 4d6bcef3161ac4..321baeec7a6b09 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-print.cpp
@@ -44,6 +44,16 @@ void printf_deceptive_newline() {
   // CHECK-FIXES: std::println("Hello");
 }
 
+void printf_crlf_newline() {
+  printf("Hello\r\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 
'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\n");
+
+  printf("Hello\r\\n");
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: use 'std::print' instead of 
'printf' [modernize-use-std-print]
+  // CHECK-FIXES: std::print("Hello\r\\n");
+}
+
 // std::print returns nothing, so any callers that use the return
 // value cannot be automatically translated.
 int printf_uses_return_value(int choice) {



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


[clang] 3096226 - [RISCV] Fix name mangling for LMUL!=1 vector types with attribute(rvv_vector_bits)

2023-07-11 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2023-07-11T12:01:35-07:00
New Revision: 30962268e7a559d8714cca4d1af742915c9d29b1

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

LOG: [RISCV] Fix name mangling for LMUL!=1 vector types with 
attribute(rvv_vector_bits)

We were always printing "m1", we need to calculate the correct LMUL instead.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/AST/ItaniumMangle.cpp
clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp
clang/test/CodeGenCXX/riscv-rvv-fixedtypeinfo.cpp

Removed: 




diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 5ed76e19542857..f08286a0d4baef 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -35,6 +35,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/TargetParser/RISCVTargetParser.h"
 #include 
 
 using namespace clang;
@@ -3823,40 +3824,42 @@ void 
CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) {
   assert(EltType->isBuiltinType() &&
  "expected builtin type for fixed-length RVV vector!");
 
-  StringRef TypeName;
+  SmallString<20> TypeNameStr;
+  llvm::raw_svector_ostream TypeNameOS(TypeNameStr);
+  TypeNameOS << "__rvv_";
   switch (cast(EltType)->getKind()) {
   case BuiltinType::SChar:
-TypeName = "__rvv_int8m1_t";
+TypeNameOS << "int8";
 break;
   case BuiltinType::UChar:
-TypeName = "__rvv_uint8m1_t";
+TypeNameOS << "uint8";
 break;
   case BuiltinType::Short:
-TypeName = "__rvv_int16m1_t";
+TypeNameOS << "int16";
 break;
   case BuiltinType::UShort:
-TypeName = "__rvv_uint16m1_t";
+TypeNameOS << "uint16";
 break;
   case BuiltinType::Int:
-TypeName = "__rvv_int32m1_t";
+TypeNameOS << "int32";
 break;
   case BuiltinType::UInt:
-TypeName = "__rvv_uint32m1_t";
+TypeNameOS << "uint32";
 break;
   case BuiltinType::Long:
-TypeName = "__rvv_int64m1_t";
+TypeNameOS << "int64";
 break;
   case BuiltinType::ULong:
-TypeName = "__rvv_uint64m1_t";
+TypeNameOS << "uint64";
 break;
   case BuiltinType::Half:
-TypeName = "__rvv_float16m1_t";
+TypeNameOS << "float16";
 break;
   case BuiltinType::Float:
-TypeName = "__rvv_float32m1_t";
+TypeNameOS << "float32";
 break;
   case BuiltinType::Double:
-TypeName = "__rvv_float64m1_t";
+TypeNameOS << "float64";
 break;
   default:
 llvm_unreachable("unexpected element type for fixed-length RVV vector!");
@@ -3864,7 +3867,19 @@ void CXXNameMangler::mangleRISCVFixedRVVVectorType(const 
VectorType *T) {
 
   unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
 
-  Out << "9__RVV_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
+  // Apend the LMUL suffix.
+  auto VScale = getASTContext().getTargetInfo().getVScaleRange(
+  getASTContext().getLangOpts());
+  unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock;
+  TypeNameOS << 'm';
+  if (VecSizeInBits >= VLen)
+TypeNameOS << (VecSizeInBits / VLen);
+  else
+TypeNameOS << 'f' << (VLen / VecSizeInBits);
+
+  TypeNameOS << "_t";
+
+  Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj"
   << VecSizeInBits << "EE";
 }
 

diff  --git a/clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp 
b/clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp
index ff2f928c065f1c..98fb27b704fd81 100644
--- a/clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp
+++ b/clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp
@@ -19,6 +19,22 @@
 // RUN:  -target-feature +zve64d -mvscale-min=16 -mvscale-max=16 \
 // RUN:  | FileCheck %s --check-prefix=CHECK-1024
 
+typedef __rvv_int8mf8_t vint8mf8_t;
+typedef __rvv_uint8mf8_t vuint8mf8_t;
+
+typedef __rvv_int8mf4_t vint8mf4_t;
+typedef __rvv_uint8mf4_t vuint8mf4_t;
+typedef __rvv_int16mf4_t vint16mf4_t;
+typedef __rvv_uint16mf4_t vuint16mf4_t;
+
+typedef __rvv_int8mf2_t vint8mf2_t;
+typedef __rvv_uint8mf2_t vuint8mf2_t;
+typedef __rvv_int16mf2_t vint16mf2_t;
+typedef __rvv_uint16mf2_t vuint16mf2_t;
+typedef __rvv_int32mf2_t vint32mf2_t;
+typedef __rvv_uint32mf2_t vuint32mf2_t;
+typedef __rvv_float32mf2_t vfloat32mf2_t;
+
 typedef __rvv_int8m1_t vint8m1_t;
 typedef __rvv_uint8m1_t vuint8m1_t;
 typedef __rvv_int16m1_t vint16m1_t;
@@ -30,6 +46,59 @@ typedef __rvv_uint64m1_t vuint64m1_t;
 typedef __rvv_float32m1_t vfloat32m1_t;
 typedef __rvv_float64m1_t vfloat64m1_t;
 
+typedef __rvv_int8m2_t vint8m2_t;
+typedef __rvv_uint8m2_t vuint8m2_t;
+typedef __rvv_int16m2_t vint16m2_t;
+typedef __rvv_uint16m2_t vuint16m2_t;
+typedef __rvv_int32m2_t vint32m2_t;
+typedef 

[PATCH] D153659: [RISCV] Fix name mangling for LMUL!=1 vector types with attribute(rvv_vector_bits)

2023-07-11 Thread Craig Topper via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG30962268e7a5: [RISCV] Fix name mangling for LMUL!=1 vector 
types with attribute… (authored by craig.topper).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153659

Files:
  clang/lib/AST/ItaniumMangle.cpp
  clang/test/CodeGenCXX/riscv-mangle-rvv-fixed-vectors.cpp
  clang/test/CodeGenCXX/riscv-rvv-fixedtypeinfo.cpp

Index: clang/test/CodeGenCXX/riscv-rvv-fixedtypeinfo.cpp
===
--- clang/test/CodeGenCXX/riscv-rvv-fixedtypeinfo.cpp
+++ clang/test/CodeGenCXX/riscv-rvv-fixedtypeinfo.cpp
@@ -19,6 +19,22 @@
 // RUN:  -target-feature +zve64d -mvscale-min=16 -mvscale-max=16 \
 // RUN:  | FileCheck %s --check-prefix=CHECK-1024
 
+typedef __rvv_int8mf8_t vint8mf8_t;
+typedef __rvv_uint8mf8_t vuint8mf8_t;
+
+typedef __rvv_int8mf4_t vint8mf4_t;
+typedef __rvv_uint8mf4_t vuint8mf4_t;
+typedef __rvv_int16mf4_t vint16mf4_t;
+typedef __rvv_uint16mf4_t vuint16mf4_t;
+
+typedef __rvv_int8mf2_t vint8mf2_t;
+typedef __rvv_uint8mf2_t vuint8mf2_t;
+typedef __rvv_int16mf2_t vint16mf2_t;
+typedef __rvv_uint16mf2_t vuint16mf2_t;
+typedef __rvv_int32mf2_t vint32mf2_t;
+typedef __rvv_uint32mf2_t vuint32mf2_t;
+typedef __rvv_float32mf2_t vfloat32mf2_t;
+
 typedef __rvv_int8m1_t vint8m1_t;
 typedef __rvv_uint8m1_t vuint8m1_t;
 typedef __rvv_int16m1_t vint16m1_t;
@@ -30,6 +46,59 @@
 typedef __rvv_float32m1_t vfloat32m1_t;
 typedef __rvv_float64m1_t vfloat64m1_t;
 
+typedef __rvv_int8m2_t vint8m2_t;
+typedef __rvv_uint8m2_t vuint8m2_t;
+typedef __rvv_int16m2_t vint16m2_t;
+typedef __rvv_uint16m2_t vuint16m2_t;
+typedef __rvv_int32m2_t vint32m2_t;
+typedef __rvv_uint32m2_t vuint32m2_t;
+typedef __rvv_int64m2_t vint64m2_t;
+typedef __rvv_uint64m2_t vuint64m2_t;
+typedef __rvv_float32m2_t vfloat32m2_t;
+typedef __rvv_float64m2_t vfloat64m2_t;
+
+typedef __rvv_int8m4_t vint8m4_t;
+typedef __rvv_uint8m4_t vuint8m4_t;
+typedef __rvv_int16m4_t vint16m4_t;
+typedef __rvv_uint16m4_t vuint16m4_t;
+typedef __rvv_int32m4_t vint32m4_t;
+typedef __rvv_uint32m4_t vuint32m4_t;
+typedef __rvv_int64m4_t vint64m4_t;
+typedef __rvv_uint64m4_t vuint64m4_t;
+typedef __rvv_float32m4_t vfloat32m4_t;
+typedef __rvv_float64m4_t vfloat64m4_t;
+
+typedef __rvv_int8m8_t vint8m8_t;
+typedef __rvv_uint8m8_t vuint8m8_t;
+typedef __rvv_int16m8_t vint16m8_t;
+typedef __rvv_uint16m8_t vuint16m8_t;
+typedef __rvv_int32m8_t vint32m8_t;
+typedef __rvv_uint32m8_t vuint32m8_t;
+typedef __rvv_int64m8_t vint64m8_t;
+typedef __rvv_uint64m8_t vuint64m8_t;
+typedef __rvv_float32m8_t vfloat32m8_t;
+typedef __rvv_float64m8_t vfloat64m8_t;
+
+typedef vint8mf8_t fixed_int8mf8_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/8)));
+
+typedef vuint8mf8_t fixed_uint8mf8_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/8)));
+
+typedef vint8mf4_t fixed_int8mf4_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/4)));
+typedef vint16mf4_t fixed_int16mf4_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/4)));
+
+typedef vuint8mf4_t fixed_uint8mf4_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/4)));
+typedef vuint16mf4_t fixed_uint16mf4_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/4)));
+
+typedef vint8mf2_t fixed_int8mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+typedef vint16mf2_t fixed_int16mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+typedef vint32mf2_t fixed_int32mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+
+typedef vuint8mf2_t fixed_uint8mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+typedef vuint16mf2_t fixed_uint16mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+typedef vuint32mf2_t fixed_uint32mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+
+typedef vfloat32mf2_t fixed_float32mf2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen/2)));
+
 typedef vint8m1_t fixed_int8m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
 typedef vint16m1_t fixed_int16m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
 typedef vint32m1_t fixed_int32m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
@@ -43,6 +112,45 @@
 typedef vfloat32m1_t fixed_float32m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
 typedef vfloat64m1_t fixed_float64m1_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen)));
 
+typedef vint8m2_t fixed_int8m2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen*2)));
+typedef vint16m2_t fixed_int16m2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen*2)));
+typedef vint32m2_t fixed_int32m2_t __attribute__((riscv_rvv_vector_bits(__riscv_v_fixed_vlen*2)));
+typedef vint64m2_t fixed_int64m2_t 

[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

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

LGTM though there might be a minor typo with a test comment.




Comment at: clang/test/Sema/asm-goto.cpp:56
+  // expected-note@+1 {{jump enters a statement expression}}
+  return ({int a[n];label_true: 2;}); // expectednote
   // expected-note@+1 {{jump bypasses initialization of variable length array}}




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

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


[PATCH] D154999: [clang-tidy] Add bugprone-std-forward-type-mismatch check

2023-07-11 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Detects instances where std::forward is called with a different type as an
argument compared to the type specified as the template parameter.

Extracted from D144347 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154999

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/StdForwardTypeMismatchCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/StdForwardTypeMismatchCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/std-forward-type-mismatch.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/std-forward-type-mismatch.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/std-forward-type-mismatch.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/std-forward-type-mismatch.cpp
@@ -0,0 +1,144 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s bugprone-std-forward-type-mismatch %t -- -- -fno-delayed-template-parsing
+
+namespace std {
+
+struct false_type {
+  static constexpr bool value = false;
+};
+
+struct true_type {
+  static constexpr bool value = true;
+};
+
+template 
+struct is_lvalue_reference : false_type {};
+
+template 
+struct is_lvalue_reference : true_type {};
+
+template 
+struct remove_reference {
+  using type = T;
+};
+
+template 
+struct remove_reference {
+  using type = T;
+};
+
+template 
+struct remove_reference {
+  using type = T;
+};
+
+template 
+using remove_reference_t = typename remove_reference::type;
+
+template 
+constexpr T&& forward(typename std::remove_reference::type& t) noexcept {
+  return static_cast(t);
+}
+
+template 
+constexpr T&& forward(typename std::remove_reference::type&& t) noexcept {
+  static_assert(!std::is_lvalue_reference::value, "Can't forward an rvalue as an lvalue.");
+  return static_cast(t);
+}
+
+template 
+constexpr typename std::remove_reference::type&& move(T&& t) noexcept {
+  return static_cast::type&&>(t);
+}
+
+}
+
+struct TestType {
+  int value = 0U;
+};
+
+struct TestTypeEx : TestType {
+};
+
+template
+void test(Args&&...) {}
+
+
+template
+void testCorrectForward(T&& value) {
+  test(std::forward(value));
+}
+
+template
+void testCorrectForwardVariadicTemplate(Args&& ...args) {
+  test(std::forward(args)...);
+}
+
+void testExplicit1(TestTypeEx value) {
+  test(std::forward(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType' is not recommended here, use 'static_cast' instead
+// CHECK-FIXES: {{^  }}test(static_cast(value));{{$}}
+}
+
+void testExplicit2(TestTypeEx value) {
+  test(std::forward(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType &' is not recommended here, use 'static_cast' instead
+// CHECK-FIXES: {{^  }}test(static_cast(value));{{$}}
+}
+
+void testExplicit3(TestTypeEx value) {
+  test(std::forward(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType &&' is not recommended here, use 'static_cast' instead
+// CHECK-FIXES: {{^  }}test(static_cast(value));{{$}}
+}
+
+#define FORWARD(x,y) std::forward(y)
+#define FORWARD_FUNC std::forward
+#define TEMPLATE_ARG(x) 
+
+void testMacro(TestTypeEx value) {
+  test(FORWARD(TestType, value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType' is not recommended here, use 'static_cast' instead
+  test(FORWARD_FUNC(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType' is not recommended here, use 'static_cast' instead
+// CHECK-FIXES: {{^  }}test(static_cast(value));{{$}}
+  test(std::forward TEMPLATE_ARG(TestType)(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'TestTypeEx' to 'TestType' is not recommended here, use 'static_cast' instead
+}
+
+template
+struct Wrapper {};
+
+template
+struct WrapperEx : Wrapper {};
+
+template
+void testPartialTemplateBad(WrapperEx value) {
+  test(std::forward>(value));
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: using 'std::forward' for type conversions from 'WrapperEx' to 'Wrapper' is not recommended here, use 'static_cast' instead
+// CHECK-FIXES: {{^  }}test(static_cast &&>(value));{{$}}
+}
+
+template
+void testPartialTemplateCorrect(WrapperEx value) {
+  

[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin added inline comments.



Comment at: clang/unittests/Driver/ToolChainTest.cpp:371
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang", "-gdwarf-4", 
"-gsplit-dwarf=single", "-c", "foo.cpp"};
+  CreateInvocationOptions CIOpts;

MaskRay wrote:
> Without a concrete target triple, the default is used. If the default target 
> triple uses an object file format not supporting -gsplit-dwarf, this will 
> fail.
Oh, could you please advise how to select right target triple for the test or 
limit it to the case when triple I specify here is supported? I had issue in 
the past with triples and it was tricky to select something that makes all llvm 
bots happy. I added `-target arm-linux-gnueabi` and test seems to be working if 
only x86 arch is enabled.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

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


[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 539223.
DmitryPolukhin added a comment.

Added -target arm-linux-gnueabi


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/unittests/Driver/ToolChainTest.cpp


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,19 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang",
+ "-target",
+ "arm-linux-gnueabi",
+ "-gdwarf-4",
+ "-gsplit-dwarf=single",
+ "-c",
+ "foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;


Index: clang/unittests/Driver/ToolChainTest.cpp
===
--- clang/unittests/Driver/ToolChainTest.cpp
+++ clang/unittests/Driver/ToolChainTest.cpp
@@ -367,6 +367,19 @@
   EXPECT_TRUE(CallbackHasCalled);
 }
 
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang",
+ "-target",
+ "arm-linux-gnueabi",
+ "-gdwarf-4",
+ "-gsplit-dwarf=single",
+ "-c",
+ "foo.cpp"};
+  CreateInvocationOptions CIOpts;
+  std::unique_ptr CI = createInvocation(Args, CIOpts);
+  EXPECT_TRUE(CI); // no-crash
+}
+
 TEST(GetDriverMode, PrefersLastDriverMode) {
   static constexpr const char *Args[] = {"clang-cl", "--driver-mode=foo",
  "--driver-mode=bar", "foo.cpp"};
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1269,7 +1269,7 @@
 F += ".dwo";
   };
   if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
-if (StringRef(A->getValue()) == "single")
+if (StringRef(A->getValue()) == "single" && Output.isFilename())
   return Args.MakeArgString(Output.getFilename());
 
   SmallString<128> T;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D152996: [RISCV][POC] Model frm control for vfadd

2023-07-11 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 539222.
eopXD added a comment.

Under RISCVInsertReadWriteCSR, add implicit depdendency to MI if rounding mode 
is FRM_DYN.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152996

Files:
  clang/include/clang/Basic/riscv_vector.td
  clang/include/clang/Basic/riscv_vector_common.td
  clang/include/clang/Support/RISCVVIntrinsicUtils.h
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaRISCVVectorLookup.cpp
  clang/lib/Support/RISCVVIntrinsicUtils.cpp
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfadd.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/overloaded/vfadd.c
  clang/test/CodeGen/RISCV/rvv-intrinsics-handcrafted/vfadd-out-of-range.c
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/include/llvm/IR/IntrinsicsRISCV.td
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInsertReadWriteCSR.cpp
  llvm/lib/Target/RISCV/RISCVInstrFormats.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVSDPatterns.td
  llvm/lib/Target/RISCV/RISCVInstrInfoVVLPatterns.td
  llvm/test/CodeGen/RISCV/rvv/alloca-load-store-scalable-struct.ll
  llvm/test/CodeGen/RISCV/rvv/combine-vmv.ll
  llvm/test/CodeGen/RISCV/rvv/fixed-vectors-fmf.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tama.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tamu.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tuma.ll
  llvm/test/CodeGen/RISCV/rvv/masked-tumu.ll
  llvm/test/CodeGen/RISCV/rvv/rv32-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rv64-spill-vector-csr.ll
  llvm/test/CodeGen/RISCV/rvv/rvv-peephole-vmerge-masked-vops.ll
  llvm/test/CodeGen/RISCV/rvv/unmasked-tu.ll
  llvm/test/CodeGen/RISCV/rvv/vfadd.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert-crossbb.ll
  llvm/test/CodeGen/RISCV/rvv/vsetvli-insert.ll

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


[PATCH] D154915: [ARM][AArch64] Add ARM specific builtin for clz that is not undefined for 0 in ubsan.

2023-07-11 Thread Craig Topper via Phabricator via cfe-commits
craig.topper updated this revision to Diff 539221.
craig.topper added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154915

Files:
  clang/include/clang/Basic/BuiltinsAArch64.def
  clang/include/clang/Basic/BuiltinsARM.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/arm_acle.h


Index: clang/lib/Headers/arm_acle.h
===
--- clang/lib/Headers/arm_acle.h
+++ clang/lib/Headers/arm_acle.h
@@ -140,17 +140,21 @@
 /* CLZ */
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clz(uint32_t __t) {
-  return (unsigned int)__builtin_clz(__t);
+  return __builtin_arm_clz(__t);
 }
 
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzl(unsigned long __t) {
-  return (unsigned int)__builtin_clzl(__t);
+#if __SIZEOF_LONG__ == 4
+  return __builtin_arm_clz(__t);
+#else
+  return __builtin_arm_clz64(__t);
+#endif
 }
 
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzll(uint64_t __t) {
-  return (unsigned int)__builtin_clzll(__t);
+  return __builtin_arm_clz64(__t);
 }
 
 /* CLS */
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -7906,6 +7906,17 @@
 CGM.getIntrinsic(Intrinsic::bitreverse, Arg->getType()), Arg, "rbit");
   }
 
+  if (BuiltinID == clang::ARM::BI__builtin_arm_clz ||
+  BuiltinID == clang::ARM::BI__builtin_arm_clz64) {
+llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
+Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Arg->getType());
+Value *Res = Builder.CreateCall(F, {Arg, Builder.getInt1(false)});
+if (BuiltinID == clang::ARM::BI__builtin_arm_clz64)
+  Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
+return Res;
+  }
+
+
   if (BuiltinID == clang::ARM::BI__builtin_arm_cls) {
 llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
 return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_cls), Arg, 
"cls");
@@ -9988,6 +,16 @@
 CGM.getIntrinsic(Intrinsic::bitreverse, Arg->getType()), Arg, "rbit");
   }
 
+  if (BuiltinID == clang::AArch64::BI__builtin_arm_clz ||
+  BuiltinID == clang::AArch64::BI__builtin_arm_clz64) {
+llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
+Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Arg->getType());
+Value *Res = Builder.CreateCall(F, {Arg, Builder.getInt1(false)});
+if (BuiltinID == clang::AArch64::BI__builtin_arm_clz64)
+  Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
+return Res;
+  }
+
   if (BuiltinID == clang::AArch64::BI__builtin_arm_cls) {
 llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
 return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_cls), Arg,
Index: clang/include/clang/Basic/BuiltinsARM.def
===
--- clang/include/clang/Basic/BuiltinsARM.def
+++ clang/include/clang/Basic/BuiltinsARM.def
@@ -119,6 +119,8 @@
 
 // Bit manipulation
 BUILTIN(__builtin_arm_rbit, "UiUi", "nc")
+BUILTIN(__builtin_arm_clz, "UiZUi", "nc")
+BUILTIN(__builtin_arm_clz64, "UiWUi", "nc")
 BUILTIN(__builtin_arm_cls, "UiZUi", "nc")
 BUILTIN(__builtin_arm_cls64, "UiWUi", "nc")
 
Index: clang/include/clang/Basic/BuiltinsAArch64.def
===
--- clang/include/clang/Basic/BuiltinsAArch64.def
+++ clang/include/clang/Basic/BuiltinsAArch64.def
@@ -39,6 +39,8 @@
 BUILTIN(__builtin_arm_rbit64, "WUiWUi", "nc")
 BUILTIN(__builtin_arm_cls, "UiZUi", "nc")
 BUILTIN(__builtin_arm_cls64, "UiWUi", "nc")
+BUILTIN(__builtin_arm_clz, "UiZUi", "nc")
+BUILTIN(__builtin_arm_clz64, "UiWUi", "nc")
 
 // HINT
 BUILTIN(__builtin_arm_nop, "v", "")


Index: clang/lib/Headers/arm_acle.h
===
--- clang/lib/Headers/arm_acle.h
+++ clang/lib/Headers/arm_acle.h
@@ -140,17 +140,21 @@
 /* CLZ */
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clz(uint32_t __t) {
-  return (unsigned int)__builtin_clz(__t);
+  return __builtin_arm_clz(__t);
 }
 
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzl(unsigned long __t) {
-  return (unsigned int)__builtin_clzl(__t);
+#if __SIZEOF_LONG__ == 4
+  return __builtin_arm_clz(__t);
+#else
+  return __builtin_arm_clz64(__t);
+#endif
 }
 
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzll(uint64_t __t) {
-  return (unsigned int)__builtin_clzll(__t);
+  return __builtin_arm_clz64(__t);
 }
 
 /* CLS */
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -7906,6 

[PATCH] D148381: [WIP][Clang] Add element_count attribute

2023-07-11 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 539219.
void added a comment.

Rebasing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148381

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/ASTImporter.cpp
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test

Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -62,6 +62,7 @@
 // CHECK-NEXT: DiagnoseAsBuiltin (SubjectMatchRule_function)
 // CHECK-NEXT: DisableSanitizerInstrumentation (SubjectMatchRule_function, SubjectMatchRule_objc_method, SubjectMatchRule_variable_is_global)
 // CHECK-NEXT: DisableTailCalls (SubjectMatchRule_function, SubjectMatchRule_objc_method)
+// CHECK-NEXT: ElementCount (SubjectMatchRule_field)
 // CHECK-NEXT: EnableIf (SubjectMatchRule_function)
 // CHECK-NEXT: EnforceTCB (SubjectMatchRule_function, SubjectMatchRule_objc_method)
 // CHECK-NEXT: EnforceTCBLeaf (SubjectMatchRule_function, SubjectMatchRule_objc_method)
Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -8349,6 +8349,29 @@
   D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL));
 }
 
+static void handleElementCountAttr(Sema , Decl *D, const ParsedAttr ) {
+  // TODO: Probably needs more processing here. See Sema::AddAlignValueAttr.
+  SmallVector Names;
+  SmallVector Ranges;
+
+  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
+StringRef Field;
+SourceLocation FieldLoc;
+
+if (!S.checkStringLiteralArgumentAttr(AL, I, Field, ))
+  return;
+
+Names.push_back(Field);
+Ranges.push_back(FieldLoc);
+  }
+
+  ElementCountAttr *ECA = ::new (S.Context) ElementCountAttr(S.Context, AL,
+ Names.data(),
+ Names.size());
+  ECA->addCountFieldSourceRange(Ranges);
+  D->addAttr(ECA);
+}
+
 static void handleFunctionReturnThunksAttr(Sema , Decl *D,
const ParsedAttr ) {
   StringRef KindStr;
@@ -9273,6 +9296,10 @@
 handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
 break;
 
+  case ParsedAttr::AT_ElementCount:
+handleElementCountAttr(S, D, AL);
+break;
+
   // Microsoft attributes:
   case ParsedAttr::AT_LayoutVersion:
 handleLayoutVersion(S, D, AL);
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -17786,6 +17786,44 @@
  "Broken injected-class-name");
 }
 
+static const FieldDecl *FindFieldWithElementCountAttr(const RecordDecl *RD) {
+  for (const Decl *D : RD->decls()) {
+if (const auto *FD = dyn_cast(D))
+  if (FD->hasAttr())
+return FD;
+
+if (const auto *SubRD = dyn_cast(D))
+  if (const FieldDecl *FD = FindFieldWithElementCountAttr(SubRD))
+return FD;
+  }
+
+  return nullptr;
+}
+
+static StringRef
+CheckElementCountAttr(const RecordDecl *RD, const FieldDecl *FD,
+  SourceRange ) {
+  const ElementCountAttr *ECA = FD->getAttr();
+  unsigned Idx = 0;
+
+  for (StringRef Field : ECA->elementCountFields()) {
+Loc = ECA->getCountFieldSourceRange(Idx++);
+
+auto DeclIter = llvm::find_if(
+RD->fields(), [&](const FieldDecl *FD){
+  return Field == FD->getName();
+});
+
+if (DeclIter == RD->field_end())
+  return Field;
+
+if (auto *SubRD = DeclIter->getType()->getAsRecordDecl())
+  RD = SubRD;
+  }
+
+  return StringRef();
+}
+
 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
 SourceRange BraceRange) {
   AdjustDeclIfTemplate(TagD);
@@ -17843,6 +17881,19 @@
  [](const FieldDecl *FD) { return FD->isBitField(); }))
   Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
   }
+
+  // Check the "element_count" attribute to ensure that the count field exists
+  // in the struct.
+  if (const RecordDecl *RD = dyn_cast(Tag)) {
+if (const FieldDecl *FD = FindFieldWithElementCountAttr(RD)) {
+  SourceRange SR;
+  StringRef Unknown = CheckElementCountAttr(RD, FD, SR);
+
+  if (!Unknown.empty())
+Diag(SR.getBegin(), diag::warn_element_count_placeholder)
+<< Unknown << SR;
+}
+  }
 }
 
 void Sema::ActOnObjCContainerFinishDefinition() {
Index: 

[PATCH] D154784: [clang] Fix crash caused by PseudoObjectExprBitfields::NumSubExprs overflow

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

LGTM, thank you for the fix!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154784

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


[PATCH] D152924: [libLTO][AIX] Respect `-f[no]-integrated-as` on AIX

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

We have `TargetOptions::DisableIntegratedAS` (your llc.cpp change). Do you know 
why it is not feasible for the places you want to check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152924

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


[PATCH] D154186: [clang][DeclPrinter] Fix AST print of delegating constructors

2023-07-11 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/AST/ast-print-method-decl.cpp:15
+  // CHECK-NEXT: };
+};

strimo378 wrote:
> aaron.ballman wrote:
> > I'd also like to see test cases along the lines of:
> > ```
> > struct B {
> >   template 
> >   B(Ty);
> >   B(int X) : B((float)X) {}
> > };
> > 
> > struct C {
> >   C(auto);
> >   C(int) : C("") {}
> > };
> > ```
> I fully agree to you that these test cases should also work but that goes 
> beyond the scope of a "simple" delegating ctor output fix.
> 
> In the current implementation all implicitly specialized templates are output 
> and therefore the generated code is not correct C++ anymore, see 
> https://godbolt.org/z/34xaoYW5n . I think it is not a good idea to check for 
> incorrect C++ code in a test case...
> 
> I am currently focusing to get non-templated C++ code output correctly. For 
> methods e.g. there are many problems with the correct position of attributes. 
> I will address that in one of my next merge request and I want to put all 
> method related tests into ast-print-method-decl.cpp . Therefore, I would like 
> to keep the name.
> I fully agree to you that these test cases should also work but that goes 
> beyond the scope of a "simple" delegating ctor output fix.

Ah, so this is exposing an already existing issue. In that case, let's add the 
tests and leave a FIXME comment to improve the behavior in the future (bonus 
points for filing an issue) so that it's clear we've noticed there's a problem 
rather than looking like an oversight in test coverage. This also ensures that 
those forms of delegation don't cause assertions or crashes despite being wrong.

> I am currently focusing to get non-templated C++ code output correctly. For 
> methods e.g. there are many problems with the correct position of attributes. 
> I will address that in one of my next merge request and I want to put all 
> method related tests into ast-print-method-decl.cpp . Therefore, I would like 
> to keep the name.

Ah, if there's more functionality to be added to the test in the near future, 
the current name is fine by me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154186

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


[PATCH] D152924: [libLTO][AIX] Respect `-f[no]-integrated-as` on AIX

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/lto-aix.c:76
 // CSPGO: "-bplugin_opt:-cs-profile-generate" 
"-bplugin_opt:-cs-profile-path=default_%m.profraw"
+//
+// Test integrated assembler options

This `^//$` line is not useful. Some tests use this style, but it's not a good 
style.

If we remove this line, we can actually use Vim `{` `}` navigate among tests.



Comment at: clang/test/Driver/lto-aix.c:79
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fno-integrated-as \
+// RUN:  -fintegrated-as 2>&1 | FileCheck --check-prefix=INTAS %s
+// RUN: %clang --target=powerpc-ibm-aix -### %s -flto -fintegrated-as \

2-space indentation



Comment at: llvm/test/tools/llvm-lto/aix-sys-as.ll:12
+; CHECK: Wrote native object file
+

delete trailing blank line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152924

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


[PATCH] D154991: [FPEnv][TableGen] Add strictfp attribute to constrained intrinsics by default.

2023-07-11 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm accepted this revision.
arsenm added inline comments.
This revision is now accepted and ready to land.



Comment at: llvm/include/llvm/IR/Intrinsics.td:1102
 
-let IntrProperties = [IntrInaccessibleMemOnly, IntrWillReturn] in {
+/// IntrStrictFP - The intrinsic is allowed to be used in an alternate
+/// floating point environment.

Eventually I think it would be better if we had some sort of fpenv access 
property, such that we'll know which set of target intrinsics need handling and 
which aspects of the fpenv


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

https://reviews.llvm.org/D154991

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


[PATCH] D154359: [clang] Reset FP options before template instantiation

2023-07-11 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:5093
+FpPragmaStack.CurrentValue = FPOptionsOverride();
+
 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,

This seems to be fixing the crash. 



Comment at: clang/test/CodeGen/fp-template.cpp:28
+// CHECK-LABEL: define {{.*}} float @_ZN7PR6354211stable_sortIiEEffT_(
+// CHECK: fadd float
+

Shouldn't we be expecting a constraint add here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154359

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


[clang] 06611e3 - [clang] Implement `PointerLikeTraits` for `{File,Directory}EntryRef`

2023-07-11 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-07-11T11:17:24-07:00
New Revision: 06611e361363a4c209aaccd0ee24652d2c56cafb

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

LOG: [clang] Implement `PointerLikeTraits` for `{File,Directory}EntryRef`

This patch implements `llvm::PointerLikeTraits` and 
`llvm::PointerLikeTraits`, allowing some simplifications 
around umbrella header/directory code.

Reviewed By: benlangmuir

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

Added: 


Modified: 
clang/include/clang/Basic/DirectoryEntry.h
clang/include/clang/Basic/FileEntry.h
clang/include/clang/Basic/Module.h
clang/lib/Basic/Module.cpp
clang/lib/Lex/ModuleMap.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DirectoryEntry.h 
b/clang/include/clang/Basic/DirectoryEntry.h
index 6580e54e3c58b8..5d083e68facd7a 100644
--- a/clang/include/clang/Basic/DirectoryEntry.h
+++ b/clang/include/clang/Basic/DirectoryEntry.h
@@ -72,7 +72,7 @@ class DirectoryEntryRef {
   bool isSameRef(DirectoryEntryRef RHS) const { return ME == RHS.ME; }
 
   DirectoryEntryRef() = delete;
-  DirectoryEntryRef(const MapEntry ) : ME() {}
+  explicit DirectoryEntryRef(const MapEntry ) : ME() {}
 
   /// Allow DirectoryEntryRef to degrade into 'const DirectoryEntry*' to
   /// facilitate incremental adoption.
@@ -197,6 +197,21 @@ 
static_assert(std::is_trivially_copyable::value,
 } // namespace clang
 
 namespace llvm {
+
+template <> struct PointerLikeTypeTraits {
+  static inline void *getAsVoidPointer(clang::DirectoryEntryRef Dir) {
+return const_cast(());
+  }
+
+  static inline clang::DirectoryEntryRef getFromVoidPointer(void *Ptr) {
+return clang::DirectoryEntryRef(
+*reinterpret_cast(Ptr));
+  }
+
+  static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<
+  const clang::DirectoryEntryRef::MapEntry *>::NumLowBitsAvailable;
+};
+
 /// Specialisation of DenseMapInfo for DirectoryEntryRef.
 template <> struct DenseMapInfo {
   static inline clang::DirectoryEntryRef getEmptyKey() {

diff  --git a/clang/include/clang/Basic/FileEntry.h 
b/clang/include/clang/Basic/FileEntry.h
index fdeafe5348cd08..50110b8572ef48 100644
--- a/clang/include/clang/Basic/FileEntry.h
+++ b/clang/include/clang/Basic/FileEntry.h
@@ -234,6 +234,21 @@ 
static_assert(std::is_trivially_copyable::value,
 } // namespace clang
 
 namespace llvm {
+
+template <> struct PointerLikeTypeTraits {
+  static inline void *getAsVoidPointer(clang::FileEntryRef File) {
+return const_cast(());
+  }
+
+  static inline clang::FileEntryRef getFromVoidPointer(void *Ptr) {
+return clang::FileEntryRef(
+*reinterpret_cast(Ptr));
+  }
+
+  static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<
+  const clang::FileEntryRef::MapEntry *>::NumLowBitsAvailable;
+};
+
 /// Specialisation of DenseMapInfo for FileEntryRef.
 template <> struct DenseMapInfo {
   static inline clang::FileEntryRef getEmptyKey() {

diff  --git a/clang/include/clang/Basic/Module.h 
b/clang/include/clang/Basic/Module.h
index b3b53761601071..a4ad8ad2f768fe 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -156,9 +156,7 @@ class alignas(8) Module {
   std::string PresumedModuleMapFile;
 
   /// The umbrella header or directory.
-  llvm::PointerUnion
-  Umbrella;
+  llvm::PointerUnion Umbrella;
 
   /// The module signature.
   ASTFileSignature Signature;
@@ -650,19 +648,18 @@ class alignas(8) Module {
 
   /// Retrieve the umbrella directory as written.
   std::optional getUmbrellaDirAsWritten() const {
-if (const auto *ME =
-Umbrella.dyn_cast())
+if (Umbrella && Umbrella.is())
   return DirectoryName{UmbrellaAsWritten,
UmbrellaRelativeToRootModuleDirectory,
-   DirectoryEntryRef(*ME)};
+   Umbrella.get()};
 return std::nullopt;
   }
 
   /// Retrieve the umbrella header as written.
   std::optional getUmbrellaHeaderAsWritten() const {
-if (const auto *ME = Umbrella.dyn_cast())
+if (Umbrella && Umbrella.is())
   return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
-FileEntryRef(*ME)};
+Umbrella.get()};
 return std::nullopt;
   }
 

diff  --git a/clang/lib/Basic/Module.cpp b/clang/lib/Basic/Module.cpp
index 2bdbe8d2b110d7..8ec68237a0fc08 100644
--- a/clang/lib/Basic/Module.cpp
+++ b/clang/lib/Basic/Module.cpp
@@ -264,10 +264,10 @@ bool Module::fullModuleNameIs(ArrayRef 
nameParts) const {
 }
 
 OptionalDirectoryEntryRef Module::getEffectiveUmbrellaDir() const {
-  if (const auto *ME = Umbrella.dyn_cast())
-return FileEntryRef(*ME).getDir();
-  if (const auto *ME = Umbrella.dyn_cast())
-return 

[PATCH] D154905: [clang] Implement `PointerLikeTraits` for `{File,Directory}EntryRef`

2023-07-11 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
jansvoboda11 marked an inline comment as done.
Closed by commit rG06611e361363: [clang] Implement `PointerLikeTraits` for 
`{File,Directory}EntryRef` (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154905

Files:
  clang/include/clang/Basic/DirectoryEntry.h
  clang/include/clang/Basic/FileEntry.h
  clang/include/clang/Basic/Module.h
  clang/lib/Basic/Module.cpp
  clang/lib/Lex/ModuleMap.cpp

Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1162,7 +1162,7 @@
 Module *Mod, FileEntryRef UmbrellaHeader, const Twine ,
 const Twine ) {
   Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
-  Mod->Umbrella = ();
+  Mod->Umbrella = UmbrellaHeader;
   Mod->UmbrellaAsWritten = NameAsWritten.str();
   Mod->UmbrellaRelativeToRootModuleDirectory =
   PathRelativeToRootModuleDirectory.str();
@@ -1176,7 +1176,7 @@
 void ModuleMap::setUmbrellaDirAsWritten(
 Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine ,
 const Twine ) {
-  Mod->Umbrella = ();
+  Mod->Umbrella = UmbrellaDir;
   Mod->UmbrellaAsWritten = NameAsWritten.str();
   Mod->UmbrellaRelativeToRootModuleDirectory =
   PathRelativeToRootModuleDirectory.str();
Index: clang/lib/Basic/Module.cpp
===
--- clang/lib/Basic/Module.cpp
+++ clang/lib/Basic/Module.cpp
@@ -264,10 +264,10 @@
 }
 
 OptionalDirectoryEntryRef Module::getEffectiveUmbrellaDir() const {
-  if (const auto *ME = Umbrella.dyn_cast())
-return FileEntryRef(*ME).getDir();
-  if (const auto *ME = Umbrella.dyn_cast())
-return DirectoryEntryRef(*ME);
+  if (Umbrella && Umbrella.is())
+return Umbrella.get().getDir();
+  if (Umbrella && Umbrella.is())
+return Umbrella.get();
   return std::nullopt;
 }
 
Index: clang/include/clang/Basic/Module.h
===
--- clang/include/clang/Basic/Module.h
+++ clang/include/clang/Basic/Module.h
@@ -156,9 +156,7 @@
   std::string PresumedModuleMapFile;
 
   /// The umbrella header or directory.
-  llvm::PointerUnion
-  Umbrella;
+  llvm::PointerUnion Umbrella;
 
   /// The module signature.
   ASTFileSignature Signature;
@@ -650,19 +648,18 @@
 
   /// Retrieve the umbrella directory as written.
   std::optional getUmbrellaDirAsWritten() const {
-if (const auto *ME =
-Umbrella.dyn_cast())
+if (Umbrella && Umbrella.is())
   return DirectoryName{UmbrellaAsWritten,
UmbrellaRelativeToRootModuleDirectory,
-   DirectoryEntryRef(*ME)};
+   Umbrella.get()};
 return std::nullopt;
   }
 
   /// Retrieve the umbrella header as written.
   std::optional getUmbrellaHeaderAsWritten() const {
-if (const auto *ME = Umbrella.dyn_cast())
+if (Umbrella && Umbrella.is())
   return Header{UmbrellaAsWritten, UmbrellaRelativeToRootModuleDirectory,
-FileEntryRef(*ME)};
+Umbrella.get()};
 return std::nullopt;
   }
 
Index: clang/include/clang/Basic/FileEntry.h
===
--- clang/include/clang/Basic/FileEntry.h
+++ clang/include/clang/Basic/FileEntry.h
@@ -234,6 +234,21 @@
 } // namespace clang
 
 namespace llvm {
+
+template <> struct PointerLikeTypeTraits {
+  static inline void *getAsVoidPointer(clang::FileEntryRef File) {
+return const_cast(());
+  }
+
+  static inline clang::FileEntryRef getFromVoidPointer(void *Ptr) {
+return clang::FileEntryRef(
+*reinterpret_cast(Ptr));
+  }
+
+  static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<
+  const clang::FileEntryRef::MapEntry *>::NumLowBitsAvailable;
+};
+
 /// Specialisation of DenseMapInfo for FileEntryRef.
 template <> struct DenseMapInfo {
   static inline clang::FileEntryRef getEmptyKey() {
Index: clang/include/clang/Basic/DirectoryEntry.h
===
--- clang/include/clang/Basic/DirectoryEntry.h
+++ clang/include/clang/Basic/DirectoryEntry.h
@@ -72,7 +72,7 @@
   bool isSameRef(DirectoryEntryRef RHS) const { return ME == RHS.ME; }
 
   DirectoryEntryRef() = delete;
-  DirectoryEntryRef(const MapEntry ) : ME() {}
+  explicit DirectoryEntryRef(const MapEntry ) : ME() {}
 
   /// Allow DirectoryEntryRef to degrade into 'const DirectoryEntry*' to
   /// facilitate incremental adoption.
@@ -197,6 +197,21 @@
 } // namespace clang
 
 namespace llvm {
+
+template <> struct PointerLikeTypeTraits {
+  static inline void *getAsVoidPointer(clang::DirectoryEntryRef Dir) {
+return const_cast(());
+  }
+
+  

[PATCH] D154991: [FPEnv][TableGen] Add strictfp attribute to constrained intrinsics by default.

2023-07-11 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn updated this revision to Diff 539204.
kpn added a comment.

Move test and change to round-tripping as requested.


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

https://reviews.llvm.org/D154991

Files:
  clang/test/CodeGenOpenCL/cl20-device-side-enqueue-attributes.cl
  llvm/include/llvm/IR/Intrinsics.td
  llvm/test/Assembler/fp-intrinsics-attr.ll
  llvm/test/Verifier/fp-intrinsics-pass.ll
  llvm/utils/TableGen/CodeGenIntrinsics.cpp
  llvm/utils/TableGen/CodeGenIntrinsics.h
  llvm/utils/TableGen/IntrinsicEmitter.cpp

Index: llvm/utils/TableGen/IntrinsicEmitter.cpp
===
--- llvm/utils/TableGen/IntrinsicEmitter.cpp
+++ llvm/utils/TableGen/IntrinsicEmitter.cpp
@@ -388,6 +388,9 @@
   if (L->hasSideEffects != R->hasSideEffects)
 return R->hasSideEffects;
 
+  if (L->isStrictFP != R->isStrictFP)
+return R->isStrictFP;
+
   // Try to order by readonly/readnone attribute.
   uint32_t LK = L->ME.toIntValue();
   uint32_t RK = R->ME.toIntValue();
@@ -522,6 +525,8 @@
   OS << "  Attribute::get(C, Attribute::Convergent),\n";
 if (Intrinsic.isSpeculatable)
   OS << "  Attribute::get(C, Attribute::Speculatable),\n";
+if (Intrinsic.isStrictFP)
+  OS << "  Attribute::get(C, Attribute::StrictFP),\n";
 
 MemoryEffects ME = Intrinsic.ME;
 // TODO: IntrHasSideEffects should affect not only readnone intrinsics.
@@ -594,7 +599,8 @@
 Intrinsic.isNoReturn || Intrinsic.isNoCallback || Intrinsic.isNoSync ||
 Intrinsic.isNoFree || Intrinsic.isWillReturn || Intrinsic.isCold ||
 Intrinsic.isNoDuplicate || Intrinsic.isNoMerge ||
-Intrinsic.isConvergent || Intrinsic.isSpeculatable) {
+Intrinsic.isConvergent || Intrinsic.isSpeculatable ||
+Intrinsic.isStrictFP) {
   unsigned ID = UniqFnAttributes.find()->second;
   OS << "  AS[" << numAttrs++ << "] = {AttributeList::FunctionIndex, "
  << "getIntrinsicFnAttributeSet(C, " << ID << ")};\n";
Index: llvm/utils/TableGen/CodeGenIntrinsics.h
===
--- llvm/utils/TableGen/CodeGenIntrinsics.h
+++ llvm/utils/TableGen/CodeGenIntrinsics.h
@@ -103,6 +103,9 @@
   // True if the intrinsic is marked as speculatable.
   bool isSpeculatable;
 
+  // True if the intrinsic is marked as strictfp.
+  bool isStrictFP;
+
   enum ArgAttrKind {
 NoCapture,
 NoAlias,
Index: llvm/utils/TableGen/CodeGenIntrinsics.cpp
===
--- llvm/utils/TableGen/CodeGenIntrinsics.cpp
+++ llvm/utils/TableGen/CodeGenIntrinsics.cpp
@@ -74,6 +74,7 @@
   isConvergent = false;
   isSpeculatable = false;
   hasSideEffects = false;
+  isStrictFP = false;
 
   if (DefName.size() <= 4 || DefName.substr(0, 4) != "int_")
 PrintFatalError(DefLoc,
@@ -203,6 +204,8 @@
 isSpeculatable = true;
   else if (R->getName() == "IntrHasSideEffects")
 hasSideEffects = true;
+  else if (R->getName() == "IntrStrictFP")
+isStrictFP = true;
   else if (R->isSubClassOf("NoCapture")) {
 unsigned ArgNo = R->getValueAsInt("ArgNo");
 addArgAttribute(ArgNo, NoCapture);
Index: llvm/test/Verifier/fp-intrinsics-pass.ll
===
--- llvm/test/Verifier/fp-intrinsics-pass.ll
+++ llvm/test/Verifier/fp-intrinsics-pass.ll
@@ -1,7 +1,7 @@
 ; RUN: opt -passes=verify -S < %s 2>&1 | FileCheck %s
 
-declare double @llvm.experimental.constrained.fadd.f64(double, double, metadata, metadata) #0
-declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata) #0
+declare double @llvm.experimental.constrained.fadd.f64(double, double, metadata, metadata)
+declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata)
 
 ; Test that the verifier accepts legal code, and that the correct attributes are
 ; attached to the FP intrinsic. The attributes are checked at the bottom.
@@ -9,35 +9,34 @@
 ; CHECK: declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata) #[[ATTR]]
 ; Note: FP exceptions aren't usually caught through normal unwind mechanisms,
 ;   but we may want to revisit this for asynchronous exception handling.
-define double @f1(double %a, double %b) #0 {
+define double @f1(double %a, double %b) strictfp {
 ; CHECK-LABEL: define double @f1
-; CHECK-SAME: (double [[A:%.*]], double [[B:%.*]]) #[[ATTR1:[0-9]+]] {
+; CHECK-SAME: (double [[A:%.*]], double [[B:%.*]]) #[[STRICTFP:[0-9]+]] {
 ; CHECK-NEXT:  entry:
-; CHECK-NEXT:[[FADD:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[A]], double [[B]], metadata !"round.dynamic", metadata !"fpexcept.strict") #[[ATTR1]]
+; CHECK-NEXT:[[FADD:%.*]] = call double @llvm.experimental.constrained.fadd.f64(double [[A]], double [[B]], metadata !"round.dynamic", metadata !"fpexcept.strict")
 ; CHECK-NEXT:ret double [[FADD]]
 entry:
   %fadd 

[PATCH] D154983: [clang-extdef-mapping] register necessary targest for ms-style asm block

2023-07-11 Thread Tobias Hieta via Phabricator via cfe-commits
thieta accepted this revision.
thieta added a comment.
This revision is now accepted and ready to land.

Looks fine to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154983

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


[PATCH] D154991: [FPEnv][TableGen] Add strictfp attribute to constrained intrinsics by default.

2023-07-11 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: llvm/test/Feature/fp-intrinsics-attr.ll:1
+; RUN: opt -passes=verify -S < %s | FileCheck %s
+

Should move to test/Assembler and round trip through llvm-as and llvm-dis like 
other similar tests 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154991

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


[PATCH] D154991: [FPEnv][TableGen] Add strictfp attribute to constrained intrinsics by default.

2023-07-11 Thread Kevin P. Neal via Phabricator via cfe-commits
kpn created this revision.
kpn added reviewers: pengfei, chapuni, akshaykhadse, craig.topper, arsenm.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
kpn requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, wdng.
Herald added projects: clang, LLVM.

In D146869  @arsenm pointed out that the 
constrained intrinsics aren't getting the strictfp attribute by default. They 
should be, since they are required to have it anyway.

TableGen did not know about this attribute until now. This patch adds strictfp 
to TableGen, and it uses it on all of the constrained intrinsics.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D154991

Files:
  clang/test/CodeGenOpenCL/cl20-device-side-enqueue-attributes.cl
  llvm/include/llvm/IR/Intrinsics.td
  llvm/test/Feature/fp-intrinsics-attr.ll
  llvm/test/Verifier/fp-intrinsics-pass.ll
  llvm/utils/TableGen/CodeGenIntrinsics.cpp
  llvm/utils/TableGen/CodeGenIntrinsics.h
  llvm/utils/TableGen/IntrinsicEmitter.cpp

Index: llvm/utils/TableGen/IntrinsicEmitter.cpp
===
--- llvm/utils/TableGen/IntrinsicEmitter.cpp
+++ llvm/utils/TableGen/IntrinsicEmitter.cpp
@@ -388,6 +388,9 @@
   if (L->hasSideEffects != R->hasSideEffects)
 return R->hasSideEffects;
 
+  if (L->isStrictFP != R->isStrictFP)
+return R->isStrictFP;
+
   // Try to order by readonly/readnone attribute.
   uint32_t LK = L->ME.toIntValue();
   uint32_t RK = R->ME.toIntValue();
@@ -522,6 +525,8 @@
   OS << "  Attribute::get(C, Attribute::Convergent),\n";
 if (Intrinsic.isSpeculatable)
   OS << "  Attribute::get(C, Attribute::Speculatable),\n";
+if (Intrinsic.isStrictFP)
+  OS << "  Attribute::get(C, Attribute::StrictFP),\n";
 
 MemoryEffects ME = Intrinsic.ME;
 // TODO: IntrHasSideEffects should affect not only readnone intrinsics.
@@ -594,7 +599,8 @@
 Intrinsic.isNoReturn || Intrinsic.isNoCallback || Intrinsic.isNoSync ||
 Intrinsic.isNoFree || Intrinsic.isWillReturn || Intrinsic.isCold ||
 Intrinsic.isNoDuplicate || Intrinsic.isNoMerge ||
-Intrinsic.isConvergent || Intrinsic.isSpeculatable) {
+Intrinsic.isConvergent || Intrinsic.isSpeculatable ||
+Intrinsic.isStrictFP) {
   unsigned ID = UniqFnAttributes.find()->second;
   OS << "  AS[" << numAttrs++ << "] = {AttributeList::FunctionIndex, "
  << "getIntrinsicFnAttributeSet(C, " << ID << ")};\n";
Index: llvm/utils/TableGen/CodeGenIntrinsics.h
===
--- llvm/utils/TableGen/CodeGenIntrinsics.h
+++ llvm/utils/TableGen/CodeGenIntrinsics.h
@@ -103,6 +103,9 @@
   // True if the intrinsic is marked as speculatable.
   bool isSpeculatable;
 
+  // True if the intrinsic is marked as strictfp.
+  bool isStrictFP;
+
   enum ArgAttrKind {
 NoCapture,
 NoAlias,
Index: llvm/utils/TableGen/CodeGenIntrinsics.cpp
===
--- llvm/utils/TableGen/CodeGenIntrinsics.cpp
+++ llvm/utils/TableGen/CodeGenIntrinsics.cpp
@@ -74,6 +74,7 @@
   isConvergent = false;
   isSpeculatable = false;
   hasSideEffects = false;
+  isStrictFP = false;
 
   if (DefName.size() <= 4 || DefName.substr(0, 4) != "int_")
 PrintFatalError(DefLoc,
@@ -203,6 +204,8 @@
 isSpeculatable = true;
   else if (R->getName() == "IntrHasSideEffects")
 hasSideEffects = true;
+  else if (R->getName() == "IntrStrictFP")
+isStrictFP = true;
   else if (R->isSubClassOf("NoCapture")) {
 unsigned ArgNo = R->getValueAsInt("ArgNo");
 addArgAttribute(ArgNo, NoCapture);
Index: llvm/test/Verifier/fp-intrinsics-pass.ll
===
--- llvm/test/Verifier/fp-intrinsics-pass.ll
+++ llvm/test/Verifier/fp-intrinsics-pass.ll
@@ -1,7 +1,7 @@
 ; RUN: opt -passes=verify -S < %s 2>&1 | FileCheck %s
 
-declare double @llvm.experimental.constrained.fadd.f64(double, double, metadata, metadata) #0
-declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata) #0
+declare double @llvm.experimental.constrained.fadd.f64(double, double, metadata, metadata)
+declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata)
 
 ; Test that the verifier accepts legal code, and that the correct attributes are
 ; attached to the FP intrinsic. The attributes are checked at the bottom.
@@ -9,35 +9,34 @@
 ; CHECK: declare double @llvm.experimental.constrained.sqrt.f64(double, metadata, metadata) #[[ATTR]]
 ; Note: FP exceptions aren't usually caught through normal unwind mechanisms,
 ;   but we may want to revisit this for asynchronous exception handling.
-define double @f1(double %a, double %b) #0 {
+define double @f1(double %a, double %b) strictfp {
 ; CHECK-LABEL: define double @f1
-; CHECK-SAME: (double [[A:%.*]], double [[B:%.*]]) 

[PATCH] D154658: Optimize emission of `dynamic_cast` to final classes.

2023-07-11 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

In D154658#4482202 , @rsmith wrote:

> In D154658#4481225 , @rjmccall 
> wrote:
>
>> In D154658#4479213 , @rsmith wrote:
>>
>>> I think (hope?) we should be able to apply this to a much larger set of 
>>> cases. Would it be correct to do this optimization unless the vtable might 
>>> be emitted with vague linkage and non-default visibility (that is, unless 
>>> we're in the odd case where people expect non-default visibility classes to 
>>> be the same type across DSOs)? Or are there cases where we might be using a 
>>> vtable that (eg) doesn't even have the right symbol?
>>
>> I don't know of any problems other than the total failure of vague linkage 
>> across DSO boundaries, so if we just treat that as an implicit exception to 
>> the vtable uniqueness guarantee in the ABI, I think you've got the condition 
>> exactly right: we could do this for any class where either the v-table 
>> doesn't have vague linkage or the class's formal visibility is not 
>> `default`.  Our experience at Apple with enforcing type visibility is that 
>> it's usually good for one or two bug reports a year, but it's pretty easy to 
>> explain to users what they did wrong, and Clang's visibility attributes are 
>> pretty simple to use.  (`type_visibility` helps a lot with managing 
>> tradeoffs.)
>
> I did some checking through the Clang implementation and found another two 
> cases:
>
> - under `-fapple-kext`, vague-linkage vtables get emitted in each translation 
> unit that references them
> - under `-fno-rtti`, identical vtables for distinct types could get merged 
> because we emit vtables as `unnamed_addr` (this doesn't affect 
> `dynamic_cast`, because `-fno-rtti` also disables `dynamic_cast` entirely)
>
> The good news seems to be that if you don't use any language extensions (type 
> visibility, `-fno-rtti`, `-fapple-kext`), then we do actually provide the 
> guarantee that the ABI describes. :)
>
> In D154658#4479170 , @rjmccall 
> wrote:
>
>> If there are multiple subobjects of the source type in the destination type, 
>> consider just casting to `void*` first instead of doing multiple comparisons.
>
> This turned out to be a little subtle: the vptr comparison we do after the 
> cast requires loading a vptr of an object of entirely-unknown type. This is 
> the first time we're doing that in IR generation, and `GetVTablePtr` expected 
> to be told which class it's loading the vtable for (presumably, so that it 
> can load from the right offset within the class). However, the implementation 
> of `GetVTablePtr` didn't use the class for anything; it's always at the start 
> for all of our supported ABIs. But this patch would make it harder to support 
> an ABI that didn't put the vptr at the start of the most-derived object.

Oh, this does matter on platforms using pointer authentication, because each 
vptr field is signed with a constant discriminator derived from the name of the 
class that introduced it.




Comment at: clang/lib/CodeGen/ItaniumCXXABI.cpp:204
+// another type.
+if (!CGM.GetAddrOfRTTIDescriptor(RecordTy))
+  return false;

Is there no reasonable way of checking this without actually triggering the 
emission of RTTI?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154658

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


[PATCH] D152554: [OpenMP] Migrate device code privatisation from Clang CodeGen to OMPIRBuilder

2023-07-11 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152554

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


[PATCH] D150803: [WebAssembly] Support `annotate` clang attributes for marking functions.

2023-07-11 Thread Brendan Dahl via Phabricator via cfe-commits
brendandahl updated this revision to Diff 539191.
brendandahl added a comment.

Rebase on main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150803

Files:
  lld/test/wasm/func-attr-tombstone.s
  lld/test/wasm/func-attr.s
  lld/test/wasm/merge-func-attr-section.s
  lld/wasm/InputChunks.cpp
  lld/wasm/InputFiles.cpp
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/BinaryFormat/WasmRelocs.def
  llvm/include/llvm/MC/MCExpr.h
  llvm/lib/MC/MCExpr.cpp
  llvm/lib/MC/WasmObjectWriter.cpp
  llvm/lib/Object/WasmObjectFile.cpp
  llvm/lib/Target/WebAssembly/MCTargetDesc/WebAssemblyWasmObjectWriter.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
  llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
  llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
  llvm/test/MC/WebAssembly/func-attr.s

Index: llvm/test/MC/WebAssembly/func-attr.s
===
--- /dev/null
+++ llvm/test/MC/WebAssembly/func-attr.s
@@ -0,0 +1,21 @@
+# RUN: llvm-mc -triple=wasm32-unknown-unknown < %s | FileCheck %s
+# Check that it also comiled to object for format.
+# RUN: llvm-mc -triple=wasm32-unknown-unknown -filetype=obj -o - < %s | obj2yaml | FileCheck -check-prefix=CHECK-OBJ %s
+
+foo:
+.globl foo
+.functype foo () -> ()
+end_function
+
+.section.custom_section.llvm.func_attr.custom0,"",@
+.int32  foo@FUNCINDEX
+
+# CHECK:   .section .custom_section.llvm.func_attr.custom0,"",@
+# CHECK-NEXT: .int32  foo@FUNCINDEX
+
+# CHECK-OBJ:- Type:CUSTOM
+# CHECK-OBJ-NEXT: Relocations:
+# CHECK-OBJ-NEXT:- Type:R_WASM_FUNCTION_INDEX_I32
+# CHECK-OBJ-NEXT:  Index:   0
+# CHECK-OBJ-NEXT:  Offset:  0x0
+# CHECK-OBJ-NEXT: Name:llvm.func_attr.custom0
Index: llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
===
--- /dev/null
+++ llvm/test/CodeGen/WebAssembly/func-attr-annotate.ll
@@ -0,0 +1,31 @@
+; RUN: llc < %s -asm-verbose=false -wasm-keep-registers | FileCheck %s
+
+target triple = "wasm32-unknown-unknown"
+
+@.str = private unnamed_addr constant [8 x i8] c"custom0\00", section "llvm.metadata"
+@.str.1 = private unnamed_addr constant [7 x i8] c"main.c\00", section "llvm.metadata"
+@.str.2 = private unnamed_addr constant [8 x i8] c"custom1\00", section "llvm.metadata"
+@.str.3 = private unnamed_addr constant [8 x i8] c"custom2\00", section "llvm.metadata"
+@llvm.global.annotations = appending global [3 x { ptr, ptr, ptr, i32, ptr }] [{ ptr, ptr, ptr, i32, ptr } { ptr @test0, ptr @.str, ptr @.str.1, i32 4, ptr null }, { ptr, ptr, ptr, i32, ptr } { ptr @test1, ptr @.str, ptr @.str.1, i32 5, ptr null }, { ptr, ptr, ptr, i32, ptr } { ptr @test2, ptr @.str.2, ptr @.str.1, i32 6, ptr null }], section "llvm.metadata"
+
+define void @test0() {
+  ret void
+}
+
+define void @test1() {
+  ret void
+}
+
+define void @test2() {
+  ret void
+}
+
+define void @test3() {
+  ret void
+}
+
+; CHECK:  .section.custom_section.llvm.func_attr.annotate.custom0,"",@
+; CHECK-NEXT: .int32  test0@FUNCINDEX
+; CHECK-NEXT: .int32  test1@FUNCINDEX
+; CHECK:  .section.custom_section.llvm.func_attr.annotate.custom1,"",@
+; CHECK-NEXT: .int32  test2@FUNCINDEX
Index: llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
===
--- llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
+++ llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.h
@@ -66,6 +66,7 @@
   void emitEndOfAsmFile(Module ) override;
   void EmitProducerInfo(Module );
   void EmitTargetFeatures(Module );
+  void EmitFunctionAttributes(Module );
   void emitSymbolType(const MCSymbolWasm *Sym);
   void emitGlobalVariable(const GlobalVariable *GV) override;
   void emitJumpTableInfo() override;
Index: llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
===
--- llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
+++ llvm/lib/Target/WebAssembly/WebAssemblyAsmPrinter.cpp
@@ -27,6 +27,8 @@
 #include "WebAssemblyTargetMachine.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/BinaryFormat/Wasm.h"
 #include "llvm/CodeGen/Analysis.h"
 #include "llvm/CodeGen/AsmPrinter.h"
@@ -438,6 +440,7 @@
 
   EmitProducerInfo(M);
   EmitTargetFeatures(M);
+  EmitFunctionAttributes(M);
 }
 
 void WebAssemblyAsmPrinter::EmitProducerInfo(Module ) {
@@ -556,6 +559,49 @@
   OutStreamer->popSection();
 }
 
+void WebAssemblyAsmPrinter::EmitFunctionAttributes(Module ) {
+  auto V = M.getNamedGlobal("llvm.global.annotations");
+  if (!V)
+return;
+
+  // Group all the custom attributes by name.
+  StringMap> CustomSections;
+  const ConstantArray *CA = 

[PATCH] D154910: [ARM][AArch64] Make ACLE __clzl/__clzll return unsigned int instead of unsigned long/uint64_t.

2023-07-11 Thread Craig Topper via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2df12f30551e: [ARM][AArch64] Make ACLE __clzl/__clzll return 
unsigned int instead of unsigned… (authored by craig.topper).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154910

Files:
  clang/lib/Headers/arm_acle.h
  clang/test/CodeGen/arm_acle.c


Index: clang/test/CodeGen/arm_acle.c
===
--- clang/test/CodeGen/arm_acle.c
+++ clang/test/CodeGen/arm_acle.c
@@ -332,7 +332,7 @@
 // ARM-NEXT:[[TMP0:%.*]] = call i32 @llvm.ctlz.i32(i32 [[T:%.*]], i1 false)
 // ARM-NEXT:ret i32 [[TMP0]]
 //
-uint32_t test_clz(uint32_t t) {
+unsigned test_clz(uint32_t t) {
   return __clz(t);
 }
 
@@ -345,10 +345,9 @@
 // AArch64-NEXT:  entry:
 // AArch64-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 
false)
 // AArch64-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// AArch64-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// AArch64-NEXT:ret i64 [[CONV_I]]
+// AArch64-NEXT:ret i32 [[CAST_I]]
 //
-long test_clzl(long t) {
+unsigned test_clzl(unsigned long t) {
   return __clzl(t);
 }
 
@@ -356,10 +355,9 @@
 // ARM-NEXT:  entry:
 // ARM-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 false)
 // ARM-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// ARM-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// ARM-NEXT:ret i64 [[CONV_I]]
+// ARM-NEXT:ret i32 [[CAST_I]]
 //
-uint64_t test_clzll(uint64_t t) {
+unsigned test_clzll(uint64_t t) {
   return __clzll(t);
 }
 
Index: clang/lib/Headers/arm_acle.h
===
--- clang/lib/Headers/arm_acle.h
+++ clang/lib/Headers/arm_acle.h
@@ -138,28 +138,28 @@
 
 
 /* CLZ */
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clz(uint32_t __t) {
-  return (uint32_t)__builtin_clz(__t);
+  return (unsigned int)__builtin_clz(__t);
 }
 
-static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzl(unsigned long __t) {
-  return (unsigned long)__builtin_clzl(__t);
+  return (unsigned int)__builtin_clzl(__t);
 }
 
-static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzll(uint64_t __t) {
-  return (uint64_t)__builtin_clzll(__t);
+  return (unsigned int)__builtin_clzll(__t);
 }
 
 /* CLS */
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __cls(uint32_t __t) {
   return __builtin_arm_cls(__t);
 }
 
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clsl(unsigned long __t) {
 #if __SIZEOF_LONG__ == 4
   return __builtin_arm_cls(__t);
@@ -168,7 +168,7 @@
 #endif
 }
 
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clsll(uint64_t __t) {
   return __builtin_arm_cls64(__t);
 }


Index: clang/test/CodeGen/arm_acle.c
===
--- clang/test/CodeGen/arm_acle.c
+++ clang/test/CodeGen/arm_acle.c
@@ -332,7 +332,7 @@
 // ARM-NEXT:[[TMP0:%.*]] = call i32 @llvm.ctlz.i32(i32 [[T:%.*]], i1 false)
 // ARM-NEXT:ret i32 [[TMP0]]
 //
-uint32_t test_clz(uint32_t t) {
+unsigned test_clz(uint32_t t) {
   return __clz(t);
 }
 
@@ -345,10 +345,9 @@
 // AArch64-NEXT:  entry:
 // AArch64-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 false)
 // AArch64-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// AArch64-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// AArch64-NEXT:ret i64 [[CONV_I]]
+// AArch64-NEXT:ret i32 [[CAST_I]]
 //
-long test_clzl(long t) {
+unsigned test_clzl(unsigned long t) {
   return __clzl(t);
 }
 
@@ -356,10 +355,9 @@
 // ARM-NEXT:  entry:
 // ARM-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 false)
 // ARM-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// ARM-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// ARM-NEXT:ret i64 [[CONV_I]]
+// ARM-NEXT:ret i32 [[CAST_I]]
 //
-uint64_t test_clzll(uint64_t t) {
+unsigned test_clzll(uint64_t t) {
   return __clzll(t);
 }
 
Index: clang/lib/Headers/arm_acle.h
===
--- clang/lib/Headers/arm_acle.h
+++ clang/lib/Headers/arm_acle.h
@@ -138,28 +138,28 @@
 
 
 /* CLZ */
-static __inline__ 

[clang] 2df12f3 - [ARM][AArch64] Make ACLE __clzl/__clzll return unsigned int instead of unsigned long/uint64_t.

2023-07-11 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2023-07-11T10:42:25-07:00
New Revision: 2df12f30551e0cb9ecfd49a0cacf929e785c15da

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

LOG: [ARM][AArch64] Make ACLE __clzl/__clzll return unsigned int instead of 
unsigned long/uint64_t.

Use unsigned long in place of uint32_t for both clz and cls.

As far as I can tell this matches what ACLE defines and what gcc implements.

Noticed while investigating fixing 
https://github.com/llvm/llvm-project/issues/63113

Reviewed By: tmatheson

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

Added: 


Modified: 
clang/lib/Headers/arm_acle.h
clang/test/CodeGen/arm_acle.c

Removed: 




diff  --git a/clang/lib/Headers/arm_acle.h b/clang/lib/Headers/arm_acle.h
index e086f1f02dad0c..382487f1283e4d 100644
--- a/clang/lib/Headers/arm_acle.h
+++ b/clang/lib/Headers/arm_acle.h
@@ -138,28 +138,28 @@ __rorl(unsigned long __x, uint32_t __y) {
 
 
 /* CLZ */
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clz(uint32_t __t) {
-  return (uint32_t)__builtin_clz(__t);
+  return (unsigned int)__builtin_clz(__t);
 }
 
-static __inline__ unsigned long __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzl(unsigned long __t) {
-  return (unsigned long)__builtin_clzl(__t);
+  return (unsigned int)__builtin_clzl(__t);
 }
 
-static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clzll(uint64_t __t) {
-  return (uint64_t)__builtin_clzll(__t);
+  return (unsigned int)__builtin_clzll(__t);
 }
 
 /* CLS */
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __cls(uint32_t __t) {
   return __builtin_arm_cls(__t);
 }
 
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clsl(unsigned long __t) {
 #if __SIZEOF_LONG__ == 4
   return __builtin_arm_cls(__t);
@@ -168,7 +168,7 @@ __clsl(unsigned long __t) {
 #endif
 }
 
-static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__))
 __clsll(uint64_t __t) {
   return __builtin_arm_cls64(__t);
 }

diff  --git a/clang/test/CodeGen/arm_acle.c b/clang/test/CodeGen/arm_acle.c
index f21bc5c1c5b0e9..b1105a1d5aabb6 100644
--- a/clang/test/CodeGen/arm_acle.c
+++ b/clang/test/CodeGen/arm_acle.c
@@ -332,7 +332,7 @@ uint64_t test_rorll(uint64_t x, uint32_t y) {
 // ARM-NEXT:[[TMP0:%.*]] = call i32 @llvm.ctlz.i32(i32 [[T:%.*]], i1 false)
 // ARM-NEXT:ret i32 [[TMP0]]
 //
-uint32_t test_clz(uint32_t t) {
+unsigned test_clz(uint32_t t) {
   return __clz(t);
 }
 
@@ -345,10 +345,9 @@ uint32_t test_clz(uint32_t t) {
 // AArch64-NEXT:  entry:
 // AArch64-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 
false)
 // AArch64-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// AArch64-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// AArch64-NEXT:ret i64 [[CONV_I]]
+// AArch64-NEXT:ret i32 [[CAST_I]]
 //
-long test_clzl(long t) {
+unsigned test_clzl(unsigned long t) {
   return __clzl(t);
 }
 
@@ -356,10 +355,9 @@ long test_clzl(long t) {
 // ARM-NEXT:  entry:
 // ARM-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[T:%.*]], i1 false)
 // ARM-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
-// ARM-NEXT:[[CONV_I:%.*]] = sext i32 [[CAST_I]] to i64
-// ARM-NEXT:ret i64 [[CONV_I]]
+// ARM-NEXT:ret i32 [[CAST_I]]
 //
-uint64_t test_clzll(uint64_t t) {
+unsigned test_clzll(uint64_t t) {
   return __clzll(t);
 }
 



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


[PATCH] D153920: [clang] Move the clang formatting job to run-buildbot to fix the CI

2023-07-11 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik updated this revision to Diff 539183.
philnik added a comment.
Herald added a reviewer: NoQ.

Try to fix CI


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153920

Files:
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/utils/ci/buildkite-pipeline.yml
  clang/utils/ci/run-buildbot
  libcxx/utils/ci/buildkite-pipeline-clang.yml
  libcxx/utils/ci/generate-buildkite-pipeline

Index: libcxx/utils/ci/generate-buildkite-pipeline
===
--- libcxx/utils/ci/generate-buildkite-pipeline
+++ libcxx/utils/ci/generate-buildkite-pipeline
@@ -11,16 +11,4 @@
 # This script generates the appropriate libc++ CI pipeline based on which project(s) were changed.
 #
 
-if git diff --name-only HEAD~1 | grep -q -E "^libcxx/|^libcxxabi/|^libunwind/|^runtimes/|^cmake/"; then
-  LIBCXX_CHANGED=true
-fi
-
-if git diff --name-only HEAD~1 | grep -q -E "^clang/"; then
-  CLANG_CHANGED=true
-fi
-
-if [[ "${CLANG_CHANGED}" == "true" && "${LIBCXX_CHANGED}" != "true" ]]; then
-  cat libcxx/utils/ci/buildkite-pipeline-clang.yml
-else
-  cat libcxx/utils/ci/buildkite-pipeline.yml
-fi
+cat clang/utils/ci/buildkite-pipeline.yml
Index: clang/utils/ci/run-buildbot
===
--- /dev/null
+++ clang/utils/ci/run-buildbot
@@ -0,0 +1,128 @@
+#!/usr/bin/env bash
+#===--===##
+#
+# 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
+#
+#===--===##
+
+set -ex
+set -o pipefail
+unset LANG
+unset LC_ALL
+unset LC_COLLATE
+
+PROGNAME="$(basename "${0}")"
+
+function usage() {
+cat <
+
+[-h|--help] Display this help and exit.
+
+--llvm-rootPath to the root of the LLVM monorepo. By default, we try
+to figure it out based on the current working directory.
+
+--build-dirThe directory to use for building the library. By default,
+this is '/build/'.
+EOF
+}
+
+if [[ $# == 0 ]]; then
+   usage
+   exit 0
+fi
+
+while [[ $# -gt 0 ]]; do
+case ${1} in
+-h|--help)
+usage
+exit 0
+;;
+--llvm-root)
+MONOREPO_ROOT="${2}"
+shift; shift
+;;
+--build-dir)
+BUILD_DIR="${2}"
+shift; shift
+;;
+*)
+BUILDER="${1}"
+shift
+;;
+esac
+done
+
+MONOREPO_ROOT="${MONOREPO_ROOT:="$(git rev-parse --show-toplevel)"}"
+BUILD_DIR="${BUILD_DIR:=${MONOREPO_ROOT}/build/${BUILDER}}"
+INSTALL_DIR="${BUILD_DIR}/install"
+
+# Print the version of a few tools to aid diagnostics in some cases
+cmake --version
+ninja --version
+
+case "${BUILDER}" in
+check-format)
+! grep -rnI '[[:blank:]]$' clang/lib clang/include clang/docs
+;;
+build-clang)
+mkdir install
+# We use Release here to avoid including debug information. Otherwise, the
+# clang binary is very large, which is problematic because we need to upload
+# the artifacts for other jobs to use. This may seem like nothing, but with
+# the number of jobs we run daily, this can result in thousands of GB of
+# network I/O.
+cmake  \
+-S llvm\
+-B build   \
+-G Ninja   \
+-DCMAKE_CXX_COMPILER_LAUNCHER="ccache" \
+-DCMAKE_BUILD_TYPE=Release \
+-DCMAKE_INSTALL_PREFIX=install \
+-DLLVM_ENABLE_PROJECTS="clang;compiler-rt" \
+
+ninja -C build install-clang install-clang-resource-headers
+ccache -s
+tar -cJvf install.tar.xz install/
+buildkite-agent artifact upload --debug install.tar.xz
+;;
+generic-cxx03)
+buildkite-agent artifact download install.tar.xz .
+tar -xvf install.tar.xz
+export CC=$(pwd)/install/bin/clang
+export CXX=$(pwd)/install/bin/clang++
+chmod +x install/bin/clang install/bin/clang++
+libcxx/utils/ci/run-buildbot generic-cxx03
+;;
+generic-cxx26)
+buildkite-agent artifact download install.tar.xz .
+tar -xvf install.tar.xz
+export CC=$(pwd)/install/bin/clang
+export CXX=$(pwd)/install/bin/clang++
+chmod +x install/bin/clang install/bin/clang++
+libcxx/utils/ci/run-buildbot generic-cxx26
+;;
+generic-modules)
+buildkite-agent artifact download 

[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/unittests/Driver/ToolChainTest.cpp:371
+TEST(CompilerInvocation, SplitSwarfSingleCrash) {
+  static constexpr const char *Args[] = {"clang", "-gdwarf-4", 
"-gsplit-dwarf=single", "-c", "foo.cpp"};
+  CreateInvocationOptions CIOpts;

Without a concrete target triple, the default is used. If the default target 
triple uses an object file format not supporting -gsplit-dwarf, this will fail.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

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


[PATCH] D154602: [clang][clangd] Don't crash/assert on -gsplit-dwarf=single without output

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

https://maskray.me/blog/2021-08-08-toolchain-testing#the-test-checks-at-the-wrong-layer
 I think there is a minor "The test checks too little" issue as we can utilize 
the test to check a few more properties, but I am fine with this.
And I may try improving the test at spare time..


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154602

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


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-11 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

The code change looks good but the driver test will cause an issue.
I think we need a fake sysroot tree under `Inputs/`.
Otherwise if we have a system cross gcc at 
`/usr/lib/gcc{,-cross}/powerpc64le-unknown-eabi/12`, Clang Driver will pick up 
these files.
This is really difficult to debug for someone not so familiar with Driver (I 
think I have done quite a lot of work, but still quite puzzled).
You may check many other tests using --sysroot, remove --sysroot, and check the 
behavior change.


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

https://reviews.llvm.org/D154357

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


[PATCH] D152021: [clang][AIX] Fix Overly Strict LTO Option Checking against `data-sections` when `mxcoff-roptr` is in Effect

2023-07-11 Thread Qiongsi Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0b66b3417c02: [clang][AIX] Fix Overly Strict LTO Option 
Checking against `data-sections` when… (authored by qiongsiwu1).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152021

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/test/Driver/ppc-roptr.c


Index: clang/test/Driver/ppc-roptr.c
===
--- clang/test/Driver/ppc-roptr.c
+++ clang/test/Driver/ppc-roptr.c
@@ -12,7 +12,7 @@
 // RUN: %clang -### --target=powerpc-ibm-aix-xcoff %s 2>&1 | \
 // RUN: FileCheck %s --check-prefix=NO_ROPTR
 // RUN: %clang -### --target=powerpc64-ibm-aix-xcoff -mxcoff-roptr -flto %s 
2>&1 | \
-// RUN: FileCheck %s --check-prefixes=ROPTR,LINK,LTO_ROPTR
+// RUN: FileCheck %s 
--check-prefixes=NO_DATA_SECTION_ERR,ROPTR,LINK,LTO_ROPTR
 // RUN: touch %t.o
 // RUN: %clang -### --target=powerpc64-ibm-aix-xcoff -mxcoff-roptr %t.o 2>&1 | 
\
 // RUN: FileCheck %s --check-prefix=LINK
@@ -33,14 +33,14 @@
 // RUN: %clang -### --target=powerpc64le-unknown-linux-gnu -mno-xcoff-roptr 
-flto \
 // RUN: %t.o 2>&1 | FileCheck %s --check-prefix=TARGET_NOROPTR_ERR
 
-// ROPTR: "-mxcoff-roptr"
-// LINK: "-bforceimprw"
-// LTO_ROPTR: "-bplugin_opt:-mxcoff-roptr"
-// NO_ROPTR-NOT: "-mxcoff-roptr"
-// NO_ROPTR-NOT: "-bforceimprw"
-
 // DATA_SECTION_ERR: error: -mxcoff-roptr is supported only with 
-fdata-sections
 // NO_DATA_SECTION_ERR-NOT: error: -mxcoff-roptr is supported only with 
-fdata-sections
 // TARGET_ROPTR_ERR: error: unsupported option '-mxcoff-roptr' for target 
'powerpc64le-unknown-linux-gnu'
 // TARGET_NOROPTR_ERR: error: unsupported option '-mno-xcoff-roptr' for target 
'powerpc64le-unknown-linux-gnu'
 // SHARED_ERR: error: -mxcoff-roptr is not supported with -shared
+
+// ROPTR: "-mxcoff-roptr"
+// LINK: "-bforceimprw"
+// LTO_ROPTR: "-bplugin_opt:-mxcoff-roptr"
+// NO_ROPTR-NOT: "-mxcoff-roptr"
+// NO_ROPTR-NOT: "-bforceimprw"
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -725,13 +725,16 @@
 CmdArgs.push_back(
 Args.MakeArgString(Twine(PluginOptPrefix) + "-function-sections=0"));
 
+  bool DataSectionsTurnedOff = false;
   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
-   UseSeparateSections))
+   UseSeparateSections)) {
 CmdArgs.push_back(
 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=1"));
-  else if (Args.hasArg(options::OPT_fno_data_sections))
+  } else if (Args.hasArg(options::OPT_fno_data_sections)) {
+DataSectionsTurnedOff = true;
 CmdArgs.push_back(
 Args.MakeArgString(Twine(PluginOptPrefix) + "-data-sections=0"));
+  }
 
   if (Args.hasArg(options::OPT_mxcoff_roptr) ||
   Args.hasArg(options::OPT_mno_xcoff_roptr)) {
@@ -744,8 +747,10 @@
   << OptStr << ToolChain.getTriple().str();
 
 if (HasRoptr) {
-  if (!Args.hasFlag(options::OPT_fdata_sections,
-options::OPT_fno_data_sections, UseSeparateSections))
+  // The data sections option is on by default on AIX. We only need to 
error
+  // out when -fno-data-sections is specified explicitly to turn off data
+  // sections.
+  if (DataSectionsTurnedOff)
 D.Diag(diag::err_roptr_requires_data_sections);
 
   CmdArgs.push_back(


Index: clang/test/Driver/ppc-roptr.c
===
--- clang/test/Driver/ppc-roptr.c
+++ clang/test/Driver/ppc-roptr.c
@@ -12,7 +12,7 @@
 // RUN: %clang -### --target=powerpc-ibm-aix-xcoff %s 2>&1 | \
 // RUN: FileCheck %s --check-prefix=NO_ROPTR
 // RUN: %clang -### --target=powerpc64-ibm-aix-xcoff -mxcoff-roptr -flto %s 2>&1 | \
-// RUN: FileCheck %s --check-prefixes=ROPTR,LINK,LTO_ROPTR
+// RUN: FileCheck %s --check-prefixes=NO_DATA_SECTION_ERR,ROPTR,LINK,LTO_ROPTR
 // RUN: touch %t.o
 // RUN: %clang -### --target=powerpc64-ibm-aix-xcoff -mxcoff-roptr %t.o 2>&1 | \
 // RUN: FileCheck %s --check-prefix=LINK
@@ -33,14 +33,14 @@
 // RUN: %clang -### --target=powerpc64le-unknown-linux-gnu -mno-xcoff-roptr -flto \
 // RUN: %t.o 2>&1 | FileCheck %s --check-prefix=TARGET_NOROPTR_ERR
 
-// ROPTR: "-mxcoff-roptr"
-// LINK: "-bforceimprw"
-// LTO_ROPTR: "-bplugin_opt:-mxcoff-roptr"
-// NO_ROPTR-NOT: "-mxcoff-roptr"
-// NO_ROPTR-NOT: "-bforceimprw"
-
 // DATA_SECTION_ERR: error: -mxcoff-roptr is supported only with -fdata-sections
 // NO_DATA_SECTION_ERR-NOT: error: -mxcoff-roptr is supported only with -fdata-sections
 // TARGET_ROPTR_ERR: error: unsupported option '-mxcoff-roptr' for target 

  1   2   3   >