[PATCH] D139713: [Sema] Fix crash when evaluating nested call with value-dependent arg

2023-01-05 Thread Pierre van Houtryve 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 rGd6acd0196b33: [Sema] Fix crash when evaluating nested call 
with value-dependent arg (authored by Pierre-vh).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139713

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp


Index: clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -fsyntax-only %s -std=c++14
+
+// Checks that Clang doesn't crash/assert on the nested call to "kaboom"
+// in "bar()".
+//
+// This is an interesting test case for `ExprConstant.cpp`'s `CallStackFrame`
+// because it triggers the following chain of events:
+// 0. `CheckEnableIf` calls `EvaluateWithSubstitution`.
+//  1. The outer call to "kaboom" gets evaluated.
+//   2. The expr for "a" gets evaluated, it has a version X;
+//  a temporary with the key (a, X) is created.
+// 3. The inner call to "kaboom" gets evaluated.
+//   4. The expr for "a" gets evaluated, it has a version Y;
+//  a temporary with the key (a, Y) is created.
+//   5. The expr for "b" gets evaluated, it has a version Y;
+//  a temporary with the key (b, Y) is created.
+//   6. `EvaluateWithSubstitution` looks at "b" but cannot evaluate it
+//  because it's value-dependent (due to the call to "f.foo()").
+//
+// When `EvaluateWithSubstitution` bails out while evaluating the outer
+// call, it attempts to fetch "b"'s param slot to clean it up.
+//
+// This used to cause an assertion failure in `getTemporary` because
+// a temporary with the key "(b, Y)" (created at step 4) existed but
+// not one for "(b, X)", which is what it was trying to fetch.
+
+template
+__attribute__((enable_if(true, "")))
+T kaboom(T a, T b) {
+  return b;
+}
+
+struct A {
+  double foo();
+};
+
+template 
+struct B {
+  A &f;
+
+  void bar() {
+kaboom(kaboom(0.0, 1.0), f.foo());
+  }
+};
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -594,11 +594,6 @@
   auto LB = Temporaries.lower_bound(KV);
   if (LB != Temporaries.end() && LB->first == KV)
 return &LB->second;
-  // Pair (Key,Version) wasn't found in the map. Check that no elements
-  // in the map have 'Key' as their key.
-  assert((LB == Temporaries.end() || LB->first.first != Key) &&
- (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) 
&&
- "Element with key 'Key' found in map");
   return nullptr;
 }
 


Index: clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -fsyntax-only %s -std=c++14
+
+// Checks that Clang doesn't crash/assert on the nested call to "kaboom"
+// in "bar()".
+//
+// This is an interesting test case for `ExprConstant.cpp`'s `CallStackFrame`
+// because it triggers the following chain of events:
+// 0. `CheckEnableIf` calls `EvaluateWithSubstitution`.
+//  1. The outer call to "kaboom" gets evaluated.
+//   2. The expr for "a" gets evaluated, it has a version X;
+//  a temporary with the key (a, X) is created.
+// 3. The inner call to "kaboom" gets evaluated.
+//   4. The expr for "a" gets evaluated, it has a version Y;
+//  a temporary with the key (a, Y) is created.
+//   5. The expr for "b" gets evaluated, it has a version Y;
+//  a temporary with the key (b, Y) is created.
+//   6. `EvaluateWithSubstitution` looks at "b" but cannot evaluate it
+//  because it's value-dependent (due to the call to "f.foo()").
+//
+// When `EvaluateWithSubstitution` bails out while evaluating the outer
+// call, it attempts to fetch "b"'s param slot to clean it up.
+//
+// This used to cause an assertion failure in `getTemporary` because
+// a temporary with the key "(b, Y)" (created at step 4) existed but
+// not one for "(b, X)", which is what it was trying to fetch.
+
+template
+__attribute__((enable_if(true, "")))
+T kaboom(T a, T b) {
+  return b;
+}
+
+struct A {
+  double foo();
+};
+
+template 
+struct B {
+  A &f;
+
+  void bar() {
+kaboom(kaboom(0.0, 1.0), f.foo());
+  }
+};
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -594,11 +594,6 @@
   auto LB = Temporaries.lower_bound(KV);
   if (LB !

[clang] d6acd01 - [Sema] Fix crash when evaluating nested call with value-dependent arg

2023-01-05 Thread Pierre van Houtryve via cfe-commits

Author: Pierre van Houtryve
Date: 2023-01-06T02:57:50-05:00
New Revision: d6acd0196b3378bdeb5193053e290d7194c4f72d

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

LOG: [Sema] Fix crash when evaluating nested call with value-dependent arg

Fix an edge case `ExprConstant.cpp`'s `EvaluateWithSubstitution` when called by 
`CheckEnableIf`

The assertion in `CallStackFrame::getTemporary`
could fail during evaluation of nested calls to a function
using `enable_if` when the second argument was a
value-dependent expression.

This caused a temporary to be created for the second
argument with a given version during the
evaluation of the inner call, but we bailed out
when evaluating the second argument of the
outer call due to the expression being value-dependent.
After bailing out, we tried to clean up the argument's value slot but it
caused an assertion to trigger in `getTemporary` as
a temporary for the second argument existed, but only for the inner call and 
not the outer call.

See the test case for a more complete description of the issue.

Reviewed By: ahatanak

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

Added: 
clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp

Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 78cfecbec9fd3..a43845e53c5d0 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -594,11 +594,6 @@ namespace {
   auto LB = Temporaries.lower_bound(KV);
   if (LB != Temporaries.end() && LB->first == KV)
 return &LB->second;
-  // Pair (Key,Version) wasn't found in the map. Check that no elements
-  // in the map have 'Key' as their key.
-  assert((LB == Temporaries.end() || LB->first.first != Key) &&
- (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) 
&&
- "Element with key 'Key' found in map");
   return nullptr;
 }
 

diff  --git 
a/clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp 
b/clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
new file mode 100644
index 0..998f2ccf92534
--- /dev/null
+++ b/clang/test/SemaCXX/enable_if-nested-call-with-valuedependent-param.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_cc1 -fsyntax-only %s -std=c++14
+
+// Checks that Clang doesn't crash/assert on the nested call to "kaboom"
+// in "bar()".
+//
+// This is an interesting test case for `ExprConstant.cpp`'s `CallStackFrame`
+// because it triggers the following chain of events:
+// 0. `CheckEnableIf` calls `EvaluateWithSubstitution`.
+//  1. The outer call to "kaboom" gets evaluated.
+//   2. The expr for "a" gets evaluated, it has a version X;
+//  a temporary with the key (a, X) is created.
+// 3. The inner call to "kaboom" gets evaluated.
+//   4. The expr for "a" gets evaluated, it has a version Y;
+//  a temporary with the key (a, Y) is created.
+//   5. The expr for "b" gets evaluated, it has a version Y;
+//  a temporary with the key (b, Y) is created.
+//   6. `EvaluateWithSubstitution` looks at "b" but cannot evaluate it
+//  because it's value-dependent (due to the call to "f.foo()").
+//
+// When `EvaluateWithSubstitution` bails out while evaluating the outer
+// call, it attempts to fetch "b"'s param slot to clean it up.
+//
+// This used to cause an assertion failure in `getTemporary` because
+// a temporary with the key "(b, Y)" (created at step 4) existed but
+// not one for "(b, X)", which is what it was trying to fetch.
+
+template
+__attribute__((enable_if(true, "")))
+T kaboom(T a, T b) {
+  return b;
+}
+
+struct A {
+  double foo();
+};
+
+template 
+struct B {
+  A &f;
+
+  void bar() {
+kaboom(kaboom(0.0, 1.0), f.foo());
+  }
+};



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


[PATCH] D137996: Add support for a backdoor driver option that enables emitting header usage information in JSON to a file

2023-01-05 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/tools/driver/driver.cpp:251
+ std::string &OptFile) {
+  T OptVal = ::getenv(EnvOptSet);
+  if (OptVal) {

SeanP wrote:
> This change is not POSIX compliant.  If T is char *, the next call to 
> getenv() on line 253 invalidates the value saved into OptVal.  getenv() is 
> allowed to use the same buffer for the return value.  That means the value 
> OptVal is pointing at will be overwritten by the next call.
> 
> When T is bool you need the `!!` operators to get the char * converted to 
> bool correctly.
> 
> I suggest leaving this function as it was and calling getenv() directly for 
> the scenario involving CC_PRINT_HEADERS_FORMAT.  Make sure you save the 
> getenv() results into std::string so the value isn't overridden.
Thank you for notifying me of the bug. It should be fixed in 
https://github.com/llvm/llvm-project/commit/34aa2e24c89ae39c0db4254d8aafcae0285dbe34


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137996

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


[clang] 34aa2e2 - Save the result of getenv() to a string

2023-01-05 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-01-05T22:59:07-08:00
New Revision: 34aa2e24c89ae39c0db4254d8aafcae0285dbe34

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

LOG: Save the result of getenv() to a string

The result has to be saved to a string as the result might be
overwritten by subsequent calls to getenv.

https://pubs.opengroup.org/onlinepubs/009696899/functions/getenv.html

See the discussion here: https://reviews.llvm.org/D137996#4029305

Added: 


Modified: 
clang/tools/driver/driver.cpp

Removed: 




diff  --git a/clang/tools/driver/driver.cpp b/clang/tools/driver/driver.cpp
index 126670052421f..0d46f5ec8d1fa 100644
--- a/clang/tools/driver/driver.cpp
+++ b/clang/tools/driver/driver.cpp
@@ -248,11 +248,13 @@ static void getCLEnvVarOptions(std::string &EnvValue, 
llvm::StringSaver &Saver,
 template 
 static T checkEnvVar(const char *EnvOptSet, const char *EnvOptFile,
  std::string &OptFile) {
-  T OptVal = ::getenv(EnvOptSet);
-  if (OptVal) {
-if (const char *Var = ::getenv(EnvOptFile))
-  OptFile = Var;
-  }
+  const char *Str = ::getenv(EnvOptSet);
+  if (!Str)
+return T{};
+
+  T OptVal = Str;
+  if (const char *Var = ::getenv(EnvOptFile))
+OptFile = Var;
   return OptVal;
 }
 
@@ -264,32 +266,37 @@ static bool SetBackdoorDriverOutputsFromEnvVars(Driver 
&TheDriver) {
 TheDriver.CCPrintHeadersFilename)) {
 TheDriver.CCPrintHeadersFormat = HIFMT_Textual;
 TheDriver.CCPrintHeadersFiltering = HIFIL_None;
-  } else if (const char *EnvVar = checkEnvVar(
- "CC_PRINT_HEADERS_FORMAT", "CC_PRINT_HEADERS_FILE",
- TheDriver.CCPrintHeadersFilename)) {
-TheDriver.CCPrintHeadersFormat = stringToHeaderIncludeFormatKind(EnvVar);
-if (!TheDriver.CCPrintHeadersFormat) {
-  TheDriver.Diag(clang::diag::err_drv_print_header_env_var) << 0 << EnvVar;
-  return false;
-}
+  } else {
+std::string EnvVar = checkEnvVar(
+"CC_PRINT_HEADERS_FORMAT", "CC_PRINT_HEADERS_FILE",
+TheDriver.CCPrintHeadersFilename);
+if (!EnvVar.empty()) {
+  TheDriver.CCPrintHeadersFormat =
+  stringToHeaderIncludeFormatKind(EnvVar.c_str());
+  if (!TheDriver.CCPrintHeadersFormat) {
+TheDriver.Diag(clang::diag::err_drv_print_header_env_var)
+<< 0 << EnvVar;
+return false;
+  }
 
-const char *FilteringStr = ::getenv("CC_PRINT_HEADERS_FILTERING");
-HeaderIncludeFilteringKind Filtering;
-if (!stringToHeaderIncludeFiltering(FilteringStr, Filtering)) {
-  TheDriver.Diag(clang::diag::err_drv_print_header_env_var)
-  << 1 << FilteringStr;
-  return false;
-}
+  const char *FilteringStr = ::getenv("CC_PRINT_HEADERS_FILTERING");
+  HeaderIncludeFilteringKind Filtering;
+  if (!stringToHeaderIncludeFiltering(FilteringStr, Filtering)) {
+TheDriver.Diag(clang::diag::err_drv_print_header_env_var)
+<< 1 << FilteringStr;
+return false;
+  }
 
-if ((TheDriver.CCPrintHeadersFormat == HIFMT_Textual &&
- Filtering != HIFIL_None) ||
-(TheDriver.CCPrintHeadersFormat == HIFMT_JSON &&
- Filtering != HIFIL_Only_Direct_System)) {
-  TheDriver.Diag(clang::diag::err_drv_print_header_env_var_combination)
-  << EnvVar << FilteringStr;
-  return false;
+  if ((TheDriver.CCPrintHeadersFormat == HIFMT_Textual &&
+   Filtering != HIFIL_None) ||
+  (TheDriver.CCPrintHeadersFormat == HIFMT_JSON &&
+   Filtering != HIFIL_Only_Direct_System)) {
+TheDriver.Diag(clang::diag::err_drv_print_header_env_var_combination)
+<< EnvVar << FilteringStr;
+return false;
+  }
+  TheDriver.CCPrintHeadersFiltering = Filtering;
 }
-TheDriver.CCPrintHeadersFiltering = Filtering;
   }
 
   TheDriver.CCLogDiagnostics =



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


[clang] 1ff3064 - [Driver] Simplify -fsanitize-memory-track-origins handling. NFC

2023-01-05 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-01-05T22:21:13-08:00
New Revision: 1ff3064c65b4d4440254311474efe176fd1c4e2c

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

LOG: [Driver] Simplify -fsanitize-memory-track-origins handling. NFC

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/SanitizerArgs.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index dd299fa8e8830..b2f74add94ee4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1728,6 +1728,7 @@ def fsanitize_memory_track_origins_EQ : Joined<["-"], 
"fsanitize-memory-track-or
 
MarshallingInfoInt>;
 def fsanitize_memory_track_origins : Flag<["-"], 
"fsanitize-memory-track-origins">,
  Group,
+ Alias, 
AliasArgs<["2"]>,
  HelpText<"Enable origins tracking in 
MemorySanitizer">;
 def fno_sanitize_memory_track_origins : Flag<["-"], 
"fno-sanitize-memory-track-origins">,
 Group,

diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 96a701366e37b..52bee6a755ff4 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -650,14 +650,9 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
   if (AllAddedKinds & SanitizerKind::Memory) {
 if (Arg *A =
 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
-options::OPT_fsanitize_memory_track_origins,
 options::OPT_fno_sanitize_memory_track_origins)) {
-  if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) 
{
-MsanTrackOrigins = 2;
-  } else if (A->getOption().matches(
- options::OPT_fno_sanitize_memory_track_origins)) {
-MsanTrackOrigins = 0;
-  } else {
+  if (!A->getOption().matches(
+  options::OPT_fno_sanitize_memory_track_origins)) {
 StringRef S = A->getValue();
 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
 MsanTrackOrigins > 2) {



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


[clang] 22df454 - Revert "[Fix]"[-Wunsafe-buffer-usage] Add a new `forEachDescendant` matcher that skips callable declarations""

2023-01-05 Thread via cfe-commits

Author: ziqingluo-90
Date: 2023-01-05T22:06:46-08:00
New Revision: 22df4549a3718dcd8b387ba8246978349e4be50c

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

LOG: Revert "[Fix]"[-Wunsafe-buffer-usage] Add a new `forEachDescendant` 
matcher that skips callable declarations""

This reverts commit ef47a0a711f12add401394f7af07a0b4d1635b56.

Revert "[-Wunsafe-buffer-usage] Add a new `forEachDescendant` matcher that 
skips callable declarations"

This reverts commit b2ac5fd724c44cf662caed84bd8f84af574b981d.

This patch is causing failure in some Sanitizer tests
(https://lab.llvm.org/buildbot/#/builders/5/builds/30522/steps/13/logs/stdio).  
Reverting the patch and its' fix.

Added: 


Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 80a54c3ad38b7..a699d27c1544c 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -8,112 +8,12 @@
 
 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/SmallVector.h"
 
 using namespace llvm;
 using namespace clang;
 using namespace ast_matchers;
 
-namespace clang::ast_matchers {
-// A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
-// except for those belonging to a 
diff erent callable of "n".
-class MatchDescendantVisitor
-: public RecursiveASTVisitor {
-public:
-  typedef RecursiveASTVisitor VisitorBase;
-
-  // Creates an AST visitor that matches `Matcher` on all
-  // descendants of a given node "n" except for the ones
-  // belonging to a 
diff erent callable of "n".
-  MatchDescendantVisitor(const internal::DynTypedMatcher *Matcher,
- internal::ASTMatchFinder *Finder,
- internal::BoundNodesTreeBuilder *Builder,
- internal::ASTMatchFinder::BindKind Bind)
-  : Matcher(Matcher), Finder(Finder), Builder(Builder), Bind(Bind),
-Matches(false) {}
-
-  // Returns true if a match is found in a subtree of `DynNode`, which belongs
-  // to the same callable of `DynNode`.
-  bool findMatch(const DynTypedNode &DynNode) {
-Matches = false;
-if (const Stmt *StmtNode = DynNode.get()) {
-  TraverseStmt(const_cast(StmtNode));
-  *Builder = ResultBindings;
-  return Matches;
-}
-return false;
-  }
-
-  // The following are overriding methods from the base visitor class.
-  // They are public only to allow CRTP to work. They are *not *part
-  // of the public API of this class.
-
-  // For the matchers so far used in safe buffers, we only need to match
-  // `Stmt`s.  To override more as needed.
-
-  bool TraverseDecl(Decl *Node) {
-if (!Node)
-  return true;
-if (!match(*Node))
-  return false;
-// To skip callables:
-if (isa(Node))
-  return true;
-// Traverse descendants
-return VisitorBase::TraverseDecl(Node);
-  }
-
-  bool TraverseStmt(Stmt *Node, DataRecursionQueue *Queue = nullptr) {
-if (!Node)
-  return true;
-if (!match(*Node))
-  return false;
-// To skip callables:
-if (isa(Node))
-  return true;
-return VisitorBase::TraverseStmt(Node);
-  }
-
-  bool shouldVisitTemplateInstantiations() const { return true; }
-  bool shouldVisitImplicitCode() const {
-// TODO: let's ignore implicit code for now
-return false;
-  }
-
-private:
-  // Sets 'Matched' to true if 'Matcher' matches 'Node'
-  //
-  // Returns 'true' if traversal should continue after this function
-  // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
-  template  bool match(const T &Node) {
-internal::BoundNodesTreeBuilder RecursiveBuilder(*Builder);
-
-if (Matcher->matches(DynTypedNode::create(Node), Finder,
- &RecursiveBuilder)) {
-  ResultBindings.addMatch(RecursiveBuilder);
-  Matches = true;
-  if (Bind != internal::ASTMatchFinder::BK_All)
-return false; // Abort as soon as a match is found.
-}
-return true;
-  }
-
-  const internal::DynTypedMatcher *const Matcher;
-  internal::ASTMatchFinder *const Finder;
-  internal::BoundNodesTreeBuilder *const Builder;
-  internal::BoundNodesTreeBuilder ResultBindings;
-  const internal::ASTMatchFinder::BindKind Bind;
-  bool Matches;
-};
-
-AST_MATCHER_P(Stmt, forEveryDescendant, internal::Matcher, innerMatcher) 
{
-  MatchDescendantVisitor Visitor(new DynTypedMatcher(innerMatcher), Finder,
- Builder, ASTMatchFinder::BK_All);
-  return Visitor.findMatch(DynTypedNode::create(Node));
-}
-} // namespace c

[PATCH] D141107: [clang-tidy] don't warn when returning the result for bugprone-standalone-empty

2023-01-05 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry created this revision.
v1nh1shungry added reviewers: cjdb, hokein.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
v1nh1shungry requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Relevant issue: https://github.com/llvm/llvm-project/issues/59517

Currently this check will warn when the result is used in a `return`
statement, e.g.

  bool foobar() {
std::vector v;
return v.empty();
// will get a warning here, which makes no sense IMO
  }


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D141107

Files:
  clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
@@ -576,3 +576,16 @@
 // CHECK-MESSAGES: :[[#@LINE-1]]:5: warning: ignoring the result of 
'std::empty' [bugprone-standalone-empty]
   }
 }
+
+bool test_empty_in_return() {
+  {
+std::vector v;
+return v.empty();
+// no-warning
+  }
+  {
+std::vector v;
+return std::empty(v);
+// no-warning
+  }
+}
Index: clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
@@ -98,6 +98,7 @@
   const auto PParentStmtExpr = Result.Nodes.getNodeAs("stexpr");
   const auto ParentCompStmt = Result.Nodes.getNodeAs("parent");
   const auto *ParentCond = getCondition(Result.Nodes, "parent");
+  const auto *ParentReturnStmt = Result.Nodes.getNodeAs("parent");
 
   if (const auto *MemberCall =
   Result.Nodes.getNodeAs("empty")) {
@@ -109,6 +110,9 @@
 if (PParentStmtExpr && ParentCompStmt &&
 ParentCompStmt->body_back() == MemberCall->getExprStmt())
   return;
+// Skip if it's a return statement
+if (ParentReturnStmt)
+  return;
 
 SourceLocation MemberLoc = MemberCall->getBeginLoc();
 SourceLocation ReplacementLoc = MemberCall->getExprLoc();
@@ -150,6 +154,8 @@
 if (PParentStmtExpr && ParentCompStmt &&
 ParentCompStmt->body_back() == NonMemberCall->getExprStmt())
   return;
+if (ParentReturnStmt)
+  return;
 
 SourceLocation NonMemberLoc = NonMemberCall->getExprLoc();
 SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc();


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/standalone-empty.cpp
@@ -576,3 +576,16 @@
 // CHECK-MESSAGES: :[[#@LINE-1]]:5: warning: ignoring the result of 'std::empty' [bugprone-standalone-empty]
   }
 }
+
+bool test_empty_in_return() {
+  {
+std::vector v;
+return v.empty();
+// no-warning
+  }
+  {
+std::vector v;
+return std::empty(v);
+// no-warning
+  }
+}
Index: clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp
@@ -98,6 +98,7 @@
   const auto PParentStmtExpr = Result.Nodes.getNodeAs("stexpr");
   const auto ParentCompStmt = Result.Nodes.getNodeAs("parent");
   const auto *ParentCond = getCondition(Result.Nodes, "parent");
+  const auto *ParentReturnStmt = Result.Nodes.getNodeAs("parent");
 
   if (const auto *MemberCall =
   Result.Nodes.getNodeAs("empty")) {
@@ -109,6 +110,9 @@
 if (PParentStmtExpr && ParentCompStmt &&
 ParentCompStmt->body_back() == MemberCall->getExprStmt())
   return;
+// Skip if it's a return statement
+if (ParentReturnStmt)
+  return;
 
 SourceLocation MemberLoc = MemberCall->getBeginLoc();
 SourceLocation ReplacementLoc = MemberCall->getExprLoc();
@@ -150,6 +154,8 @@
 if (PParentStmtExpr && ParentCompStmt &&
 ParentCompStmt->body_back() == NonMemberCall->getExprStmt())
   return;
+if (ParentReturnStmt)
+  return;
 
 SourceLocation NonMemberLoc = NonMemberCall->getExprLoc();
 SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D127442: [Sema] Fix a bug where clang doesn't detect uses of unavailable decls in C++ base or member initializers

2023-01-05 Thread Akira Hatanaka 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 rG143ec502e985: [Sema] Fix a bug where clang doesn't 
detect uses of unavailable decls (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127442

Files:
  clang/lib/Sema/SemaAvailability.cpp
  clang/test/SemaCXX/attr-availability.cpp


Index: clang/test/SemaCXX/attr-availability.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/attr-availability.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9.0 -std=c++11 -fsyntax-only 
-verify %s
+
+__attribute__((availability(macos, introduced = 10.0))) int init10();
+__attribute__((availability(macos, introduced = 11.0))) int init11(); // 
expected-note 2 {{'init11' has been marked as being introduced in macOS 11.0}}
+
+struct B0 {
+  B0(int);
+};
+
+struct B1 {
+  B1(int);
+};
+
+struct S : B0, B1 {
+  S() : B0(init10()),
+B1(init11()), // expected-warning {{'init11' is only available on 
macOS 11.0}} expected-note {{enclose 'init11'}}
+i0(init10()),
+i1(init11())  // expected-warning {{'init11' is only available on 
macOS 11.0}} expected-note {{enclose 'init11'}}
+  {}
+  int i0, i1;
+};
Index: clang/lib/Sema/SemaAvailability.cpp
===
--- clang/lib/Sema/SemaAvailability.cpp
+++ clang/lib/Sema/SemaAvailability.cpp
@@ -898,6 +898,11 @@
   return;
 
 Body = FD->getBody();
+
+if (auto *CD = dyn_cast(FD))
+  for (const CXXCtorInitializer *CI : CD->inits())
+DiagnoseUnguardedAvailability(*this, 
D).IssueDiagnostics(CI->getInit());
+
   } else if (auto *MD = dyn_cast(D))
 Body = MD->getBody();
   else if (auto *BD = dyn_cast(D))


Index: clang/test/SemaCXX/attr-availability.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/attr-availability.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9.0 -std=c++11 -fsyntax-only -verify %s
+
+__attribute__((availability(macos, introduced = 10.0))) int init10();
+__attribute__((availability(macos, introduced = 11.0))) int init11(); // expected-note 2 {{'init11' has been marked as being introduced in macOS 11.0}}
+
+struct B0 {
+  B0(int);
+};
+
+struct B1 {
+  B1(int);
+};
+
+struct S : B0, B1 {
+  S() : B0(init10()),
+B1(init11()), // expected-warning {{'init11' is only available on macOS 11.0}} expected-note {{enclose 'init11'}}
+i0(init10()),
+i1(init11())  // expected-warning {{'init11' is only available on macOS 11.0}} expected-note {{enclose 'init11'}}
+  {}
+  int i0, i1;
+};
Index: clang/lib/Sema/SemaAvailability.cpp
===
--- clang/lib/Sema/SemaAvailability.cpp
+++ clang/lib/Sema/SemaAvailability.cpp
@@ -898,6 +898,11 @@
   return;
 
 Body = FD->getBody();
+
+if (auto *CD = dyn_cast(FD))
+  for (const CXXCtorInitializer *CI : CD->inits())
+DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(CI->getInit());
+
   } else if (auto *MD = dyn_cast(D))
 Body = MD->getBody();
   else if (auto *BD = dyn_cast(D))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 143ec50 - [Sema] Fix a bug where clang doesn't detect uses of unavailable decls

2023-01-05 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-01-05T20:33:56-08:00
New Revision: 143ec502e9859141e9d340ed59046dad0fc4ee6f

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

LOG: [Sema] Fix a bug where clang doesn't detect uses of unavailable decls
in C++ base or member initializers

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

Added: 
clang/test/SemaCXX/attr-availability.cpp

Modified: 
clang/lib/Sema/SemaAvailability.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaAvailability.cpp 
b/clang/lib/Sema/SemaAvailability.cpp
index b0e99da9dd5f7..316c01309a8c6 100644
--- a/clang/lib/Sema/SemaAvailability.cpp
+++ b/clang/lib/Sema/SemaAvailability.cpp
@@ -898,6 +898,11 @@ void Sema::DiagnoseUnguardedAvailabilityViolations(Decl 
*D) {
   return;
 
 Body = FD->getBody();
+
+if (auto *CD = dyn_cast(FD))
+  for (const CXXCtorInitializer *CI : CD->inits())
+DiagnoseUnguardedAvailability(*this, 
D).IssueDiagnostics(CI->getInit());
+
   } else if (auto *MD = dyn_cast(D))
 Body = MD->getBody();
   else if (auto *BD = dyn_cast(D))

diff  --git a/clang/test/SemaCXX/attr-availability.cpp 
b/clang/test/SemaCXX/attr-availability.cpp
new file mode 100644
index 0..8964bdbd34d44
--- /dev/null
+++ b/clang/test/SemaCXX/attr-availability.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -triple x86_64-apple-macosx10.9.0 -std=c++11 -fsyntax-only 
-verify %s
+
+__attribute__((availability(macos, introduced = 10.0))) int init10();
+__attribute__((availability(macos, introduced = 11.0))) int init11(); // 
expected-note 2 {{'init11' has been marked as being introduced in macOS 11.0}}
+
+struct B0 {
+  B0(int);
+};
+
+struct B1 {
+  B1(int);
+};
+
+struct S : B0, B1 {
+  S() : B0(init10()),
+B1(init11()), // expected-warning {{'init11' is only available on 
macOS 11.0}} expected-note {{enclose 'init11'}}
+i0(init10()),
+i1(init11())  // expected-warning {{'init11' is only available on 
macOS 11.0}} expected-note {{enclose 'init11'}}
+  {}
+  int i0, i1;
+};



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


[PATCH] D136639: [CodeGen][ObjC] Fix a memory leak that occurs when a non-trivial C struct property is set using dot notation

2023-01-05 Thread Akira Hatanaka 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 rGea0cd51a4958: [CodeGen][ObjC] Fix a memory leak that occurs 
when a non-trivial C (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136639

Files:
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/test/CodeGenObjC/nontrivial-c-struct-property.m


Index: clang/test/CodeGenObjC/nontrivial-c-struct-property.m
===
--- clang/test/CodeGenObjC/nontrivial-c-struct-property.m
+++ clang/test/CodeGenObjC/nontrivial-c-struct-property.m
@@ -68,3 +68,39 @@
 // CHECK: call void @objc_copyCppObjectAtomic({{.*}}, {{.*}}, ptr noundef 
@__move_assignment_8_8_s0)
 // CHECK-NOT: call
 // CHECK: ret void
+
+// CHECK: define void @test0(ptr noundef %[[C:.*]], ptr noundef %[[A:.*]])
+// CHECK: %[[C_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[A_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[AGG_TMP_ENSURED:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: %[[AGG_TMP:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: store ptr null, ptr %[[C_ADDR]], align 8
+// CHECK: call void @llvm.objc.storeStrong(ptr %[[C_ADDR]], ptr %[[C]])
+// CHECK: store ptr %[[A]], ptr %[[A_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load ptr, ptr %[[A_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP_ENSURED]], ptr 
%[[V0]])
+// CHECK: %[[V1:.*]] = load ptr, ptr %[[C_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP]], ptr 
%[[AGG_TMP_ENSURED]])
+// CHECK: %[[V2:.*]] = icmp eq ptr %[[V1]], null
+// CHECK: br i1 %[[V2]], label %[[MSGSEND_NULL:.*]], label %[[MSGSEND_CALL:.*]]
+
+// CHECK: [[MSGSEND_CALL]]:
+// CHECK: %[[V3:.*]] = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
+// CHECK: %[[COERCE_DIVE:.*]] = getelementptr inbounds %[[STRUCT_S0]], ptr 
%[[AGG_TMP]], i32 0, i32 0
+// CHECK: %[[V4:.*]] = load ptr, ptr %[[COERCE_DIVE]], align 8
+// CHECK: %[[COERCE_VAL_PI:.*]] = ptrtoint ptr %[[V4]] to i64
+// CHECK: call void @objc_msgSend(ptr noundef %[[V1]], ptr noundef %[[V3]], 
i64 %[[COERCE_VAL_PI]])
+// CHECK: br label %[[MSGSEND_CONT:.*]]
+
+// CHECK: [[MSGSEND_NULL]]:
+// CHECK: call void @__destructor_8_s0(ptr %[[AGG_TMP]])
+// CHECK: br label %[[MSGSEND_CONT]]
+
+// CHECK: [[MSGSEND_CONT]]:
+// CHECK: call void @__destructor_8_s0(ptr %[[AGG_TMP_ENSURED]]
+// CHECK: call void @llvm.objc.storeStrong(ptr %[[C_ADDR]], ptr null)
+// CHECK: ret void
+
+void test0(C *c, S0 *a) {
+  c.atomic0 = *a;
+}
Index: clang/lib/CodeGen/CGExprAgg.cpp
===
--- clang/lib/CodeGen/CGExprAgg.cpp
+++ clang/lib/CodeGen/CGExprAgg.cpp
@@ -201,7 +201,16 @@
   return EmitFinalDestCopy(E->getType(), LV);
 }
 
-CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
+AggValueSlot Slot = EnsureSlot(E->getType());
+bool NeedsDestruction =
+!Slot.isExternallyDestructed() &&
+E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
+if (NeedsDestruction)
+  Slot.setExternallyDestructed();
+CGF.EmitPseudoObjectRValue(E, Slot);
+if (NeedsDestruction)
+  CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Slot.getAddress(),
+  E->getType());
   }
 
   void VisitVAArgExpr(VAArgExpr *E);


Index: clang/test/CodeGenObjC/nontrivial-c-struct-property.m
===
--- clang/test/CodeGenObjC/nontrivial-c-struct-property.m
+++ clang/test/CodeGenObjC/nontrivial-c-struct-property.m
@@ -68,3 +68,39 @@
 // CHECK: call void @objc_copyCppObjectAtomic({{.*}}, {{.*}}, ptr noundef @__move_assignment_8_8_s0)
 // CHECK-NOT: call
 // CHECK: ret void
+
+// CHECK: define void @test0(ptr noundef %[[C:.*]], ptr noundef %[[A:.*]])
+// CHECK: %[[C_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[A_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[AGG_TMP_ENSURED:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: %[[AGG_TMP:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: store ptr null, ptr %[[C_ADDR]], align 8
+// CHECK: call void @llvm.objc.storeStrong(ptr %[[C_ADDR]], ptr %[[C]])
+// CHECK: store ptr %[[A]], ptr %[[A_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load ptr, ptr %[[A_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP_ENSURED]], ptr %[[V0]])
+// CHECK: %[[V1:.*]] = load ptr, ptr %[[C_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP]], ptr %[[AGG_TMP_ENSURED]])
+// CHECK: %[[V2:.*]] = icmp eq ptr %[[V1]], null
+// CHECK: br i1 %[[V2]], label %[[MSGSEND_NULL:.*]], label %[[MSGSEND_CALL:.*]]
+
+// CHECK: [[MSGSEND_CALL]]:
+// CHECK: %[[V3:.*]] = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
+// CHECK: %[[COERCE_DIVE:.*]] = getelementptr inbounds %[[STRUCT_S0]], ptr %[[AGG_TMP]], i32 0, i32 0

[clang] ea0cd51 - [CodeGen][ObjC] Fix a memory leak that occurs when a non-trivial C

2023-01-05 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-01-05T19:48:25-08:00
New Revision: ea0cd51a495829ea35b7b8304b16784946598d19

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

LOG: [CodeGen][ObjC] Fix a memory leak that occurs when a non-trivial C
struct property is set using dot notation

Make sure the destructor is called if needed.

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

Added: 


Modified: 
clang/lib/CodeGen/CGExprAgg.cpp
clang/test/CodeGenObjC/nontrivial-c-struct-property.m

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 5fdbc6a75201f..45b3edf70e2e3 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -201,7 +201,16 @@ class AggExprEmitter : public StmtVisitor {
   return EmitFinalDestCopy(E->getType(), LV);
 }
 
-CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
+AggValueSlot Slot = EnsureSlot(E->getType());
+bool NeedsDestruction =
+!Slot.isExternallyDestructed() &&
+E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
+if (NeedsDestruction)
+  Slot.setExternallyDestructed();
+CGF.EmitPseudoObjectRValue(E, Slot);
+if (NeedsDestruction)
+  CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Slot.getAddress(),
+  E->getType());
   }
 
   void VisitVAArgExpr(VAArgExpr *E);

diff  --git a/clang/test/CodeGenObjC/nontrivial-c-struct-property.m 
b/clang/test/CodeGenObjC/nontrivial-c-struct-property.m
index 9f907e20331a0..12c042feac98f 100644
--- a/clang/test/CodeGenObjC/nontrivial-c-struct-property.m
+++ b/clang/test/CodeGenObjC/nontrivial-c-struct-property.m
@@ -68,3 +68,39 @@ -(void)setP1:(S0)s0 {
 // CHECK: call void @objc_copyCppObjectAtomic({{.*}}, {{.*}}, ptr noundef 
@__move_assignment_8_8_s0)
 // CHECK-NOT: call
 // CHECK: ret void
+
+// CHECK: define void @test0(ptr noundef %[[C:.*]], ptr noundef %[[A:.*]])
+// CHECK: %[[C_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[A_ADDR:.*]] = alloca ptr, align 8
+// CHECK: %[[AGG_TMP_ENSURED:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: %[[AGG_TMP:.*]] = alloca %[[STRUCT_S0]], align 8
+// CHECK: store ptr null, ptr %[[C_ADDR]], align 8
+// CHECK: call void @llvm.objc.storeStrong(ptr %[[C_ADDR]], ptr %[[C]])
+// CHECK: store ptr %[[A]], ptr %[[A_ADDR]], align 8
+// CHECK: %[[V0:.*]] = load ptr, ptr %[[A_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP_ENSURED]], ptr 
%[[V0]])
+// CHECK: %[[V1:.*]] = load ptr, ptr %[[C_ADDR]], align 8
+// CHECK: call void @__copy_constructor_8_8_s0(ptr %[[AGG_TMP]], ptr 
%[[AGG_TMP_ENSURED]])
+// CHECK: %[[V2:.*]] = icmp eq ptr %[[V1]], null
+// CHECK: br i1 %[[V2]], label %[[MSGSEND_NULL:.*]], label %[[MSGSEND_CALL:.*]]
+
+// CHECK: [[MSGSEND_CALL]]:
+// CHECK: %[[V3:.*]] = load ptr, ptr @OBJC_SELECTOR_REFERENCES_, align 8
+// CHECK: %[[COERCE_DIVE:.*]] = getelementptr inbounds %[[STRUCT_S0]], ptr 
%[[AGG_TMP]], i32 0, i32 0
+// CHECK: %[[V4:.*]] = load ptr, ptr %[[COERCE_DIVE]], align 8
+// CHECK: %[[COERCE_VAL_PI:.*]] = ptrtoint ptr %[[V4]] to i64
+// CHECK: call void @objc_msgSend(ptr noundef %[[V1]], ptr noundef %[[V3]], 
i64 %[[COERCE_VAL_PI]])
+// CHECK: br label %[[MSGSEND_CONT:.*]]
+
+// CHECK: [[MSGSEND_NULL]]:
+// CHECK: call void @__destructor_8_s0(ptr %[[AGG_TMP]])
+// CHECK: br label %[[MSGSEND_CONT]]
+
+// CHECK: [[MSGSEND_CONT]]:
+// CHECK: call void @__destructor_8_s0(ptr %[[AGG_TMP_ENSURED]]
+// CHECK: call void @llvm.objc.storeStrong(ptr %[[C_ADDR]], ptr null)
+// CHECK: ret void
+
+void test0(C *c, S0 *a) {
+  c.atomic0 = *a;
+}



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


[PATCH] D141105: [OpenMP] Add support for '--offload-arch=native' to OpenMP offloading

2023-01-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, tianshilei1992, JonChesterfield, tra, 
yaxunl.
Herald added a subscriber: guansong.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, MaskRay.
Herald added a project: clang.

This patch adds support for '--offload-arch=native' to OpenMP
offloading. This will automatically generate the toolchains required to
fulfil whatever GPUs the user has installed. Getting this to work
requires a bit of a hack. The problem is that we need the ToolChain to
launch its searching program. But we do not yet have that ToolChain
built. I had to temporarily make the ToolChain and also add some logic
to ignore regular warnings & errors.

Depends on D141078 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D141105

Files:
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp

Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -848,9 +848,29 @@
   HostTC->getTriple());
 
   // Attempt to deduce the offloading triple from the set of architectures.
-  // We can only correctly deduce NVPTX / AMDGPU triples currently.
-  llvm::DenseSet Archs =
-  getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr);
+  // We can only correctly deduce NVPTX / AMDGPU triples currently. We need
+  // to temporarily create these toolchains so that we can access tools for
+  // inferring architectures.
+  llvm::DenseSet Archs;
+  if (NVPTXTriple) {
+auto TempTC = std::make_unique(
+*this, *NVPTXTriple, *HostTC, C.getInputArgs());
+for (StringRef Arch : getOffloadArchs(
+ C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
+  Archs.insert(Arch);
+  }
+  if (AMDTriple) {
+auto TempTC = std::make_unique(
+*this, *AMDTriple, *HostTC, C.getInputArgs());
+for (StringRef Arch : getOffloadArchs(
+ C, C.getArgs(), Action::OFK_OpenMP, &*TempTC, true))
+  Archs.insert(Arch);
+  }
+  if (!AMDTriple && !NVPTXTriple) {
+for (StringRef Arch :
+ getOffloadArchs(C, C.getArgs(), Action::OFK_OpenMP, nullptr, true))
+  Archs.insert(Arch);
+  }
   for (StringRef Arch : Archs) {
 if (NVPTXTriple && IsNVIDIAGpuArch(StringToCudaArch(
getProcessorFromTargetID(*NVPTXTriple, Arch {
@@ -4182,16 +4202,17 @@
 static StringRef getCanonicalArchString(Compilation &C,
 const llvm::opt::DerivedArgList &Args,
 StringRef ArchStr,
-const llvm::Triple &Triple) {
+const llvm::Triple &Triple,
+bool Query = false) {
   // Lookup the CUDA / HIP architecture string. Only report an error if we were
   // expecting the triple to be only NVPTX / AMDGPU.
   CudaArch Arch = StringToCudaArch(getProcessorFromTargetID(Triple, ArchStr));
-  if (Triple.isNVPTX() &&
+  if (!Query && Triple.isNVPTX() &&
   (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch))) {
 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
 << "CUDA" << ArchStr;
 return StringRef();
-  } else if (Triple.isAMDGPU() &&
+  } else if (!Query && Triple.isAMDGPU() &&
  (Arch == CudaArch::UNKNOWN || !IsAMDGpuArch(Arch))) {
 C.getDriver().Diag(clang::diag::err_drv_offload_bad_gpu_arch)
 << "HIP" << ArchStr;
@@ -4234,7 +4255,8 @@
 
 llvm::DenseSet
 Driver::getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args,
-Action::OffloadKind Kind, const ToolChain *TC) const {
+Action::OffloadKind Kind, const ToolChain *TC,
+bool Query) const {
   if (!TC)
 TC = &C.getDefaultToolChain();
 
@@ -4271,18 +4293,22 @@
 if (Arch == "native") {
   auto GPUsOrErr = TC->getSystemGPUArchs(Args);
   if (!GPUsOrErr) {
-TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
-<< llvm::Triple::getArchTypeName(TC->getArch())
-<< llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
+if (Query)
+  llvm::consumeError(GPUsOrErr.takeError());
+else
+  TC->getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
+  << llvm::Triple::getArchTypeName(TC->getArch())
+  << llvm::toString(GPUsOrErr.takeError()) << "--offload-arch";
 continue;
   }
 
-  for (auto ArchStr : *GPUsOrErr)
-Archs.insert(
-getCanonicalArchString(C, Arg

[PATCH] D141078: [CUDA][HIP] Support '--offload-arch=native' for the new driver

2023-01-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 486741.
jhuber6 added a comment.

Change error to use canonical arch string from the triple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141078

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/amdgpu-hip-system-arch.c
  clang/test/Driver/nvptx-cuda-system-arch.c
  clang/test/Driver/openmp-offload-infer.c

Index: clang/test/Driver/openmp-offload-infer.c
===
--- clang/test/Driver/openmp-offload-infer.c
+++ clang/test/Driver/openmp-offload-infer.c
@@ -40,10 +40,10 @@
 // CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
-// RUN: --offload-arch=sm_70 --offload-arch=gfx908 --offload-arch=native \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908 --offload-arch=skylake \
 // RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-FAILED
 
-// CHECK-FAILED: error: failed to deduce triple for target architecture 'native'; specify the triple using '-fopenmp-targets' and '-Xopenmp-target' instead.
+// CHECK-FAILED: error: failed to deduce triple for target architecture 'skylake'; specify the triple using '-fopenmp-targets' and '-Xopenmp-target' instead.
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
 // RUN: --offload-arch=sm_70 --offload-arch=gfx908 -fno-openmp \
Index: clang/test/Driver/nvptx-cuda-system-arch.c
===
--- clang/test/Driver/nvptx-cuda-system-arch.c
+++ clang/test/Driver/nvptx-cuda-system-arch.c
@@ -14,14 +14,20 @@
 // case when nvptx-arch returns nothing or fails
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_fail -x cuda %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-new-driver --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_fail -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
 // NO-OUTPUT-ERROR: error: cannot determine nvptx64 architecture{{.*}}; consider passing it via '--offload-arch'
 
 // case when nvptx_arch does not return anything with successful execution
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_empty -x cuda %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-new-driver --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_empty -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
 // EMPTY-OUTPUT: error: cannot determine nvptx64 architecture: No NVIDIA GPU detected in the system; consider passing it via '--offload-arch'
 
 // case when nvptx_arch does not return anything with successful execution
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_sm_70 -x cuda %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=ARCH-sm_70
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --offload-new-driver --nvptx-arch-tool=%t/nvptx_arch_sm_70 -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=ARCH-sm_70
 // ARCH-sm_70: "-cc1" "-triple" "nvptx64-nvidia-cuda"{{.*}}"-target-cpu" "sm_70"
Index: clang/test/Driver/amdgpu-hip-system-arch.c
===
--- clang/test/Driver/amdgpu-hip-system-arch.c
+++ clang/test/Driver/amdgpu-hip-system-arch.c
@@ -14,14 +14,20 @@
 // case when amdgpu-arch returns nothing or fails
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --amdgpu-arch-tool=%t/amdgpu_arch_fail -x hip %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-new-driver --offload-arch=native --amdgpu-arch-tool=%t/amdgpu_arch_fail -x hip %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
 // NO-OUTPUT-ERROR: error: cannot determine amdgcn architecture{{.*}}; consider passing it via '--offload-arch'
 
 // case when amdgpu_arch does not return anything with successful execution
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --amdgpu-arch-tool=%t/amdgpu_arch_empty -x hip %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-new-driver --offload-arch=native --amdgpu-arch-tool=%t/amdgpu_arch_empty -x hip %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
 // EMPTY-OUTPUT: error: cannot determine amdgcn archit

[PATCH] D136639: [CodeGen][ObjC] Fix a memory leak that occurs when a non-trivial C struct property is set using dot notation

2023-01-05 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

In D136639#4006953 , @rjmccall wrote:

> Oh, I see.  That's a really unfortunate way to end up emitting this code 
> pattern, since ignoring the result is so common.  To fix that, we'd have to 
> either figure out the result was unused in Sema or do a relatively complex 
> analysis in IRGen, though.

`DiagnoseUnusedExprResult` diagnoses unused expressions in Sema, so we can 
modify the `PseudoObjectExpr`s when it's called.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136639

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


[PATCH] D140527: [LoongArch] Add intrinsics for CACOP instruction

2023-01-05 Thread Xiaodong Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9e06d18c80e7: [LoongArch] Add intrinsics for CACOP 
instruction (authored by XiaodongLoong).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140527

Files:
  clang/include/clang/Basic/BuiltinsLoongArch.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/larchintrin.h
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/LoongArch/intrinsic-la32-error.c
  clang/test/CodeGen/LoongArch/intrinsic-la32.c
  clang/test/CodeGen/LoongArch/intrinsic-la64.c
  clang/test/Driver/loongarch-default-features.c
  llvm/include/llvm/IR/IntrinsicsLoongArch.td
  llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
  llvm/lib/Target/LoongArch/LoongArchISelLowering.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
  llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la64.ll

Index: llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
@@ -1,6 +1,7 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s
 
+declare void @llvm.loongarch.cacop.d(i64, i64, i64)
 declare i32 @llvm.loongarch.crc.w.b.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.h.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.w.w(i32, i32)
@@ -46,6 +47,15 @@
   ret i32 %res
 }
 
+define void @cacop_d(i64 %a) nounwind {
+; CHECK-LABEL: cacop_d:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:cacop 1, $a0, 4
+; CHECK-NEXT:ret
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 4)
+  ret void
+}
+
 define i32 @crc_w_d_w(i64 %a, i32 %b) nounwind {
 ; CHECK-LABEL: crc_w_d_w:
 ; CHECK:   # %bb.0:
Index: llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
@@ -1,6 +1,8 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: not llc --mtriple=loongarch64 < %s 2>&1 | FileCheck %s
 
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
+declare void @llvm.loongarch.cacop.d(i64, i64, i64)
 declare i64 @llvm.loongarch.csrrd.d(i32 immarg)
 declare i64 @llvm.loongarch.csrwr.d(i64, i32 immarg)
 declare i64 @llvm.loongarch.csrxchg.d(i64, i64, i32 immarg)
@@ -46,3 +48,37 @@
   %0 = call i64 @llvm.loongarch.csrxchg.d(i64 %a, i64 %b, i32 -1)
   ret i64 %0
 }
+
+define void @cacop_w(i32 %a) nounwind {
+; CHECK: llvm.loongarch.cacop.w requires target: loongarch32
+  call void @llvm.loongarch.cacop.w(i32 1, i32 %a, i32 4)
+  ret void
+}
+
+define void @cacop_arg0_out_of_hi_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 32, i64 %a, i64 1024)
+  ret void
+}
+
+define void @cacop_arg0_out_of_lo_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 -1, i64 %a, i64 1024)
+  ret void
+}
+
+define void @cacop_arg2_out_of_hi_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 4096)
+  ret void
+}
+
+define void @cacop_arg2_out_of_lo_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 -4096)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
@@ -0,0 +1,13 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc --mtriple=loongarch32 < %s | FileCheck %s
+
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
+
+define void @cacop_w(i32 %a) nounwind {
+; CHECK-LABEL: cacop_w:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:cacop 1, $a0, 4
+; CHECK-NEXT:ret
+  call void @llvm.loongarch.cacop.w(i32 1, i32 %a, i32 4)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
@@ -1,5 +1,6 @@
 ; RUN: not llc --mtriple=loongarch32 --disable-verify < %s 2>&1 | FileCheck %s
 
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
 declare i32 @llvm.loongarch.crc.w.b.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.h.w(i32, i

[clang] 9e06d18 - [LoongArch] Add intrinsics for CACOP instruction

2023-01-05 Thread Xiaodong Liu via cfe-commits

Author: Xiaodong Liu
Date: 2023-01-06T11:41:35+08:00
New Revision: 9e06d18c80e77383f0ecdda428e74fbc1df3dd99

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

LOG: [LoongArch] Add intrinsics for CACOP instruction

The CACOP instruction is mainly used for cache initialization
and cache-consistency maintenance.

Depends on D140872

Reviewed By: SixWeining

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

Added: 
llvm/test/CodeGen/LoongArch/intrinsic-la32.ll

Modified: 
clang/include/clang/Basic/BuiltinsLoongArch.def
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Basic/Targets/LoongArch.cpp
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Headers/larchintrin.h
clang/lib/Sema/SemaChecking.cpp
clang/test/CodeGen/LoongArch/intrinsic-la32-error.c
clang/test/CodeGen/LoongArch/intrinsic-la32.c
clang/test/CodeGen/LoongArch/intrinsic-la64.c
clang/test/Driver/loongarch-default-features.c
llvm/include/llvm/IR/IntrinsicsLoongArch.td
llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
llvm/lib/Target/LoongArch/LoongArchISelLowering.h
llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
llvm/test/CodeGen/LoongArch/intrinsic-la64.ll

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsLoongArch.def 
b/clang/include/clang/Basic/BuiltinsLoongArch.def
index cc466cf2703ca..7f2c8403410dd 100644
--- a/clang/include/clang/Basic/BuiltinsLoongArch.def
+++ b/clang/include/clang/Basic/BuiltinsLoongArch.def
@@ -17,6 +17,8 @@
 
 // TODO: Support more builtins.
 // TODO: Added feature constraints.
+TARGET_BUILTIN(__builtin_loongarch_cacop_d, "vLiULiLi", "nc", "64bit")
+TARGET_BUILTIN(__builtin_loongarch_cacop_w, "viUii", "nc", "32bit")
 TARGET_BUILTIN(__builtin_loongarch_dbar, "vIUi", "nc", "")
 TARGET_BUILTIN(__builtin_loongarch_ibar, "vIUi", "nc", "")
 TARGET_BUILTIN(__builtin_loongarch_movfcsr2gr, "UiIUi", "nc", "f")

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 16ab35fcb7a67..c684d3b4a7810 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11764,4 +11764,6 @@ def warn_unsafe_buffer_expression : Warning<
 def warn_unsafe_buffer_variable : Warning<
   "variable %0 participates in unchecked buffer operations">,
   InGroup, DefaultIgnore;
+def err_loongarch_builtin_requires_la32 : Error<
+  "this builtin requires target: loongarch32">;
 } // end of sema component.

diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 5ac94864cebb2..4ce2be8c80742 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -179,6 +179,8 @@ bool LoongArchTargetInfo::initFeatureMap(
 const std::vector &FeaturesVec) const {
   if (getTriple().getArch() == llvm::Triple::loongarch64)
 Features["64bit"] = true;
+  if (getTriple().getArch() == llvm::Triple::loongarch32)
+Features["32bit"] = true;
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
 }

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0afa25da7aee3..fa6128b2a6441 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -19694,6 +19694,12 @@ Value 
*CodeGenFunction::EmitLoongArchBuiltinExpr(unsigned BuiltinID,
   switch (BuiltinID) {
   default:
 llvm_unreachable("unexpected builtin ID.");
+  case LoongArch::BI__builtin_loongarch_cacop_d:
+ID = Intrinsic::loongarch_cacop_d;
+break;
+  case LoongArch::BI__builtin_loongarch_cacop_w:
+ID = Intrinsic::loongarch_cacop_w;
+break;
   case LoongArch::BI__builtin_loongarch_dbar:
 ID = Intrinsic::loongarch_dbar;
 break;

diff  --git a/clang/lib/Headers/larchintrin.h b/clang/lib/Headers/larchintrin.h
index 5edcf4c02a441..c5c533ee0b8c1 100644
--- a/clang/lib/Headers/larchintrin.h
+++ b/clang/lib/Headers/larchintrin.h
@@ -106,6 +106,16 @@ extern __inline int
 
 #define __break(/*ui15*/ _1) __builtin_loongarch_break((_1))
 
+#if __loongarch_grlen == 32
+#define __cacop_w(/*uimm5*/ _1, /*unsigned int*/ _2, /*simm12*/ _3)
\
+  ((void)__builtin_loongarch_cacop_w((_1), (unsigned int)(_2), (_3)))
+#endif
+
+#if __loongarch_grlen == 64
+#define __cacop_d(/*uimm5*/ _1, /*unsigned long int*/ _2, /*simm12*/ _3)   
\
+  ((void)__builtin_loongarch_cacop_d((_1), (unsigned long int)(_2), (_3)))
+#endif
+
 #define __dbar(/*ui15*/ _1) __builtin_loongarch_dbar((_1))
 
 #define __ibar(/*ui15*/ _1) __builtin_loongarch_ibar((_1))

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecki

[PATCH] D141051: [CUDA][HIP] Add support for `--offload-arch=native` to CUDA and refactor

2023-01-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 486739.
jhuber6 added a comment.

Change error to print canonical arch name from Triple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141051

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/AMDGPU.h
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Cuda.h
  clang/test/Driver/Inputs/nvptx-arch/nvptx_arch_fail
  clang/test/Driver/Inputs/nvptx-arch/nvptx_arch_sm_70
  clang/test/Driver/amdgpu-hip-system-arch.c
  clang/test/Driver/amdgpu-openmp-system-arch-fail.c
  clang/test/Driver/nvptx-cuda-system-arch.c

Index: clang/test/Driver/nvptx-cuda-system-arch.c
===
--- /dev/null
+++ clang/test/Driver/nvptx-cuda-system-arch.c
@@ -0,0 +1,27 @@
+// REQUIRES: system-linux
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// REQUIRES: shell
+
+// RUN: mkdir -p %t
+// RUN: cp %S/Inputs/nvptx-arch/nvptx_arch_fail %t/
+// RUN: cp %S/Inputs/nvptx-arch/nvptx_arch_sm_70 %t/
+// RUN: echo '#!/bin/sh' > %t/nvptx_arch_empty
+// RUN: chmod +x %t/nvptx_arch_fail
+// RUN: chmod +x %t/nvptx_arch_sm_70
+// RUN: chmod +x %t/nvptx_arch_empty
+
+// case when nvptx-arch returns nothing or fails
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_fail -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
+// NO-OUTPUT-ERROR: error: cannot determine nvptx64 architecture{{.*}}; consider passing it via '--offload-arch'
+
+// case when nvptx_arch does not return anything with successful execution
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_empty -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
+// EMPTY-OUTPUT: error: cannot determine nvptx64 architecture: No NVIDIA GPU detected in the system; consider passing it via '--offload-arch'
+
+// case when nvptx_arch does not return anything with successful execution
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -nogpulib --offload-arch=native --nvptx-arch-tool=%t/nvptx_arch_sm_70 -x cuda %s 2>&1 \
+// RUN:   | FileCheck %s --check-prefix=ARCH-sm_70
+// ARCH-sm_70: "-cc1" "-triple" "nvptx64-nvidia-cuda"{{.*}}"-target-cpu" "sm_70"
Index: clang/test/Driver/amdgpu-openmp-system-arch-fail.c
===
--- clang/test/Driver/amdgpu-openmp-system-arch-fail.c
+++ clang/test/Driver/amdgpu-openmp-system-arch-fail.c
@@ -15,14 +15,14 @@
 // case when amdgpu_arch returns nothing or fails
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib --amdgpu-arch-tool=%t/amdgpu_arch_fail %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=NO-OUTPUT-ERROR
-// NO-OUTPUT-ERROR: error: cannot determine AMDGPU architecture{{.*}}Exited with error code 1; consider passing it via '--march'
+// NO-OUTPUT-ERROR: error: cannot determine amdgcn architecture{{.*}}; consider passing it via '-march'
 
 // case when amdgpu_arch returns multiple gpus but all are different
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib --amdgpu-arch-tool=%t/amdgpu_arch_different %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=MULTIPLE-OUTPUT-ERROR
-// MULTIPLE-OUTPUT-ERROR: error: cannot determine AMDGPU architecture: Multiple AMD GPUs found with different archs; consider passing it via '--march'
+// MULTIPLE-OUTPUT-ERROR: error: cannot determine amdgcn architecture: Multiple AMD GPUs found with different archs; consider passing it via '-march'
 
 // case when amdgpu_arch does not return anything with successful execution
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib --amdgpu-arch-tool=%t/amdgpu_arch_empty %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=EMPTY-OUTPUT
-// EMPTY-OUTPUT: error: cannot determine AMDGPU architecture: No AMD GPU detected in the system; consider passing it via '--march'
+// EMPTY-OUTPUT: error: cannot determine amdgcn architecture: No AMD GPU detected in the system; consider passing it via '-march'
Index: clang/test/Driver/amdgpu-hip-system-arch.c
===
--- /dev/null
+++ clang/test/Driver/amdgpu-hip-system-arch.c
@@ -0,0 +1,27 @@
+// REQUIRES: system-linux
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+// REQUIRES: shell
+
+// RUN: mkdir -p %t
+// RUN: cp %S/Inputs/amdgpu-arch/amdgpu_arch_fail %t/
+//

[PATCH] D141098: [clang-format][NFC] Set DeriveLineEnding to false in config files

2023-01-05 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel added a comment.

The LLVM Coding Standard apparently doesn't mention line endings..? A quick 
grep does show a bunch of \r\n results, primarily in tests. I'd be in favor of 
forcing \n, but I think this is a wider matter..?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141098

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


[PATCH] D139168: [C++20] [Modules] [ClangScanDeps] Enable to print make-style dependency file within P1689 format (4/4)

2023-01-05 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

>> In what mode will clang output #include information without erroring about 
>> missing .pcm files for import statements? -E -fdirectives-only perhaps? This 
>> further exacerbates the need for "fake" command lines and costs on platforms 
>> with expensive process execution.
>
> After we land D137526 , we are able to do 
> this by: `-M -MF  -E`.

BTW, if you are interested, it should be possible to use clang-scan-deps to get 
the make-style format information.


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

https://reviews.llvm.org/D139168

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


[PATCH] D140312: [clang-format] Disallow decltype in the middle of constraints

2023-01-05 Thread Emilia Dreamer 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 rGd9899501576e: [clang-format] Disallow decltype in the middle 
of constraints (authored by rymiel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140312

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -580,6 +580,14 @@
   EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
   EXPECT_TOKEN(Tokens[11], tok::identifier, TT_FunctionDeclarationName);
 
+  Tokens = annotate("template \n"
+"requires Bar\n"
+"decltype(auto) foo(T) { return false; }");
+  ASSERT_EQ(Tokens.size(), 24u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
+  EXPECT_TOKEN(Tokens[14], tok::identifier, TT_FunctionDeclarationName);
+
   Tokens = annotate("template \n"
 "struct S {\n"
 "  void foo() const requires Bar;\n"
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24199,6 +24199,10 @@
"  }\n"
"};");
 
+  verifyFormat("template \n"
+   "  requires(std::same_as)\n"
+   "decltype(auto) fun() {}");
+
   auto Style = getLLVMStyle();
 
   verifyFormat(
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3543,7 +3543,6 @@
 case tok::minus:
 case tok::star:
 case tok::slash:
-case tok::kw_decltype:
   LambdaNextTimeAllowed = true;
   // Just eat them.
   nextToken();


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -580,6 +580,14 @@
   EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
   EXPECT_TOKEN(Tokens[11], tok::identifier, TT_FunctionDeclarationName);
 
+  Tokens = annotate("template \n"
+"requires Bar\n"
+"decltype(auto) foo(T) { return false; }");
+  ASSERT_EQ(Tokens.size(), 24u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
+  EXPECT_TOKEN(Tokens[14], tok::identifier, TT_FunctionDeclarationName);
+
   Tokens = annotate("template \n"
 "struct S {\n"
 "  void foo() const requires Bar;\n"
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24199,6 +24199,10 @@
"  }\n"
"};");
 
+  verifyFormat("template \n"
+   "  requires(std::same_as)\n"
+   "decltype(auto) fun() {}");
+
   auto Style = getLLVMStyle();
 
   verifyFormat(
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -3543,7 +3543,6 @@
 case tok::minus:
 case tok::star:
 case tok::slash:
-case tok::kw_decltype:
   LambdaNextTimeAllowed = true;
   // Just eat them.
   nextToken();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D140339: [clang-format] Remove special logic for parsing concept definitions.

2023-01-05 Thread Emilia Dreamer 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 rGb1eeec6177fa: [clang-format] Remove special logic for 
parsing concept definitions. (authored by rymiel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140339

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -23588,10 +23588,10 @@
"concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
"&& sizeof(T) <= 8;");
 
-  verifyFormat(
-  "template \n"
-  "concept DelayedCheck = static_cast(0) ||\n"
-  "   requires(T t) { t.bar(); } && sizeof(T) <= 8;");
+  verifyFormat("template \n"
+   "concept DelayedCheck =\n"
+   "static_cast(0) || requires(T t) { t.bar(); } && "
+   "sizeof(T) <= 8;");
 
   verifyFormat("template \n"
"concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
@@ -23599,8 +23599,8 @@
 
   verifyFormat(
   "template \n"
-  "concept DelayedCheck = (bool)(0) ||\n"
-  "   requires(T t) { t.bar(); } && sizeof(T) <= 8;");
+  "concept DelayedCheck =\n"
+  "(bool)(0) || requires(T t) { t.bar(); } && sizeof(T) <= 8;");
 
   verifyFormat("template \n"
"concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
@@ -23636,6 +23636,9 @@
   verifyFormat("template \n"
"concept True = S::Value;");
 
+  verifyFormat("template \n"
+   "concept True = T.field;");
+
   verifyFormat(
   "template \n"
   "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
@@ -23914,11 +23917,9 @@
   verifyFormat("template  concept True = true;", Style);
 
   verifyFormat(
-  "template  concept C = decltype([]() -> std::true_type {\n"
-  "return {};\n"
-  "  }())::value &&\n"
-  "  requires(T t) { t.bar(); } && "
-  "sizeof(T) <= 8;",
+  "template  concept C =\n"
+  "decltype([]() -> std::true_type { return {}; }())::value &&\n"
+  "requires(T t) { t.bar(); } && sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
@@ -23936,21 +23937,20 @@
 
   // The following tests are invalid C++, we just want to make sure we don't
   // assert.
-  verifyFormat("template \n"
-   "concept C = requires C2;");
+  verifyNoCrash("template \n"
+"concept C = requires C2;");
 
-  verifyFormat("template \n"
-   "concept C = 5 + 4;");
+  verifyNoCrash("template \n"
+"concept C = 5 + 4;");
 
-  verifyFormat("template \n"
-   "concept C =\n"
-   "class X;");
+  verifyNoCrash("template \n"
+"concept C = class X;");
 
-  verifyFormat("template \n"
-   "concept C = [] && true;");
+  verifyNoCrash("template \n"
+"concept C = [] && true;");
 
-  verifyFormat("template \n"
-   "concept C = [] && requires(T t) { typename T::size_type; };");
+  verifyNoCrash("template \n"
+"concept C = [] && requires(T t) { typename T::size_type; };");
 }
 
 TEST_F(FormatTest, RequiresClausesPositions) {
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -158,7 +158,6 @@
   void parseAccessSpecifier();
   bool parseEnum();
   bool parseStructLike();
-  void parseConcept();
   bool parseRequires();
   void parseRequiresClause(FormatToken *RequiresToken);
   void parseRequiresExpression(FormatToken *RequiresToken);
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1818,9 +1818,6 @@
 break;
   }
   break;
-case tok::kw_concept:
-  parseConcept();
-  return;
 case tok::kw_requires: {
   if (Style.isCpp()) {
 bool ParsedClause = parseRequires();
@@ -3277,26 +3274,6 @@
   }
 }
 
-/// \brief Parses a concept definition.
-/// \pre The current token has to be the concept keyword.
-///
-/// Returns if either the concept has been completely parsed, or if it detects
-/// that the concept definition is incorrect.
-void UnwrappedLineParser::parseConcept() {
-  assert(FormatTok->is(tok::kw_concept) && "'concept' expected");
-  nextTo

[clang] d989950 - [clang-format] Disallow decltype in the middle of constraints

2023-01-05 Thread Emilia Dreamer via cfe-commits

Author: Emilia Dreamer
Date: 2023-01-06T05:18:28+02:00
New Revision: d9899501576e7b3b8ec4a3f0f855a6bfe68cef88

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

LOG: [clang-format] Disallow decltype in the middle of constraints

If a function with a `requires` clause as a constraint has a decltype
return type, such as `decltype(auto)`, the decltype was seen to be part
of the constraint clause, rather than as part of the function
declaration, causing it to be placed on the wrong line.

This patch disallows decltype to be a part of these clauses

Fixes https://github.com/llvm/llvm-project/issues/59578

Depends on D140339

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 81a6d8ffc0ee..c97ecc782120 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3543,7 +3543,6 @@ void UnwrappedLineParser::parseConstraintExpression() {
 case tok::minus:
 case tok::star:
 case tok::slash:
-case tok::kw_decltype:
   LambdaNextTimeAllowed = true;
   // Just eat them.
   nextToken();

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 21b497bd9568..b2a1e2c57f8c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24199,6 +24199,10 @@ TEST_F(FormatTest, RequiresClauses) {
"  }\n"
"};");
 
+  verifyFormat("template \n"
+   "  requires(std::same_as)\n"
+   "decltype(auto) fun() {}");
+
   auto Style = getLLVMStyle();
 
   verifyFormat(

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 806c75d1e813..dba893dfdd50 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -580,6 +580,14 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
   EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
   EXPECT_TOKEN(Tokens[11], tok::identifier, TT_FunctionDeclarationName);
 
+  Tokens = annotate("template \n"
+"requires Bar\n"
+"decltype(auto) foo(T) { return false; }");
+  ASSERT_EQ(Tokens.size(), 24u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
+  EXPECT_TRUE(Tokens[9]->ClosesRequiresClause);
+  EXPECT_TOKEN(Tokens[14], tok::identifier, TT_FunctionDeclarationName);
+
   Tokens = annotate("template \n"
 "struct S {\n"
 "  void foo() const requires Bar;\n"



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


[clang] b1eeec6 - [clang-format] Remove special logic for parsing concept definitions.

2023-01-05 Thread Emilia Dreamer via cfe-commits

Author: Emilia Dreamer
Date: 2023-01-06T05:17:58+02:00
New Revision: b1eeec6177fafcc433d98c4f46f353b13c68aca0

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

LOG: [clang-format] Remove special logic for parsing concept definitions.

Previously, clang-format relied on a special method to parse concept
definitions, `UnwrappedLineParser::parseConcept()`, which deferred to
`UnwrappedLineParser::parseConstraintExpression()`. This is problematic,
because the C++ grammar treats concepts and requires clauses
differently, causing issues such as 
https://github.com/llvm/llvm-project/issues/55898 and 
https://github.com/llvm/llvm-project/issues/58130.

This patch removes `parseConcept`, letting the formatter parse concept
definitions as more like what they actually are, fancy bool definitions.

NOTE that because of this, some long concept definitions change in their
formatting, as can be seen in the changed tests. This is because of a
change in split penalties, caused by a change in MightBeFunctionDecl on
the concept definition line, which was previously `true` but with this
patch is now `false`.

One might argue that `false` is a more "correct" value for concept
definitions, but I'd be fine with setting it to `true` again to maintain
compatibility with previous versions.

Fixes https://github.com/llvm/llvm-project/issues/58130

Depends on D140330

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 35fa8cf91b33..9dd92c9b08f1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1690,8 +1690,8 @@ class AnnotatingParser {
 if (!Tok)
   return false;
 
-if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
- tok::kw_struct, tok::kw_using)) {
+if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_struct,
+ tok::kw_using)) {
   return false;
 }
 

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 8e1ea0677902..81a6d8ffc0ee 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1818,9 +1818,6 @@ void UnwrappedLineParser::parseStructuralElement(
 break;
   }
   break;
-case tok::kw_concept:
-  parseConcept();
-  return;
 case tok::kw_requires: {
   if (Style.isCpp()) {
 bool ParsedClause = parseRequires();
@@ -3277,26 +3274,6 @@ void UnwrappedLineParser::parseAccessSpecifier() {
   }
 }
 
-/// \brief Parses a concept definition.
-/// \pre The current token has to be the concept keyword.
-///
-/// Returns if either the concept has been completely parsed, or if it detects
-/// that the concept definition is incorrect.
-void UnwrappedLineParser::parseConcept() {
-  assert(FormatTok->is(tok::kw_concept) && "'concept' expected");
-  nextToken();
-  if (!FormatTok->is(tok::identifier))
-return;
-  nextToken();
-  if (!FormatTok->is(tok::equal))
-return;
-  nextToken();
-  parseConstraintExpression();
-  if (FormatTok->is(tok::semi))
-nextToken();
-  addUnwrappedLine();
-}
-
 /// \brief Parses a requires, decides if it is a clause or an expression.
 /// \pre The current token has to be the requires keyword.
 /// \returns true if it parsed a clause.
@@ -3463,6 +3440,8 @@ void UnwrappedLineParser::parseRequiresClause(FormatToken 
*RequiresToken) {
   ? TT_RequiresClauseInARequiresExpression
   : TT_RequiresClause);
 
+  // NOTE: parseConstraintExpression is only ever called from this function.
+  // It could be inlined into here.
   parseConstraintExpression();
 
   if (!InRequiresExpression)
@@ -3496,9 +3475,8 @@ void 
UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) {
 
 /// \brief Parses a constraint expression.
 ///
-/// This is either the definition of a concept, or the body of a requires
-/// clause. It returns, when the parsing is complete, or the expression is
-/// incorrect.
+/// This is the body of a requires clause. It returns, when the parsing is
+/// complete, or the expression is incorrect.
 void UnwrappedLineParser::parseConstraintExpression() {
   // The special handling for lambdas is needed since tryToParseLambda() eats a
   // token and if a requires expression is the last part of a requires clause

diff  --git a/clang/lib/Format/Unwr

[PATCH] D105584: [MLIR][OpenMP] Distribute Construct Operation

2023-01-05 Thread Abid via Phabricator via cfe-commits
abidmalikwaterloo updated this revision to Diff 486732.
abidmalikwaterloo added a comment.

Added a pretty test for omp.distrubute in ops.mlir


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105584

Files:
  mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
  mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
  mlir/test/Dialect/OpenMP/ops.mlir

Index: mlir/test/Dialect/OpenMP/ops.mlir
===
--- mlir/test/Dialect/OpenMP/ops.mlir
+++ mlir/test/Dialect/OpenMP/ops.mlir
@@ -133,6 +133,30 @@
   return
 }
 
+// CHECK-LABEL: omp_DistributeOp
+func.func @omp_DistributeOp(%lb : index, %ub : index, %step : index, %data_var : memref, %chunk_var : i32) -> () {
+// CHECK: for (%{{.*}}) : index = (%{{.*}}) to (%{{.*}}) step (%{{.*}})
+  "omp.distribute" (%lb, %ub, %step) ({
+^bb0(%iv: index):
+ omp.yield 
+  }) {operand_segment_sizes = array} :
+(index, index, index) -> ()
+ 
+ return
+ }
+ 
+// CHECK-LABEL: omp_distribute_pretty
+ func.func @omp_distribute_pretty(%lb : index, %ub : index, %step : index, %data_var : memref, %chunk_var : i32) -> () {
+// CHECK: omp.distribute
+// CHECK-SAME: for (%{{.*}}) : index = (%{{.*}}) to (%{{.*}}) step (%{{.*}})
+  omp.distribute 
+  for (%iv) : index = (%lb) to (%ub) step (%step) {
+omp.yield
+  }
+
+ return
+ }
+ 
 // CHECK-LABEL: omp_wsloop
 func.func @omp_wsloop(%lb : index, %ub : index, %step : index, %data_var : memref, %linear_var : i32, %chunk_var : i32) -> () {
 
@@ -145,7 +169,7 @@
 (index, index, index) -> ()
 
   // CHECK: omp.wsloop linear(%{{.*}} = %{{.*}} : memref) schedule(static)
-  // CHECK-SAMe: for (%{{.*}}) : index = (%{{.*}}) to (%{{.*}}) step (%{{.*}})
+  // CHECK-SAME: for (%{{.*}}) : index = (%{{.*}}) to (%{{.*}}) step (%{{.*}})
   "omp.wsloop" (%lb, %ub, %step, %data_var, %linear_var) ({
 ^bb0(%iv: index):
   omp.yield
Index: mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
===
--- mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -281,6 +281,26 @@
   return success();
 }
 
+//===-===//
+// Verifier for Dristribute Op
+//===-===//
+
+LogicalResult DistributeOp::verify(){
+  if (this->getLowerBound().empty()) 
+return emitOpError() << "empty lowerbound for distribute loop operation";
+  
+  if (this->getUpperBound().empty()) 
+return emitOpError() << "empty upperbound for distribute loop operation";
+  
+  if (this->getLowerBound().size() != this->getUpperBound().size())
+return emitOpError() << "upperbound and lowerbound sizes are not equal";
+
+  if (this->getLowerBound().size() != this->getStep().size())
+return emitOpError() << "upperbound, lowerbound and step sizes are not equal";
+ 	
+  return success();	
+}
+
 /// schedule ::= `schedule` `(` sched-list `)`
 /// sched-list ::= sched-val | sched-val sched-list |
 ///sched-val `,` sched-modifier
@@ -590,7 +610,7 @@
 }
 
 //===--===//
-// WsLoopOp
+// LoopControl
 //===--===//
 
 /// loop-control ::= `(` ssa-id-list `)` `:` type `=`  loop-bounds
Index: mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
===
--- mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -452,7 +452,7 @@
 def YieldOp : OpenMP_Op<"yield",
 [Pure, ReturnLike, Terminator,
  ParentOneOf<["WsLoopOp", "ReductionDeclareOp",
- "AtomicUpdateOp", "SimdLoopOp"]>]> {
+ "AtomicUpdateOp", "SimdLoopOp", "DistributeOp"]>]> {
   let summary = "loop yield and termination operation";
   let description = [{
 "omp.yield" yields SSA values from the OpenMP dialect op region and
@@ -469,6 +469,65 @@
   let assemblyFormat = [{ ( `(` $results^ `:` type($results) `)` )? attr-dict}];
 }
 
+//===--===//
+// 2.9.4.1 distribute Construct
+//===--===//
+
+def DistributeOp : OpenMP_Op<"distribute", [AttrSizedOperandSegments,
+AllTypesMatch<["lowerBound", "upperBound", "step"]>]> {
+  let summary = "distribute loop construct";
+  let description = [{ 
+The distribute construct specifies that the iterations of one or more loop
+will be executed by the initial teams in the context of their implicit 
+tasks. The iterations are distributed across the initial threads of all 
+initial teams that execute the teams region to which the distribute region 
+binds.
+
+The distribute loop construc

[PATCH] D140339: [clang-format] Remove special logic for parsing concept definitions.

2023-01-05 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel marked an inline comment as done.
rymiel added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:23593-23594
-  "template \n"
-  "concept DelayedCheck = static_cast(0) ||\n"
-  "   requires(T t) { t.bar(); } && sizeof(T) <= 8;");
 

owenpan wrote:
> What would happen with parentheses added?
> ```
> concept DelayedCheck = (static_cast(0) || requires(T t) { t.bar(); }) 
> && sizeof(T) <= 8;
> concept DelayedCheck = static_cast(0) || (requires(T t) { t.bar(); } && 
> sizeof(T) <= 8);
> ```
No difference:
```
concept DelayedCheck =
(static_cast(0) || requires(T t) { t.bar(); }) && sizeof(T) <= 8;
concept DelayedCheck =
static_cast(0) || (requires(T t) { t.bar(); } && sizeof(T) <= 8);
concept DelayedCheck =
static_cast(0) || requires(T t) { t.bar(); } && sizeof(T) <= 8;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140339

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


[PATCH] D140767: [clang-format] Require space before noexcept qualifier

2023-01-05 Thread Emilia Dreamer via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG54fab18cedac: [clang-format] Require space before noexcept 
qualifier (authored by rymiel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140767

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10566,10 +10566,10 @@
 
 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("void A::b() && {}");
-  verifyFormat("void A::b() &&noexcept {}");
+  verifyFormat("void A::b() && noexcept {}");
   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
-  verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
+  verifyFormat("Deleted &operator=(const Deleted &) & noexcept = default;");
   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
   verifyFormat("Deleted &operator=(const Deleted &) &;");
@@ -10579,16 +10579,16 @@
   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
-  verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
+  verifyFormat("SomeType MemberFunction(const Deleted &) && noexcept {}");
   verifyFormat("void Fn(T const &) const &;");
   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
-  verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
+  verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;");
   verifyFormat("template \n"
"void F(T) && = delete;",
getGoogleStyle());
   verifyFormat("template  void operator=(T) &;");
   verifyFormat("template  void operator=(T) const &;");
-  verifyFormat("template  void operator=(T) &noexcept;");
+  verifyFormat("template  void operator=(T) & noexcept;");
   verifyFormat("template  void operator=(T) & = default;");
   verifyFormat("template  void operator=(T) &&;");
   verifyFormat("template  void operator=(T) && = delete;");
@@ -10678,31 +10678,31 @@
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) &noexcept {}\n"
+   "  int &foo(const std::string &str) & noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) &&noexcept {}\n"
+   "  int &foo(const std::string &str) && noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) const &noexcept {}\n"
+   "  int &foo(const std::string &str) const & noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) const &noexcept {}\n"
+   "  int &foo(const std::string &str) const & noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
+   "  auto foo(const std::string &str) && noexcept -> int & {}\n"
"};",
BreakTemplate);
 
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3530,7 +3530,8 @@
 if (Right.is(TT_BlockComment))
   return true;
 // foo() -> const Bar * override/final
-if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
+if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final,
+  tok::kw_noexcept) &&
 !Right.is(TT_StartOfName)) {
   return true;
 }


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10566,10 +10566,10 @@
 
 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("void A::b() && {}");
-  verifyFormat("void A::b() &&noexcept {}");
+  verifyFormat("void A::b() && noexcept {}");
   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
-  verifyFormat("Deleted &operator=(cons

[clang] 54fab18 - [clang-format] Require space before noexcept qualifier

2023-01-05 Thread Emilia Dreamer via cfe-commits

Author: Emilia Dreamer
Date: 2023-01-06T05:03:56+02:00
New Revision: 54fab18cedace085344b674ab9de2c93b5fa479b

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

LOG: [clang-format] Require space before noexcept qualifier

This brings the noexcept qualifier more visually in line with the other
keyword qualifiers, such as "final" and "override".

Originally reported as https://github.com/llvm/llvm-project/issues/44542,
it was closed as "working by design" and reinforcing tests were added
as part of a218706cba90248be0c60bd6a8f10dbcf0270955. The exact spacing
depended on the `PointerAlignment` option, where the default value of
`Right` would leave no space.

This patch seeks to change this behaviour, regardless of the configured
`PointerAlignment` option (matching the previous behaviour of the `Left`
option).

Closes https://github.com/llvm/llvm-project/issues/59729

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 3ed0b3d3c6612..35fa8cf91b330 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3530,7 +3530,8 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 if (Right.is(TT_BlockComment))
   return true;
 // foo() -> const Bar * override/final
-if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
+if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final,
+  tok::kw_noexcept) &&
 !Right.is(TT_StartOfName)) {
   return true;
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2265b03f0868a..843e945aeae5b 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10566,10 +10566,10 @@ TEST_F(FormatTest, UnderstandsOverloadedOperators) {
 
 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("void A::b() && {}");
-  verifyFormat("void A::b() &&noexcept {}");
+  verifyFormat("void A::b() && noexcept {}");
   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
-  verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
+  verifyFormat("Deleted &operator=(const Deleted &) & noexcept = default;");
   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
   verifyFormat("Deleted &operator=(const Deleted &) &;");
@@ -10579,16 +10579,16 @@ TEST_F(FormatTest, 
UnderstandsFunctionRefQualification) {
   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
-  verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
+  verifyFormat("SomeType MemberFunction(const Deleted &) && noexcept {}");
   verifyFormat("void Fn(T const &) const &;");
   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
-  verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
+  verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;");
   verifyFormat("template \n"
"void F(T) && = delete;",
getGoogleStyle());
   verifyFormat("template  void operator=(T) &;");
   verifyFormat("template  void operator=(T) const &;");
-  verifyFormat("template  void operator=(T) &noexcept;");
+  verifyFormat("template  void operator=(T) & noexcept;");
   verifyFormat("template  void operator=(T) & = default;");
   verifyFormat("template  void operator=(T) &&;");
   verifyFormat("template  void operator=(T) && = delete;");
@@ -10678,31 +10678,31 @@ TEST_F(FormatTest, 
UnderstandsFunctionRefQualification) {
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) &noexcept {}\n"
+   "  int &foo(const std::string &str) & noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) &&noexcept {}\n"
+   "  int &foo(const std::string &str) && noexcept {}\n"
"};",
BreakTemplate);
 
   verifyFormat("struct f {\n"
"  template \n"
-   "  int &foo(const std::string &str) const &noexcept {}\n"
+   "  int &foo(const std::string &str) co

[PATCH] D138329: [-Wunsafe-buffer-usage] Add a new recursive matcher to replace `forEachDescendant` in unsafe buffer check

2023-01-05 Thread Kirill Stoimenov via Phabricator via cfe-commits
kstoimenov added a comment.

Is it possible these errors are due to your change: 
https://lab.llvm.org/buildbot/#/builders/5/builds/30522/steps/13/logs/stdio? If 
so please consider reverting/fixing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138329

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


[PATCH] D141058: [clang-tidy] fix wrong fixup for bugprone-implicit-widening-of-multiplication-result

2023-01-05 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry marked 2 inline comments as done.
v1nh1shungry added a comment.

Thank you for reviewing and giving suggestions! @Eugene.Zelenko


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141058

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


[PATCH] D141058: [clang-tidy] fix wrong fixup for bugprone-implicit-widening-of-multiplication-result

2023-01-05 Thread Vincent Hong via Phabricator via cfe-commits
v1nh1shungry updated this revision to Diff 486729.
v1nh1shungry added a comment.

don't use `auto`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141058

Files:
  
clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-array-subscript-expression.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-int.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-pointer-offset.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-pointer-offset.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-pointer-offset.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-pointer-offset.cpp
@@ -18,7 +18,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:17: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(ptrdiff_t)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 char *t1(char *base, int a, int b) {
   return a * b + base;
@@ -35,7 +35,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:17: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(size_t)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 
 char *t3(char *base, int a, unsigned int b) {
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-int.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-int.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-int.cpp
@@ -18,7 +18,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:10: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(long)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 unsigned long t1(int a, int b) {
   return a * b;
@@ -28,7 +28,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:10: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(long)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 
 long t2(unsigned int a, int b) {
@@ -39,7 +39,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:10: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(unsigned long)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 unsigned long t3(unsigned int a, int b) {
   return a * b;
@@ -49,7 +49,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:10: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(unsigned long)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 
 long t4(int a, unsigned int b) {
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-array-subscript-expression.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-array-subscript-expression.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/implicit-widening-of-multiplication-result-array-subscript-expression.cpp
@@ -18,7 +18,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:16: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(ptrdiff_t)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 void *t1(char *base, int a, int b) {
   return &((a * b)[base]);
@@ -35,7 +35,7 @@
   // CHECK-NOTES-CXX:  static_cast( )
   // CHECK-NOTES-ALL: :[[@LINE-5]]:16: note: perform multiplication in a wider type
   // CHECK-NOTES-C:(size_t)
-  // CHECK-NOTES-CXX:  static_cast()
+  // CHECK-NOTES-CXX:  static_cast( )
 }
 
 char *t3(char *base, int a, unsigned int b) {
Index: clang-tools-extra/clang-tidy/bugprone/ImplicitW

[PATCH] D139168: [C++20] [Modules] [ClangScanDeps] Enable to print make-style dependency file within P1689 format (4/4)

2023-01-05 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

> IMO, this is not suitable; there must be *one* depfile for Ninja to work 
> (otherwise build tools will need to manually collate all of this into one for 
> ninja.

Yeah, but the producer of the compilation database is able to create a 
compilation db with the same `-MF` option. Do you mean you will feel much 
better that the clang-scan-deps will have a strong check?

>> 2. (The original way) Specify -MF in the command line of clang-scan-deps.
>
> I feel this scales and communicates what is happening much better because it 
> actually is a flag for clang-scan-deps itself.

There is a related problem that how do we set the target of the dependency? In 
per file mode, we can easily specify it in the command line of clang-scan-deps. 
But we have to extract them ("-MT") from the command line with compilation 
database. (Otherwise all the targets have the same name, which is incorrect). 
Do you think it is acceptable?

> In what mode will clang output #include information without erroring about 
> missing .pcm files for import statements? -E -fdirectives-only perhaps? This 
> further exacerbates the need for "fake" command lines and costs on platforms 
> with expensive process execution.

After we land D137526 , we are able to do 
this by: `-M -MF  -E`.


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

https://reviews.llvm.org/D139168

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


[clang] 7f56488 - Fix for tests on Windows buildbot

2023-01-05 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2023-01-05T21:25:32-05:00
New Revision: 7f564882466787e5b93c9253d7dbcaf6ebd82f95

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

LOG: Fix for tests on Windows buildbot

Added: 


Modified: 
clang/test/Driver/netbsd.c
clang/test/Driver/netbsd.cpp

Removed: 




diff  --git a/clang/test/Driver/netbsd.c b/clang/test/Driver/netbsd.c
index b59acf144fbc6..5d76aac525d9e 100644
--- a/clang/test/Driver/netbsd.c
+++ b/clang/test/Driver/netbsd.c
@@ -483,4 +483,4 @@
 // RUN:   | FileCheck %s --check-prefix=DRIVER-PASS-INCLUDES
 // DRIVER-PASS-INCLUDES:  "-cc1" {{.*}}"-resource-dir" "[[RESOURCE:[^"]+]]"
 // DRIVER-PASS-INCLUDES-SAME: {{^}} "-internal-isystem" 
"[[RESOURCE]]{{/|}}include"
-// DRIVER-PASS-INCLUDES-SAME: {{^}} "-internal-externc-isystem" "/usr/include"
+// DRIVER-PASS-INCLUDES-SAME: {{^}} "-internal-externc-isystem" 
"{{.*}}/usr/include"

diff  --git a/clang/test/Driver/netbsd.cpp b/clang/test/Driver/netbsd.cpp
index d6bd4a3c2dd87..ffc33e33700eb 100644
--- a/clang/test/Driver/netbsd.cpp
+++ b/clang/test/Driver/netbsd.cpp
@@ -345,4 +345,4 @@
 // RUN:   | FileCheck %s --check-prefix=DRIVER-PASS-INCLUDES
 // DRIVER-PASS-INCLUDES:  "-cc1" {{.*}}"-resource-dir" "[[RESOURCE:[^"]+]]"
 // DRIVER-PASS-INCLUDES:  "-internal-isystem" 
"[[RESOURCE]]{{/|}}include"
-// DRIVER-PASS-INCLUDES:  "-internal-externc-isystem" "/usr/include"
+// DRIVER-PASS-INCLUDES:  "-internal-externc-isystem" "{{.*}}/usr/include"



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


[clang] 8fd279f - [Driver] move Fuchsia header search path management to the driver

2023-01-05 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2023-01-05T21:21:08-05:00
New Revision: 8fd279f7d369d6acdea7c0bd60c40bbc8c6beb06

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

LOG: [Driver] move Fuchsia header search path management to the driver

Fuchsia already implements AddClangSystemIncludeArgs(). So it looks like we
just have to switch over to using it.

Reviewed By: phosek

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

Added: 


Modified: 
clang/lib/Lex/InitHeaderSearch.cpp

Removed: 




diff  --git a/clang/lib/Lex/InitHeaderSearch.cpp 
b/clang/lib/Lex/InitHeaderSearch.cpp
index 8dc5d95f9c6b0..d55746b346214 100644
--- a/clang/lib/Lex/InitHeaderSearch.cpp
+++ b/clang/lib/Lex/InitHeaderSearch.cpp
@@ -235,7 +235,6 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const 
llvm::Triple &triple,
 case llvm::Triple::PS4:
 case llvm::Triple::PS5:
 case llvm::Triple::ELFIAMCU:
-case llvm::Triple::Fuchsia:
   break;
 case llvm::Triple::Win32:
   if (triple.getEnvironment() != llvm::Triple::Cygnus)
@@ -338,7 +337,6 @@ void InitHeaderSearch::AddDefaultCIncludePaths(const 
llvm::Triple &triple,
   case llvm::Triple::RTEMS:
   case llvm::Triple::NaCl:
   case llvm::Triple::ELFIAMCU:
-  case llvm::Triple::Fuchsia:
 break;
   case llvm::Triple::PS4:
   case llvm::Triple::PS5: {
@@ -413,6 +411,7 @@ bool InitHeaderSearch::ShouldAddDefaultIncludePaths(
   case llvm::Triple::FreeBSD:
   case llvm::Triple::NetBSD:
   case llvm::Triple::OpenBSD:
+  case llvm::Triple::Fuchsia:
   case llvm::Triple::Hurd:
   case llvm::Triple::Linux:
   case llvm::Triple::Solaris:



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


[PATCH] D141073: [Driver] move Fuchsia header search path management to the driver

2023-01-05 Thread Brad Smith 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 rG8fd279f7d369: [Driver] move Fuchsia header search path 
management to the driver (authored by brad).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141073

Files:
  clang/lib/Lex/InitHeaderSearch.cpp


Index: clang/lib/Lex/InitHeaderSearch.cpp
===
--- clang/lib/Lex/InitHeaderSearch.cpp
+++ clang/lib/Lex/InitHeaderSearch.cpp
@@ -235,7 +235,6 @@
 case llvm::Triple::PS4:
 case llvm::Triple::PS5:
 case llvm::Triple::ELFIAMCU:
-case llvm::Triple::Fuchsia:
   break;
 case llvm::Triple::Win32:
   if (triple.getEnvironment() != llvm::Triple::Cygnus)
@@ -338,7 +337,6 @@
   case llvm::Triple::RTEMS:
   case llvm::Triple::NaCl:
   case llvm::Triple::ELFIAMCU:
-  case llvm::Triple::Fuchsia:
 break;
   case llvm::Triple::PS4:
   case llvm::Triple::PS5: {
@@ -413,6 +411,7 @@
   case llvm::Triple::FreeBSD:
   case llvm::Triple::NetBSD:
   case llvm::Triple::OpenBSD:
+  case llvm::Triple::Fuchsia:
   case llvm::Triple::Hurd:
   case llvm::Triple::Linux:
   case llvm::Triple::Solaris:


Index: clang/lib/Lex/InitHeaderSearch.cpp
===
--- clang/lib/Lex/InitHeaderSearch.cpp
+++ clang/lib/Lex/InitHeaderSearch.cpp
@@ -235,7 +235,6 @@
 case llvm::Triple::PS4:
 case llvm::Triple::PS5:
 case llvm::Triple::ELFIAMCU:
-case llvm::Triple::Fuchsia:
   break;
 case llvm::Triple::Win32:
   if (triple.getEnvironment() != llvm::Triple::Cygnus)
@@ -338,7 +337,6 @@
   case llvm::Triple::RTEMS:
   case llvm::Triple::NaCl:
   case llvm::Triple::ELFIAMCU:
-  case llvm::Triple::Fuchsia:
 break;
   case llvm::Triple::PS4:
   case llvm::Triple::PS5: {
@@ -413,6 +411,7 @@
   case llvm::Triple::FreeBSD:
   case llvm::Triple::NetBSD:
   case llvm::Triple::OpenBSD:
+  case llvm::Triple::Fuchsia:
   case llvm::Triple::Hurd:
   case llvm::Triple::Linux:
   case llvm::Triple::Solaris:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D141073: [Driver] move Fuchsia header search path management to the driver

2023-01-05 Thread Petr Hosek via Phabricator via cfe-commits
phosek accepted this revision.
phosek added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141073

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


[PATCH] D137058: [Driver] [Modules] Support -fmodule-output (1/2)

2023-01-05 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

@dblaikie would you like to take a look at this?


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

https://reviews.llvm.org/D137058

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


[PATCH] D140927: [C++20][Modules] Fix named module import diagnostics.

2023-01-05 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140927

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


[PATCH] D140527: [LoongArch] Add intrinsics for CACOP instruction

2023-01-05 Thread Xiaodong Liu via Phabricator via cfe-commits
XiaodongLoong updated this revision to Diff 486725.
XiaodongLoong added a comment.

rebase code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140527

Files:
  clang/include/clang/Basic/BuiltinsLoongArch.def
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/larchintrin.h
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/LoongArch/intrinsic-la32-error.c
  clang/test/CodeGen/LoongArch/intrinsic-la32.c
  clang/test/CodeGen/LoongArch/intrinsic-la64.c
  clang/test/Driver/loongarch-default-features.c
  llvm/include/llvm/IR/IntrinsicsLoongArch.td
  llvm/lib/Target/LoongArch/LoongArchISelLowering.cpp
  llvm/lib/Target/LoongArch/LoongArchISelLowering.h
  llvm/lib/Target/LoongArch/LoongArchInstrInfo.td
  llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
  llvm/test/CodeGen/LoongArch/intrinsic-la64.ll

Index: llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la64.ll
@@ -1,6 +1,7 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: llc --mtriple=loongarch64 < %s | FileCheck %s
 
+declare void @llvm.loongarch.cacop.d(i64, i64, i64)
 declare i32 @llvm.loongarch.crc.w.b.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.h.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.w.w(i32, i32)
@@ -46,6 +47,15 @@
   ret i32 %res
 }
 
+define void @cacop_d(i64 %a) nounwind {
+; CHECK-LABEL: cacop_d:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:cacop 1, $a0, 4
+; CHECK-NEXT:ret
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 4)
+  ret void
+}
+
 define i32 @crc_w_d_w(i64 %a, i32 %b) nounwind {
 ; CHECK-LABEL: crc_w_d_w:
 ; CHECK:   # %bb.0:
Index: llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la64-error.ll
@@ -1,6 +1,8 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
 ; RUN: not llc --mtriple=loongarch64 < %s 2>&1 | FileCheck %s
 
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
+declare void @llvm.loongarch.cacop.d(i64, i64, i64)
 declare i64 @llvm.loongarch.csrrd.d(i32 immarg)
 declare i64 @llvm.loongarch.csrwr.d(i64, i32 immarg)
 declare i64 @llvm.loongarch.csrxchg.d(i64, i64, i32 immarg)
@@ -46,3 +48,37 @@
   %0 = call i64 @llvm.loongarch.csrxchg.d(i64 %a, i64 %b, i32 -1)
   ret i64 %0
 }
+
+define void @cacop_w(i32 %a) nounwind {
+; CHECK: llvm.loongarch.cacop.w requires target: loongarch32
+  call void @llvm.loongarch.cacop.w(i32 1, i32 %a, i32 4)
+  ret void
+}
+
+define void @cacop_arg0_out_of_hi_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 32, i64 %a, i64 1024)
+  ret void
+}
+
+define void @cacop_arg0_out_of_lo_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 -1, i64 %a, i64 1024)
+  ret void
+}
+
+define void @cacop_arg2_out_of_hi_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 4096)
+  ret void
+}
+
+define void @cacop_arg2_out_of_lo_range(i64 %a) nounwind {
+; CHECK: argument to 'llvm.loongarch.cacop.d' out of range
+entry:
+  call void @llvm.loongarch.cacop.d(i64 1, i64 %a, i64 -4096)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
===
--- /dev/null
+++ llvm/test/CodeGen/LoongArch/intrinsic-la32.ll
@@ -0,0 +1,13 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc --mtriple=loongarch32 < %s | FileCheck %s
+
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
+
+define void @cacop_w(i32 %a) nounwind {
+; CHECK-LABEL: cacop_w:
+; CHECK:   # %bb.0:
+; CHECK-NEXT:cacop 1, $a0, 4
+; CHECK-NEXT:ret
+  call void @llvm.loongarch.cacop.w(i32 1, i32 %a, i32 4)
+  ret void
+}
Index: llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
===
--- llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
+++ llvm/test/CodeGen/LoongArch/intrinsic-la32-error.ll
@@ -1,5 +1,6 @@
 ; RUN: not llc --mtriple=loongarch32 --disable-verify < %s 2>&1 | FileCheck %s
 
+declare void @llvm.loongarch.cacop.w(i32, i32, i32)
 declare i32 @llvm.loongarch.crc.w.b.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.h.w(i32, i32)
 declare i32 @llvm.loongarch.crc.w.w.w(i32, i32)
@@ -18,6 +19,34 @@
 declare i64 @ll

[PATCH] D140307: [clang-tidy] Match derived types in in modernize-loop-convert

2023-01-05 Thread Chris Cotter via Phabricator via cfe-commits
ccotter marked an inline comment as done.
ccotter added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp:258
+   hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
+   hasMethod(cxxMethodDecl(hasName("end"),
+   isConst())) // 
hasDeclaration

ccotter wrote:
> carlosgalvezp wrote:
> > Replace tabs with spaces
> Ah, I think this was before I figured out `arc diff` and was copy/pasting 
> diff files around :/
> 
> Thanks for catching this.
just to confirm, how did you notice the tabs? I couldnt find them when I 
downloaded the phab raw diff for any of the versions in the history. I still 
see a double right arrow `»` in the phab diff - is that indicating a tab or 
something else?

As a sanity check, I ran `./clang/tools/clang-format/git-clang-format --binary 
build/bin/clang-format` from the root of my project and the tool did not 
produce any changes with the latest version of the changes I submitted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140307

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


[PATCH] D141070: [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

2023-01-05 Thread Brad Smith 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 rGf70d17fc2c10: [LoongArch] Define 
__GCC_HAVE_SYNC_COMPARE_AND_SWAP macros (authored by brad).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141070

Files:
  clang/lib/Basic/Targets/LoongArch.cpp
  clang/test/Preprocessor/init-loongarch.c
  clang/test/Preprocessor/predefined-arch-macros.c


Index: clang/test/Preprocessor/predefined-arch-macros.c
===
--- clang/test/Preprocessor/predefined-arch-macros.c
+++ clang/test/Preprocessor/predefined-arch-macros.c
@@ -4372,3 +4372,20 @@
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
+
+// Begin LoongArch tests 
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch32-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA32_ATOMICS
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA64_ATOMICS
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
Index: clang/test/Preprocessor/init-loongarch.c
===
--- clang/test/Preprocessor/init-loongarch.c
+++ clang/test/Preprocessor/init-loongarch.c
@@ -81,6 +81,9 @@
 // LA32: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
 // LA32: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
 // LA32: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
 // LA32: #define __ILP32__ 1
 // LA32: #define __INT16_C_SUFFIX__
 // LA32: #define __INT16_FMTd__ "hd"
@@ -394,6 +397,10 @@
 // LA64: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
 // LA64: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
 // LA64: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
 // LA64: #define __INT16_C_SUFFIX__
 // LA64: #define __INT16_FMTd__ "hd"
 // LA64: #define __INT16_FMTi__ "hi"
Index: clang/lib/Basic/Targets/LoongArch.cpp
===
--- clang/lib/Basic/Targets/LoongArch.cpp
+++ clang/lib/Basic/Targets/LoongArch.cpp
@@ -158,6 +158,12 @@
   } else if (ABI == "lp64s" || ABI == "ilp32s") {
 Builder.defineMacro("__loongarch_soft_float");
   }
+
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
+  if (GRLen == 64)
+Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
 }
 
 static constexpr Builtin::Info BuiltinInfo[] = {


Index: clang/test/Preprocessor/predefined-arch-macros.c
===
--- clang/test/Preprocessor/predefined-arch-macros.c
+++ clang/test/Preprocessor/predefined-arch-macros.c
@@ -4372,3 +4372,20 @@
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
+
+// Begin LoongArch tests 
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch32-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA32_ATOMICS
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA64_ATOMICS
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
I

[clang] f70d17f - [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

2023-01-05 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2023-01-05T20:21:22-05:00
New Revision: f70d17fc2c10381682123c5f8766bd59c27dfbdd

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

LOG: [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

Reviewed By: SixWeining, MaskRay

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

Added: 


Modified: 
clang/lib/Basic/Targets/LoongArch.cpp
clang/test/Preprocessor/init-loongarch.c
clang/test/Preprocessor/predefined-arch-macros.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index 75e3d503ad24..5ac94864cebb 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -158,6 +158,12 @@ void LoongArchTargetInfo::getTargetDefines(const 
LangOptions &Opts,
   } else if (ABI == "lp64s" || ABI == "ilp32s") {
 Builder.defineMacro("__loongarch_soft_float");
   }
+
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
+  Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
+  if (GRLen == 64)
+Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
 }
 
 static constexpr Builtin::Info BuiltinInfo[] = {

diff  --git a/clang/test/Preprocessor/init-loongarch.c 
b/clang/test/Preprocessor/init-loongarch.c
index b7b84d42d4ec..686c9681361e 100644
--- a/clang/test/Preprocessor/init-loongarch.c
+++ b/clang/test/Preprocessor/init-loongarch.c
@@ -81,6 +81,9 @@
 // LA32: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
 // LA32: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
 // LA32: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// LA32: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
 // LA32: #define __ILP32__ 1
 // LA32: #define __INT16_C_SUFFIX__
 // LA32: #define __INT16_FMTd__ "hd"
@@ -394,6 +397,10 @@
 // LA64: #define __GCC_ATOMIC_SHORT_LOCK_FREE 2
 // LA64: #define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
 // LA64: #define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+// LA64: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
 // LA64: #define __INT16_C_SUFFIX__
 // LA64: #define __INT16_FMTd__ "hd"
 // LA64: #define __INT16_FMTi__ "hi"

diff  --git a/clang/test/Preprocessor/predefined-arch-macros.c 
b/clang/test/Preprocessor/predefined-arch-macros.c
index 259ce1b47171..1b1afd6c2238 100644
--- a/clang/test/Preprocessor/predefined-arch-macros.c
+++ b/clang/test/Preprocessor/predefined-arch-macros.c
@@ -4372,3 +4372,20 @@
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
 // CHECK_WASM_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
+
+// Begin LoongArch tests 
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch32-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA32_ATOMICS
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA32_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+
+// RUN: %clang -E -dM %s -o - 2>&1 \
+// RUN: --target=loongarch64-unknown-linux-gnu \
+// RUN:   | FileCheck -match-full-lines %s -check-prefix=CHECK_LA64_ATOMICS
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
+// CHECK_LA64_ATOMICS: #define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1



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


[PATCH] D140307: [clang-tidy] Match derived types in in modernize-loop-convert

2023-01-05 Thread Chris Cotter via Phabricator via cfe-commits
ccotter marked 2 inline comments as done.
ccotter added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp:258
+   hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
+   hasMethod(cxxMethodDecl(hasName("end"),
+   isConst())) // 
hasDeclaration

carlosgalvezp wrote:
> Replace tabs with spaces
Ah, I think this was before I figured out `arc diff` and was copy/pasting diff 
files around :/

Thanks for catching this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140307

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


[PATCH] D141070: [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

2023-01-05 Thread Lu Weining via Phabricator via cfe-commits
SixWeining accepted this revision.
SixWeining added a comment.

This matches LoongArch gcc's  behavior.  So LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141070

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


[PATCH] D140307: [clang-tidy] Match derived types in in modernize-loop-convert

2023-01-05 Thread Chris Cotter via Phabricator via cfe-commits
ccotter updated this revision to Diff 486716.
ccotter added a comment.

- Match derived types in in modernize-loop-convert
- fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140307

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/loop-convert/structures.h
  clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -575,6 +575,7 @@
 const dependent *Pconstv;
 
 transparent> Cv;
+dependent_derived VD;
 
 void f() {
   int Sum = 0;
@@ -653,6 +654,15 @@
   // CHECK-FIXES: for (int I : V)
   // CHECK-FIXES-NEXT: printf("Fibonacci number is %d\n", I);
   // CHECK-FIXES-NEXT: Sum += I + 2;
+
+  for (int I = 0, E = VD.size(); E != I; ++I) {
+printf("Fibonacci number is %d\n", VD[I]);
+Sum += VD[I] + 2;
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop instead
+  // CHECK-FIXES: for (int I : VD)
+  // CHECK-FIXES-NEXT: printf("Fibonacci number is %d\n", I);
+  // CHECK-FIXES-NEXT: Sum += I + 2;
 }
 
 // Ensure that 'const auto &' is used with containers of non-trivial types.
Index: 
clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/loop-convert/structures.h
===
--- 
clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/loop-convert/structures.h
+++ 
clang-tools-extra/test/clang-tidy/checkers/modernize/Inputs/loop-convert/structures.h
@@ -126,6 +126,10 @@
   void constFoo() const;
 };
 
+template
+class dependent_derived : public dependent {
+};
+
 template
 class doublyDependent{
  public:
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -204,6 +204,10 @@
   The check now skips concept definitions since redundant expressions still 
make sense
   inside them.
 
+- Improved :doc:`modernize-loop-convert 
`
+  to check for container functions ``begin``/``end`` etc on base classes of 
the container
+  type, instead of only as direct members of the container type itself.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -251,17 +251,18 @@
   // functions called begin() and end() taking the container as an argument
   // are also allowed.
   TypeMatcher RecordWithBeginEnd = qualType(anyOf(
-  qualType(
-  isConstQualified(),
-  hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl(
-  hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
-  hasMethod(cxxMethodDecl(hasName("end"),
-  isConst()   // hasDeclaration
- ))), // qualType
+  qualType(isConstQualified(),
+   hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+   cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
+   hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
+   hasMethod(cxxMethodDecl(hasName("end"),
+   isConst())) // 
hasDeclaration
+  ))), // qualType
   qualType(unless(isConstQualified()),
hasUnqualifiedDesugaredType(recordType(hasDeclaration(
-   cxxRecordDecl(hasMethod(hasName("begin")),
- hasMethod(hasName("end"))) // qualType
+   cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
+   hasMethod(hasName("begin")),
+   hasMethod(hasName("end") // qualType
   ));
 
   StatementMatcher SizeCallMatcher = cxxMemberCallExpr(


Index: clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize/loop-convert-basic.cpp
@@ -575,6 +575,7 @@
 const dependent *Pconstv;
 
 transparent> Cv;
+dependent_derived VD;
 
 void f() {
   int Sum = 0;
@@ -653,6 +654,15 @@
   // CHECK-FIXES: for (int I : V)
   // CHECK-FIXES-NEXT: printf("Fib

[PATCH] D80392: [mips][mc][clang] Use pc-relative relocations in .eh_frame

2023-01-05 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D80392#4028011 , @wzssyqa wrote:

> When link with ld.bfd, we get:
>
>   ld/ld-new: .eh_frame_hdr entry overflow
>   ld/ld-new: final link failed: bad value
>
> It seems due to the `initial_loc` in the object from LLVM is quite big than 
> the gcc/gas one.
>
>   initial_loc: 0x10cd0, vma: 0xe78

I have some notes on 
https://maskray.me/blog/2020-11-08-stack-unwinding#dwarf-call-frame-information
(See 
https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic.pdf)
Different targets may use different encoding for the `initial_location` field.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80392

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


[clang] 2b1a517 - Revert "[clang][dataflow] Only model struct fields that are used in the function being analyzed."

2023-01-05 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2023-01-06T01:07:28Z
New Revision: 2b1a517a92bfdfa3b692a660e19a2bb22513a567

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

LOG: Revert "[clang][dataflow] Only model struct fields that are used in the 
function being analyzed."

This reverts commit 5e8f597c2fedc740b71f07dfdb1ef3c2d348b193. It caused msan 
and ubsan breakages.

Added: 


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

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index 98135508aabb..f8ee5864482b 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -54,21 +54,14 @@ llvm::DenseSet getObjectFields(QualType 
Type);
 /// is used during dataflow analysis.
 class DataflowAnalysisContext {
 public:
-  // FIXME: merge with TransferOptions from Transfer.h.
-  struct Options {
-bool EnableContextSensitiveAnalysis;
-  };
-
   /// Constructs a dataflow analysis context.
   ///
   /// Requirements:
   ///
   ///  `S` must not be null.
-  DataflowAnalysisContext(std::unique_ptr S,
-  Options Opts = {
-  /*EnableContextSensitiveAnalysis=*/false})
+  DataflowAnalysisContext(std::unique_ptr S)
   : S(std::move(S)), TrueVal(createAtomicBoolValue()),
-FalseVal(createAtomicBoolValue()), Options(Opts) {
+FalseVal(createAtomicBoolValue()) {
 assert(this->S != nullptr);
   }
 
@@ -260,11 +253,7 @@ class DataflowAnalysisContext {
   /// returns null.
   const ControlFlowContext *getControlFlowContext(const FunctionDecl *F);
 
-  void addFieldsReferencedInScope(llvm::DenseSet Fields);
-
 private:
-  friend class Environment;
-
   struct NullableQualTypeDenseMapInfo : private llvm::DenseMapInfo {
 static QualType getEmptyKey() {
   // Allow a NULL `QualType` by using a 
diff erent value as the empty key.
@@ -276,10 +265,6 @@ class DataflowAnalysisContext {
 using DenseMapInfo::isEqual;
   };
 
-  /// Returns the subset of fields of `Type` that are referenced in the scope 
of
-  /// the analysis.
-  llvm::DenseSet getReferencedFields(QualType Type);
-
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used
   /// to track tokens of flow conditions that were already visited by recursive
@@ -345,8 +330,6 @@ class DataflowAnalysisContext {
   AtomicBoolValue &TrueVal;
   AtomicBoolValue &FalseVal;
 
-  Options Options;
-
   // Indices that are used to avoid recreating the same composite boolean
   // values.
   llvm::DenseMap, ConjunctionValue *>
@@ -376,9 +359,6 @@ class DataflowAnalysisContext {
   llvm::DenseMap FlowConditionConstraints;
 
   llvm::DenseMap FunctionContexts;
-
-  // All fields referenced (statically) in the scope of the analysis.
-  llvm::DenseSet FieldsReferencedInScope;
 };
 
 } // namespace dataflow

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index fbc5f6d2c889..c1653c2ab4ed 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -452,9 +452,6 @@ class Environment {
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
-  /// Assigns storage locations and values to all variables in `Vars`.
-  void initVars(llvm::DenseSet Vars);
-
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
index 6b7b2dc8912b..af2f1fcbe24e 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -16,7 +16,6 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/Analysis/FlowSensitive/DebugSupport.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
-#include "llvm/ADT/SetOperations.h"
 #include "llvm/Support/Debug.h"
 #include 
 #inclu

[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

I'll revert now and take a look in the morning...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

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


[PATCH] D136651: [Clang] Give Clang the ability to use a shared stat cache

2023-01-05 Thread Frederic Riss via Phabricator via cfe-commits
friss added a comment.

In D136651#4030008 , @benlangmuir 
wrote:

> Re-added a few of my minor comments that I think got lost on a specific 
> version of the diff. Otherwise LGTM.

Sorry for missing these. I think I addressed all of them now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136651

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


[PATCH] D136651: [Clang] Give Clang the ability to use a shared stat cache

2023-01-05 Thread Frederic Riss via Phabricator via cfe-commits
friss updated this revision to Diff 486711.
friss added a comment.

Fix Windows build (Thanks @ravi-ramaseshan)
Address @benlangmuir comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136651

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/CompilerInvocation.h
  clang/include/clang/Lex/HeaderSearchOptions.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CMakeLists.txt
  clang/test/Driver/vfsstatcache.c
  clang/test/clang-stat-cache/cache-effects.c
  clang/test/clang-stat-cache/errors.test
  clang/tools/CMakeLists.txt
  clang/tools/clang-stat-cache/CMakeLists.txt
  clang/tools/clang-stat-cache/clang-stat-cache.cpp
  llvm/include/llvm/Support/StatCacheFileSystem.h
  llvm/lib/Support/CMakeLists.txt
  llvm/lib/Support/StatCacheFileSystem.cpp
  llvm/unittests/Support/VirtualFileSystemTest.cpp

Index: llvm/unittests/Support/VirtualFileSystemTest.cpp
===
--- llvm/unittests/Support/VirtualFileSystemTest.cpp
+++ llvm/unittests/Support/VirtualFileSystemTest.cpp
@@ -14,9 +14,11 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/StatCacheFileSystem.h"
 #include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 #include 
 
@@ -3228,3 +3230,306 @@
 "  DummyFileSystem (RecursiveContents)\n",
 Output);
 }
+
+class StatCacheFileSystemTest : public ::testing::Test {
+public:
+  void SetUp() override {}
+
+  template 
+  void createStatCacheFileSystem(
+  StringRef OutputFile, StringRef BaseDir, bool IsCaseSensitive,
+  IntrusiveRefCntPtr &Result,
+  StringCollection &Filenames,
+  IntrusiveRefCntPtr Lower = new ErrorDummyFileSystem(),
+  uint64_t ValidityToken = 0) {
+sys::fs::file_status s;
+status(BaseDir, s);
+vfs::StatCacheFileSystem::StatCacheWriter Generator(
+BaseDir, s, IsCaseSensitive, ValidityToken);
+std::error_code ErrorCode;
+
+Result.reset();
+
+// Base path should be present in the stat cache.
+Filenames.push_back(std::string(BaseDir));
+
+for (sys::fs::recursive_directory_iterator I(BaseDir, ErrorCode), E;
+ I != E && !ErrorCode; I.increment(ErrorCode)) {
+  Filenames.push_back(I->path());
+  StringRef Path(Filenames.back().c_str());
+  status(Path, s);
+  Generator.addEntry(Path, s);
+}
+
+{
+  raw_fd_ostream StatCacheFile(OutputFile, ErrorCode);
+  ASSERT_FALSE(ErrorCode);
+  Generator.writeStatCache(StatCacheFile);
+}
+
+loadCacheFile(OutputFile, ValidityToken, Lower, Result);
+  }
+
+  void loadCacheFile(StringRef OutputFile, uint64_t ExpectedValidityToken,
+ IntrusiveRefCntPtr Lower,
+ IntrusiveRefCntPtr &Result) {
+auto ErrorOrBuffer = MemoryBuffer::getFile(OutputFile);
+EXPECT_TRUE(ErrorOrBuffer);
+StringRef CacheBaseDir;
+bool IsCaseSensitive;
+bool VersionMatch;
+uint64_t FileValidityToken;
+auto E = vfs::StatCacheFileSystem::validateCacheFile(
+(*ErrorOrBuffer)->getMemBufferRef(), CacheBaseDir, IsCaseSensitive,
+VersionMatch, FileValidityToken);
+ASSERT_FALSE(E);
+EXPECT_TRUE(VersionMatch);
+EXPECT_EQ(FileValidityToken, ExpectedValidityToken);
+auto ExpectedCache =
+vfs::StatCacheFileSystem::create(std::move(*ErrorOrBuffer), Lower);
+ASSERT_FALSE(ExpectedCache.takeError());
+Result = *ExpectedCache;
+  }
+
+  template 
+  void
+  compareStatCacheToRealFS(IntrusiveRefCntPtr CacheFS,
+   const StringCollection &Files) {
+IntrusiveRefCntPtr RealFS = vfs::getRealFileSystem();
+
+for (auto &File : Files) {
+  auto ErrorOrStatus1 = RealFS->status(File);
+  auto ErrorOrStatus2 = CacheFS->status(File);
+
+  EXPECT_EQ((bool)ErrorOrStatus1, (bool)ErrorOrStatus2);
+  if (!ErrorOrStatus1 || !ErrorOrStatus2)
+continue;
+
+  vfs::Status s1 = *ErrorOrStatus1, s2 = *ErrorOrStatus2;
+  EXPECT_EQ(s1.getName(), s2.getName());
+  EXPECT_EQ(s1.getType(), s2.getType());
+  EXPECT_EQ(s1.getPermissions(), s2.getPermissions());
+  EXPECT_EQ(s1.getLastModificationTime(), s2.getLastModificationTime());
+  EXPECT_EQ(s1.getUniqueID(), s2.getUniqueID());
+  EXPECT_EQ(s1.getUser(), s2.getUser());
+  EXPECT_EQ(s1.getGroup(), s2.getGroup());
+  EXPECT_EQ(s1.getSize(), s2.getSize());
+}
+  }
+};
+
+TEST_F(StatCacheFileSystemTest, Basic) {
+  TempDir TestDirectory("virtual-file-system-test", /*Unique*/ true);
+  TempDir _a(TestDirectory.path("a"));
+  TempFile _ab(TestDirectory.path("a/b"));
+  TempDir _ac(TestDirectory.path("a/c"));
+  TempFile _acd(TestDirectory.p

[PATCH] D139713: [Sema] Fix crash when evaluating nested call with value-dependent arg

2023-01-05 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak accepted this revision.
ahatanak added a comment.
This revision is now accepted and ready to land.

  LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139713

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


[PATCH] D138329: [-Wunsafe-buffer-usage] Add a new recursive matcher to replace `forEachDescendant` in unsafe buffer check

2023-01-05 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

For relands, you can just use `Differential Revision: 
https://reviews.llvm.org/D138321` instead of `Related differential revision: 
https://reviews.llvm.org/D138329`.
`Revert "Revert ` can be replaced with `Reland` to emphasize that it is a 
reland (it can be omitted as well). A reland should include the original commit 
message. You may additionally mention what issue it fixes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138329

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


[PATCH] D140584: [Clang] Refactor "Designators" into a unified implementation [NFC]

2023-01-05 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 486710.
void added a comment.

Put assert in correct place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140584

Files:
  clang-tools-extra/clangd/FindTarget.cpp
  clang/include/clang/AST/Designator.h
  clang/include/clang/AST/Expr.h
  clang/include/clang/Sema/Designator.h
  clang/include/clang/Tooling/Refactoring/RecursiveSymbolVisitor.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Expr.cpp
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Index/IndexBody.cpp
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2846,8 +2846,7 @@
 }
 void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
   AddStmt(E->getInit());
-  for (const DesignatedInitExpr::Designator &D :
-   llvm::reverse(E->designators())) {
+  for (const Designator &D : llvm::reverse(E->designators())) {
 if (D.isFieldDesignator()) {
   if (FieldDecl *Field = D.getField())
 AddMemberRef(Field, D.getFieldLoc());
Index: clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
===
--- clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
+++ clang/lib/Tooling/Refactoring/Rename/USRLocFinder.cpp
@@ -227,7 +227,7 @@
   }
 
   bool VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
-for (const DesignatedInitExpr::Designator &D : E->designators()) {
+for (const Designator &D : E->designators()) {
   if (D.isFieldDesignator() && D.getField()) {
 const FieldDecl *Decl = D.getField();
 if (isInUSRSet(Decl)) {
Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -1085,7 +1085,7 @@
 Record.AddStmt(E->getSubExpr(I));
   Record.AddSourceLocation(E->getEqualOrColonLoc());
   Record.push_back(E->usesGNUSyntax());
-  for (const DesignatedInitExpr::Designator &D : E->designators()) {
+  for (const Designator &D : E->designators()) {
 if (D.isFieldDesignator()) {
   if (FieldDecl *Field = D.getField()) {
 Record.push_back(serialization::DESIG_FIELD_DECL);
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -1198,8 +1198,6 @@
 }
 
 void ASTStmtReader::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
-  using Designator = DesignatedInitExpr::Designator;
-
   VisitExpr(E);
   unsigned NumSubExprs = Record.readInt();
   assert(NumSubExprs == E->getNumSubExprs() && "Wrong number of subexprs");
@@ -1215,8 +1213,8 @@
   auto *Field = readDeclAs();
   SourceLocation DotLoc = readSourceLocation();
   SourceLocation FieldLoc = readSourceLocation();
-  Designators.push_back(Designator(Field->getIdentifier(), DotLoc,
-   FieldLoc));
+  Designators.push_back(Designator::CreateFieldDesignator(
+  Field->getIdentifier(), DotLoc, FieldLoc));
   Designators.back().setField(Field);
   break;
 }
@@ -1225,7 +1223,8 @@
   const IdentifierInfo *Name = Record.readIdentifier();
   SourceLocation DotLoc = readSourceLocation();
   SourceLocation FieldLoc = readSourceLocation();
-  Designators.push_back(Designator(Name, DotLoc, FieldLoc));
+  Designators.push_back(
+  Designator::CreateFieldDesignator(Name, DotLoc, FieldLoc));
   break;
 }
 
@@ -1233,7 +1232,8 @@
   unsigned Index = Record.readInt();
   SourceLocation LBracketLoc = readSourceLocation();
   SourceLocation RBracketLoc = readSourceLocation();
-  Designators.push_back(Designator(Index, LBracketLoc, RBracketLoc));
+  Designators.push_back(
+  Designator::CreateArrayDesignator(Index, LBracketLoc, RBracketLoc));
   break;
 }
 
@@ -1242,8 +1242,8 @@
   SourceLocation LBracketLoc = readSourceLocation();
   SourceLocation EllipsisLoc = readSourceLocation();
   SourceLocation RBracketLoc = readSourceLocation();
-  Designators.push_back(Designator(Index, LBracketLoc, EllipsisLoc,
-   RBracketLoc));
+  Designators.push_back(Designator::CreateArrayRangeDesignator(
+  Index, LBracketLoc, EllipsisLoc, RBracketLoc));
   break;
 }
 }
Index: clang

[PATCH] D140584: [Clang] Refactor "Designators" into a unified implementation [NFC]

2023-01-05 Thread Bill Wendling via Phabricator via cfe-commits
void added a comment.

In D140584#4029607 , @aaron.ballman 
wrote:

> Drive by comment (I'll give a more thorough review when I have a moment): 
> precommit CI seems to have found an issue to address.
>
> `Assertion failed: false && "Invalid accessor", file 
> C:\ws\w5\llvm-project\premerge-checks\clang\include\clang/AST/Designator.h, 
> line 276`

doh! I did a think-o. Easy fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140584

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


[PATCH] D141098: [clang-format][NFC] Set DeriveLineEnding to false in config files

2023-01-05 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: MyDeveloperDay, HazardyKnusperkeks, rymiel.
owenpan added a project: clang-format.
Herald added a project: All.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

To prevent `\r\n` line endings from getting into the source files.

I'd rather change the default to `false` for LLVM style though. What do you 
think?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D141098

Files:
  clang/include/clang/Format/.clang-format
  clang/lib/Format/.clang-format
  clang/unittests/Format/.clang-format


Index: clang/unittests/Format/.clang-format
===
--- clang/unittests/Format/.clang-format
+++ clang/unittests/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true
Index: clang/lib/Format/.clang-format
===
--- clang/lib/Format/.clang-format
+++ clang/lib/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true
Index: clang/include/clang/Format/.clang-format
===
--- clang/include/clang/Format/.clang-format
+++ clang/include/clang/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true


Index: clang/unittests/Format/.clang-format
===
--- clang/unittests/Format/.clang-format
+++ clang/unittests/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true
Index: clang/lib/Format/.clang-format
===
--- clang/lib/Format/.clang-format
+++ clang/lib/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true
Index: clang/include/clang/Format/.clang-format
===
--- clang/include/clang/Format/.clang-format
+++ clang/include/clang/Format/.clang-format
@@ -1,3 +1,4 @@
 BasedOnStyle: LLVM
+DeriveLineEnding: false
 InsertBraces: true
 RemoveBracesLLVM: true
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D139458: [clangd] Full support for #import insertions

2023-01-05 Thread David Goldman via Phabricator via cfe-commits
dgoldman marked an inline comment as done.
dgoldman added inline comments.



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:572
+  // case where a header file contains ObjC decls but no #imports.
+  Symbol::IncludeDirective Directive = preferredIncludeDirective(
+  Filename, Clang->getLangOpts(), MainFileIncludes, {});

kadircet wrote:
> as discussed offline can you guard this with the `import-insertion` flag as 
> well? we should pass it through ParseOptions.
Done, LMK if I did that properly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139458

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


[PATCH] D139458: [clangd] Full support for #import insertions

2023-01-05 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 486706.
dgoldman added a comment.

Respect ImportInsertions flag in IncludeFixer


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139458

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/ASTSignals.cpp
  clang-tools-extra/clangd/ASTSignals.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/IncludeFixer.cpp
  clang-tools-extra/clangd/IncludeFixer.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/ASTSignalsTests.cpp
  clang-tools-extra/clangd/unittests/ASTTests.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -2718,17 +2718,21 @@
   Sym.CanonicalDeclaration.FileURI = DeclFile.c_str();
   Sym.IncludeHeaders.emplace_back("\"bar.h\"", 1000,
   Symbol::Include | Symbol::Import);
-
-  auto Results = completions("Fun^", {Sym}).Completions;
+  CodeCompleteOptions Opts;
+  // Should only take effect in import contexts.
+  Opts.ImportInsertions = true;
+  auto Results = completions("Fun^", {Sym}, Opts).Completions;
   assert(!Results.empty());
   EXPECT_THAT(Results[0],
   AllOf(named("Func"), insertIncludeText("#include \"bar.h\"\n")));
 
-  Results = completions("Fun^", {Sym}, {}, "Foo.m").Completions;
+  ASTSignals Signals;
+  Signals.InsertionDirective = Symbol::IncludeDirective::Import;
+  Opts.MainFileSignals = &Signals;
+  Results = completions("Fun^", {Sym}, Opts, "Foo.m").Completions;
   assert(!Results.empty());
-  // TODO: Once #import integration support is done this should be #import.
   EXPECT_THAT(Results[0],
-  AllOf(named("Func"), insertIncludeText("#include \"bar.h\"\n")));
+  AllOf(named("Func"), insertIncludeText("#import \"bar.h\"\n")));
 
   Sym.IncludeHeaders[0].SupportedDirectives = Symbol::Import;
   Results = completions("Fun^", {Sym}).Completions;
Index: clang-tools-extra/clangd/unittests/ASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ASTTests.cpp
@@ -11,6 +11,7 @@
 #include "Annotations.h"
 #include "ParsedAST.h"
 #include "TestTU.h"
+#include "index/Symbol.h"
 #include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/Decl.h"
@@ -618,6 +619,45 @@
   hasReservedScope(*findUnqualifiedDecl(AST, "secret").getDeclContext()));
 }
 
+TEST(ClangdAST, PreferredIncludeDirective) {
+  auto ComputePreferredDirective = [](TestTU &TU) {
+auto AST = TU.build();
+return preferredIncludeDirective(AST.tuPath(), AST.getLangOpts(),
+ AST.getIncludeStructure().MainFileIncludes,
+ AST.getLocalTopLevelDecls());
+  };
+  TestTU ObjCTU = TestTU::withCode(R"cpp(
+  int main() {}
+  )cpp");
+  ObjCTU.Filename = "TestTU.m";
+  EXPECT_EQ(ComputePreferredDirective(ObjCTU),
+Symbol::IncludeDirective::Import);
+
+  TestTU HeaderTU = TestTU::withCode(R"cpp(
+  #import "TestTU.h"
+  )cpp");
+  HeaderTU.Filename = "TestTUHeader.h";
+  HeaderTU.ExtraArgs = {"-xobjective-c++-header"};
+  EXPECT_EQ(ComputePreferredDirective(HeaderTU),
+Symbol::IncludeDirective::Import);
+
+  // ObjC language option is not enough for headers.
+  HeaderTU.Code = R"cpp(
+  #include "TestTU.h"
+  )cpp";
+  EXPECT_EQ(ComputePreferredDirective(HeaderTU),
+Symbol::IncludeDirective::Include);
+
+  HeaderTU.Code = R"cpp(
+  @interface Foo
+  @end
+
+  Foo * getFoo();
+  )cpp";
+  EXPECT_EQ(ComputePreferredDirective(HeaderTU),
+Symbol::IncludeDirective::Import);
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ASTSignalsTests.cpp
===
--- clang-tools-extra/clangd/unittests/ASTSignalsTests.cpp
+++ clang-tools-extra/clangd/unittests/ASTSignalsTests.cpp
@@ -68,6 +68,7 @@
   Pair(sym("Y", index::SymbolKind::Variable, "@N@tar@S@X@FI@\\0").ID,
2),
   Pair(_ /*a*/, 3)));
+  EXPECT_EQ(Signals.InsertionDirective, Symbol::IncludeDirective::Include);
 }
 } // namespace
 } // namespace clangd
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-t

[PATCH] D141092: Optionally install clang-tblgen to aid cross-compiling

2023-01-05 Thread James Le Cuirot via Phabricator via cfe-commits
chewi added a comment.

Apologies. I conceived this against 15.0.6, but have now noticed that the 
latest TableGen.cmake may have changed things. I'll retest tomorrow and adjust 
as necessary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141092

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


[PATCH] D140999: [NFC][TargetParser] Deprecate llvm/Support/AArch64TargetParser.h

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

I don't think it is necessary to deprecate the old header then delete it after 
16.0.0 is branched.
llvm/Support/AArch64TargetParser.h has very few open-source out-of-tree uses. 
Perhaps only ldc `driver/targetmachine.cpp` uses the header. So it is not worth 
extra expedience.

Changing the include to `#include "llvm/TargetParser/AArch64TargetParser.h"` is 
totally fine, though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140999

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


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.

We're seeing a similar breakage on Linux in Fuchsia's Clang CI: 
https://ci.chromium.org/ui/p/fuchsia/builders/toolchain.ci/clang-linux-x64/b8792772367021497153/overview


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

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


[PATCH] D139446: [clangd] Add flag to control #import include insertions

2023-01-05 Thread David Goldman via Phabricator via cfe-commits
dgoldman updated this revision to Diff 486700.
dgoldman marked 2 inline comments as done.
dgoldman added a comment.

Update comment + default value


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139446

Files:
  clang-tools-extra/clangd/CodeComplete.h
  clang-tools-extra/clangd/tool/ClangdMain.cpp


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -264,6 +264,14 @@
 "Never insert #include directives as part of code completion")),
 };
 
+opt ImportInsertions{
+"import-insertions",
+cat(Features),
+desc("If header insertion is enabled, add #import directives when "
+ "accepting code completions or fixing includes in Objective-C code"),
+init(CodeCompleteOptions().ImportInsertions),
+};
+
 opt IncludeCleanerStdlib{
 "include-cleaner-stdlib",
 cat(Features),
@@ -906,6 +914,7 @@
 Opts.CodeComplete.BundleOverloads = CompletionStyle != Detailed;
   Opts.CodeComplete.ShowOrigins = ShowOrigins;
   Opts.CodeComplete.InsertIncludes = HeaderInsertion;
+  Opts.CodeComplete.ImportInsertions = ImportInsertions;
   if (!HeaderInsertionDecorators) {
 Opts.CodeComplete.IncludeIndicator.Insert.clear();
 Opts.CodeComplete.IncludeIndicator.NoInsert.clear();
Index: clang-tools-extra/clangd/CodeComplete.h
===
--- clang-tools-extra/clangd/CodeComplete.h
+++ clang-tools-extra/clangd/CodeComplete.h
@@ -70,6 +70,10 @@
 NeverInsert,
   } InsertIncludes = IncludeInsertion::IWYU;
 
+  /// Whether include insertions for Objective-C code should use #import 
instead
+  /// of #include.
+  bool ImportInsertions = false;
+
   /// A visual indicator to prepend to the completion label to indicate whether
   /// completion result would trigger an #include insertion or not.
   struct IncludeInsertionIndicator {


Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -264,6 +264,14 @@
 "Never insert #include directives as part of code completion")),
 };
 
+opt ImportInsertions{
+"import-insertions",
+cat(Features),
+desc("If header insertion is enabled, add #import directives when "
+ "accepting code completions or fixing includes in Objective-C code"),
+init(CodeCompleteOptions().ImportInsertions),
+};
+
 opt IncludeCleanerStdlib{
 "include-cleaner-stdlib",
 cat(Features),
@@ -906,6 +914,7 @@
 Opts.CodeComplete.BundleOverloads = CompletionStyle != Detailed;
   Opts.CodeComplete.ShowOrigins = ShowOrigins;
   Opts.CodeComplete.InsertIncludes = HeaderInsertion;
+  Opts.CodeComplete.ImportInsertions = ImportInsertions;
   if (!HeaderInsertionDecorators) {
 Opts.CodeComplete.IncludeIndicator.Insert.clear();
 Opts.CodeComplete.IncludeIndicator.NoInsert.clear();
Index: clang-tools-extra/clangd/CodeComplete.h
===
--- clang-tools-extra/clangd/CodeComplete.h
+++ clang-tools-extra/clangd/CodeComplete.h
@@ -70,6 +70,10 @@
 NeverInsert,
   } InsertIncludes = IncludeInsertion::IWYU;
 
+  /// Whether include insertions for Objective-C code should use #import instead
+  /// of #include.
+  bool ImportInsertions = false;
+
   /// A visual indicator to prepend to the completion label to indicate whether
   /// completion result would trigger an #include insertion or not.
   struct IncludeInsertionIndicator {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This breaks tests on Mac: http://45.33.8.238/macm1/52112/step_7.txt

Please take a look and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

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


[PATCH] D141070: [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

2023-01-05 Thread Brad Smith via Phabricator via cfe-commits
brad added a comment.

In D141070#4030069 , @MaskRay wrote:

> Wait for LoongArch folks:)

Np :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141070

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


[PATCH] D141035: [clang-format] Add an option to insert a newline at EOF if missing

2023-01-05 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 rG2c6ecc9db624: [clang-format] Add an option to insert a 
newline at EOF if missing (authored by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D141035?vs=486484&id=486693#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141035

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  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
@@ -25171,6 +25171,14 @@
   EXPECT_EQ(Code, format(Code, Style));
 }
 
+TEST_F(FormatTest, InsertNewlineAtEOF) {
+  FormatStyle Style = getLLVMStyle();
+  Style.InsertNewlineAtEOF = true;
+
+  verifyFormat("int i;\n", Style);
+  verifyFormat("int i;\n", "int i;", Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/unittests/Format/ConfigParseTest.cpp
===
--- clang/unittests/Format/ConfigParseTest.cpp
+++ clang/unittests/Format/ConfigParseTest.cpp
@@ -167,6 +167,7 @@
   CHECK_PARSE_BOOL(IndentRequiresClause);
   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
   CHECK_PARSE_BOOL(InsertBraces);
+  CHECK_PARSE_BOOL(InsertNewlineAtEOF);
   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1289,6 +1289,10 @@
 Tok->setType(TT_TrailingReturnArrow);
   }
   break;
+case tok::eof:
+  if (Style.InsertNewlineAtEOF && Tok->NewlinesBefore == 0)
+Tok->NewlinesBefore = 1;
+  break;
 default:
   break;
 }
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -899,6 +899,7 @@
 IO.mapOptional("IndentWrappedFunctionNames",
Style.IndentWrappedFunctionNames);
 IO.mapOptional("InsertBraces", Style.InsertBraces);
+IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
 IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
 IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
@@ -1355,6 +1356,7 @@
   LLVMStyle.IndentWidth = 2;
   LLVMStyle.IndentWrappedFunctionNames = false;
   LLVMStyle.InsertBraces = false;
+  LLVMStyle.InsertNewlineAtEOF = false;
   LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
   LLVMStyle.IntegerLiteralSeparator = {/*Binary=*/0, /*Decimal=*/0, /*Hex=*/0};
   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -2450,6 +2450,10 @@
   /// \version 15
   bool InsertBraces;
 
+  /// Insert a newline at end of file if missing.
+  /// \version 16
+  bool InsertNewlineAtEOF;
+
   /// The style of inserting trailing commas into container literals.
   enum TrailingCommaStyle : int8_t {
 /// Do not insert trailing commas.
@@ -4151,6 +4155,7 @@
IndentWidth == R.IndentWidth &&
IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
InsertBraces == R.InsertBraces &&
+   InsertNewlineAtEOF == R.InsertNewlineAtEOF &&
IntegerLiteralSeparator.Binary == R.IntegerLiteralSeparator.Binary &&
IntegerLiteralSeparator.Decimal ==
R.IntegerLiteralSeparator.Decimal &&
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -876,6 +876,7 @@
   in C++, C#, Java, and JavaScript.
 - Add ``BreakAfterAttributes`` option for breaking after a group of C++11
   attributes before a function declaration/definition name.
+- Add ``InsertNewlineAtEOF`` option for inserting a newline at EOF if missing.
 
 clang-extdef-mapping
 
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -3162,6 +3162,9 @@
   --i;  --i;
 whil

[clang] 2c6ecc9 - [clang-format] Add an option to insert a newline at EOF if missing

2023-01-05 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-01-05T15:25:51-08:00
New Revision: 2c6ecc9db624442dcc4c80ab02d15e0833c7f8a3

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

LOG: [clang-format] Add an option to insert a newline at EOF if missing

Closes #38042.

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

Added: 


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

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 2fa0eef92c9d9..4134d5a387d2d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3162,6 +3162,9 @@ the configuration (without a prefix: ``Auto``).
   --i;  --i;
 while (i);} while (i);
 
+**InsertNewlineAtEOF** (``Boolean``) :versionbadge:`clang-format 16`
+  Insert a newline at end of file if missing.
+
 **InsertTrailingCommas** (``TrailingCommaStyle``) :versionbadge:`clang-format 
11`
   If set to ``TCS_Wrapped`` will insert trailing commas in container
   literals (arrays and objects) that wrap across multiple lines.

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1e370acff3cc2..b69067139ffa5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -876,6 +876,7 @@ clang-format
   in C++, C#, Java, and JavaScript.
 - Add ``BreakAfterAttributes`` option for breaking after a group of C++11
   attributes before a function declaration/definition name.
+- Add ``InsertNewlineAtEOF`` option for inserting a newline at EOF if missing.
 
 clang-extdef-mapping
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 1762ff977aa49..6e5d3a163ec32 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2450,6 +2450,10 @@ struct FormatStyle {
   /// \version 15
   bool InsertBraces;
 
+  /// Insert a newline at end of file if missing.
+  /// \version 16
+  bool InsertNewlineAtEOF;
+
   /// The style of inserting trailing commas into container literals.
   enum TrailingCommaStyle : int8_t {
 /// Do not insert trailing commas.
@@ -4151,6 +4155,7 @@ struct FormatStyle {
IndentWidth == R.IndentWidth &&
IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
InsertBraces == R.InsertBraces &&
+   InsertNewlineAtEOF == R.InsertNewlineAtEOF &&
IntegerLiteralSeparator.Binary == R.IntegerLiteralSeparator.Binary 
&&
IntegerLiteralSeparator.Decimal ==
R.IntegerLiteralSeparator.Decimal &&

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 223a86b8eba27..68f24fa8596a1 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -899,6 +899,7 @@ template <> struct MappingTraits {
 IO.mapOptional("IndentWrappedFunctionNames",
Style.IndentWrappedFunctionNames);
 IO.mapOptional("InsertBraces", Style.InsertBraces);
+IO.mapOptional("InsertNewlineAtEOF", Style.InsertNewlineAtEOF);
 IO.mapOptional("InsertTrailingCommas", Style.InsertTrailingCommas);
 IO.mapOptional("IntegerLiteralSeparator", Style.IntegerLiteralSeparator);
 IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
@@ -1355,6 +1356,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.IndentWidth = 2;
   LLVMStyle.IndentWrappedFunctionNames = false;
   LLVMStyle.InsertBraces = false;
+  LLVMStyle.InsertNewlineAtEOF = false;
   LLVMStyle.InsertTrailingCommas = FormatStyle::TCS_None;
   LLVMStyle.IntegerLiteralSeparator = {/*Binary=*/0, /*Decimal=*/0, /*Hex=*/0};
   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 05fd60e315235..3ed0b3d3c6612 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1289,6 +1289,10 @@ class AnnotatingParser {
 Tok->setType(TT_TrailingReturnArrow);
   }
   break;
+case tok::eof:
+  if (Style.InsertNewlineAtEOF && Tok->NewlinesBefore == 0)
+Tok->NewlinesBefore = 1;
+  break;
 default:
   break;
 }

diff  --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 75be2e2d8cfd0..ccdeaacdcf40f 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -167,6 +167,7 @@ T

[PATCH] D141070: [LoongArch] Define __GCC_HAVE_SYNC_COMPARE_AND_SWAP macros

2023-01-05 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.

Wait for LoongArch folks:)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141070

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


[PATCH] D141035: [clang-format] Add an option to insert a newline at EOF if missing

2023-01-05 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D141035#4028134 , @MyDeveloperDay 
wrote:

> I think I've died an gone to heaven!! LGTM...  Happy New Year!

Happy New Year to you too! Thanks to your comment in D19031#1747112 
, I remembered that I had fixed 

 it even before reporting the bug  
back in 2018!




Comment at: clang/unittests/Format/FormatTest.cpp:25125-25126
+TEST_F(FormatTest, InsertNewlineAtEOF) {
+  verifyFormat("int i;\n");
+  verifyFormat("int i;");
+

Will remove them before landing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141035

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


[PATCH] D136651: [Clang] Give Clang the ability to use a shared stat cache

2023-01-05 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added a comment.

Re-added a few of my minor comments that I think got lost on a specific version 
of the diff. Otherwise LGTM.




Comment at: llvm/include/llvm/Support/StatCacheFileSystem.h:23
+/// A ProxyFileSystem using cached information for status() rather than going 
to
+/// the real filesystem.
+///

s/real/underlying/ - it could be wrapping any filesystem in principle.



Comment at: llvm/include/llvm/Support/StatCacheFileSystem.h:26
+/// When dealing with a huge tree of (mostly) immutable filesystem content
+/// like and SDK, it can be very costly to ask the underlying filesystem for
+/// `stat` data. Even when caching the `stat`s internally, having many

typo: "and SDK" -> "an SDK"



Comment at: llvm/include/llvm/Support/StatCacheFileSystem.h:51
+  static Expected>
+  create(std::unique_ptr &&CacheBuffer,
+ StringRef CacheFilename, IntrusiveRefCntPtr FS);

Nit: It's unusal to see unique_ptr && instead of just unique_ptr. Is this 
needed? Same for the constructor.



Comment at: llvm/include/llvm/Support/StatCacheFileSystem.h:52
+  create(std::unique_ptr &&CacheBuffer,
+ StringRef CacheFilename, IntrusiveRefCntPtr FS);
+

Is CacheFilename different from CacheBuffer->getBufferIdentifier()?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136651

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


[PATCH] D141092: Optionally install clang-tblgen to aid cross-compiling

2023-01-05 Thread James Le Cuirot via Phabricator via cfe-commits
chewi created this revision.
chewi added a reviewer: MaskRay.
chewi added a project: clang.
Herald added a subscriber: StephenFan.
Herald added a project: All.
chewi requested review of this revision.
Herald added a subscriber: cfe-commits.

clang-tblgen is required to cross-compile clang itself. This change respects 
LLVM_DISTRIBUTION_COMPONENTS.

Closes: https://github.com/llvm/llvm-project/issues/20282


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D141092

Files:
  clang/utils/TableGen/CMakeLists.txt


Index: clang/utils/TableGen/CMakeLists.txt
===
--- clang/utils/TableGen/CMakeLists.txt
+++ clang/utils/TableGen/CMakeLists.txt
@@ -28,3 +28,13 @@
 target_link_libraries(clang-tblgen PRIVATE clangSupport_tablegen)
 
 set_target_properties(clang-tblgen PROPERTIES FOLDER "Clang tablegenning")
+
+install(TARGETS clang-tblgen
+COMPONENT clang-tblgen
+RUNTIME DESTINATION "${CLANG_TOOLS_INSTALL_DIR}")
+
+if(NOT LLVM_ENABLE_IDE)
+  add_llvm_install_targets("install-clang-tblgen"
+   DEPENDS clang-tblgen
+   COMPONENT clang-tblgen)
+endif()


Index: clang/utils/TableGen/CMakeLists.txt
===
--- clang/utils/TableGen/CMakeLists.txt
+++ clang/utils/TableGen/CMakeLists.txt
@@ -28,3 +28,13 @@
 target_link_libraries(clang-tblgen PRIVATE clangSupport_tablegen)
 
 set_target_properties(clang-tblgen PROPERTIES FOLDER "Clang tablegenning")
+
+install(TARGETS clang-tblgen
+COMPONENT clang-tblgen
+RUNTIME DESTINATION "${CLANG_TOOLS_INSTALL_DIR}")
+
+if(NOT LLVM_ENABLE_IDE)
+  add_llvm_install_targets("install-clang-tblgen"
+   DEPENDS clang-tblgen
+   COMPONENT clang-tblgen)
+endif()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D140868: [C] Make (c ? e1 : e2) noreturn only if both e1 and e2 are noreturn

2023-01-05 Thread Fangrui Song via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcf8fd210a35c: [C] Make (c ? e1 : e2) noreturn only if both 
e1 and e2 are noreturn (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140868

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/attr-noreturn.c

Index: clang/test/CodeGen/attr-noreturn.c
===
--- clang/test/CodeGen/attr-noreturn.c
+++ clang/test/CodeGen/attr-noreturn.c
@@ -13,6 +13,7 @@
 // CHECK-LABEL: @test_conditional_gnu(
 // CHECK: %cond = select i1 %tobool, ptr @t1, ptr @t2
 // CHECK: call void %cond(
+// CHECK: call void %cond2(
 // CHECK-NEXT:unreachable
 
 // CHECK-CXX-LABEL: @_Z20test_conditional_gnui(
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -8262,7 +8262,9 @@
   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
 
-  QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
+  QualType CompositeTy = S.Context.mergeTypes(
+  lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
+  /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
 
   if (CompositeTy.isNull()) {
 // In this situation, we assume void* type. No especially good
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -10191,7 +10191,8 @@
 
 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
 bool OfBlockPointer, bool Unqualified,
-bool AllowCXX) {
+bool AllowCXX,
+bool IsConditionalOperator) {
   const auto *lbase = lhs->castAs();
   const auto *rbase = rhs->castAs();
   const auto *lproto = dyn_cast(lbase);
@@ -10254,9 +10255,27 @@
   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
 return {};
 
-  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
-  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
-
+  // When merging declarations, it's common for supplemental information like
+  // attributes to only be present in one of the declarations, and we generally
+  // want type merging to preserve the union of information.  So a merged
+  // function type should be noreturn if it was noreturn in *either* operand
+  // type.
+  //
+  // But for the conditional operator, this is backwards.  The result of the
+  // operator could be either operand, and its type should conservatively
+  // reflect that.  So a function type in a composite type is noreturn only
+  // if it's noreturn in *both* operand types.
+  //
+  // Arguably, noreturn is a kind of subtype, and the conditional operator
+  // ought to produce the most specific common supertype of its operand types.
+  // That would differ from this rule in contravariant positions.  However,
+  // neither C nor C++ generally uses this kind of subtype reasoning.  Also,
+  // as a practical matter, it would only affect C code that does abstraction of
+  // higher-order functions (taking noreturn callbacks!), which is uncommon to
+  // say the least.  So we use the simpler rule.
+  bool NoReturn = IsConditionalOperator
+  ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
+  : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
   if (lbaseInfo.getNoReturn() != NoReturn)
 allLTypes = false;
   if (rbaseInfo.getNoReturn() != NoReturn)
@@ -10389,9 +10408,9 @@
   return {};
 }
 
-QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
-bool OfBlockPointer,
-bool Unqualified, bool BlockReturnType) {
+QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
+bool Unqualified, bool BlockReturnType,
+bool IsConditionalOperator) {
   // For C++ we will not reach this code with reference types (see below),
   // for OpenMP variant call overloading we might.
   //
@@ -10684,7 +10703,8 @@
   ArrayType::ArraySizeModifier(), 0);
   }
   case Type::FunctionNoProto:
-return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
+return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
+  /*AllowCXX=*/false, IsConditionalOperator);
   case Type::Record:
   case Type::Enum:
  

[clang] cf8fd21 - [C] Make (c ? e1 : e2) noreturn only if both e1 and e2 are noreturn

2023-01-05 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-01-05T14:36:36-08:00
New Revision: cf8fd210a35c8e93136cb8edc5c6a2e818dc1b1d

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

LOG: [C] Make (c ? e1 : e2) noreturn only if both e1 and e2 are noreturn

In C mode, if e1 has __attribute__((noreturn)) but e2 doesn't, `(c ? e1 : e2)`
is incorrectly noreturn and Clang codegen produces `unreachable`
which may lead to miscompiles (see [1] `gawk/support/dfa.c`).
This problem has been known since
8c6b56f39d967347f28dd9c93f1cffddf6d7e4cd (2010) or earlier.

Fix this by making the result type noreturn only if both e1 and e2 are
noreturn, matching GCC.

`_Noreturn` and `[[noreturn]]` do not have the aforementioned problem.

Fix https://github.com/llvm/llvm-project/issues/59792 [1]

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/CodeGen/attr-noreturn.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ba464df6c0d3b..1e370acff3cc2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -335,6 +335,9 @@ Bug Fixes
   incorrect line numbers in some cases when a header file used an end of line
   character sequence that 
diff ered from the primary source file.
   `Issue 59736 `_
+- In C mode, when ``e1`` has ``__attribute__((noreturn))`` but ``e2`` doesn't,
+  ``(c ? e1 : e2)`` is no longer considered noreturn.
+  `Issue 59792 `_
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 326f115f1bda0..4c0f5075cf2b6 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2865,10 +2865,12 @@ class ASTContext : public RefCountedBase {
   bool canBindObjCObjectType(QualType To, QualType From);
 
   // Functions for calculating composite types
-  QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
-  bool Unqualified = false, bool BlockReturnType = false);
-  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
-  bool Unqualified = false, bool AllowCXX = false);
+  QualType mergeTypes(QualType, QualType, bool OfBlockPointer = false,
+  bool Unqualified = false, bool BlockReturnType = false,
+  bool IsConditionalOperator = false);
+  QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer = false,
+  bool Unqualified = false, bool AllowCXX = false,
+  bool IsConditionalOperator = false);
   QualType mergeFunctionParameterTypes(QualType, QualType,
bool OfBlockPointer = false,
bool Unqualified = false);

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index d90d59380534e..263123dbbbe0f 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -10191,7 +10191,8 @@ QualType 
ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
 
 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
 bool OfBlockPointer, bool Unqualified,
-bool AllowCXX) {
+bool AllowCXX,
+bool IsConditionalOperator) {
   const auto *lbase = lhs->castAs();
   const auto *rbase = rhs->castAs();
   const auto *lproto = dyn_cast(lbase);
@@ -10254,9 +10255,27 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, 
QualType rhs,
   if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
 return {};
 
-  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
-  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
-
+  // When merging declarations, it's common for supplemental information like
+  // attributes to only be present in one of the declarations, and we generally
+  // want type merging to preserve the union of information.  So a merged
+  // function type should be noreturn if it was noreturn in *either* operand
+  // type.
+  //
+  // But for the conditional operator, this is backwards.  The result of the
+  // operator could be either operand, and its type should conservatively
+  // reflect that.  So a function type in a composite type is noreturn only
+  // if it's noreturn in *both* o

[clang] c3ab645 - Add isInAnonymousNamespace() to the dynamic AST matchers

2023-01-05 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-01-05T17:10:14-05:00
New Revision: c3ab6455e5ad24fa8e9310b94bcce4a94b8489aa

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

LOG: Add isInAnonymousNamespace() to the dynamic AST matchers

This was added to the static matchers in
125ccd3751472a0c709498f83671577ffed394a6, but the dynamic matcher was
missed. This adds the dynamic matcher to the list.

Added: 


Modified: 
clang/lib/ASTMatchers/Dynamic/Registry.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 0a58652884ee6..4c20a1295a8da 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -428,6 +428,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(isPrivateKind);
   REGISTER_MATCHER(isFirstPrivateKind);
   REGISTER_MATCHER(isImplicit);
+  REGISTER_MATCHER(isInAnonymousNamespace);
   REGISTER_MATCHER(isInStdNamespace);
   REGISTER_MATCHER(isInTemplateInstantiation);
   REGISTER_MATCHER(isInitCapture);



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


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum 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 rG5e8f597c2fed: [clang][dataflow] Only model struct fields 
that are used in the function being… (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -16,6 +16,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Testing/Support/Error.h"
@@ -39,17 +40,22 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  llvm::StringRef TargetFun = "target") {
   using ast_matchers::hasName;
+  llvm::SmallVector ASTBuildArgs = {
+  "-fsyntax-only", "-fno-delayed-template-parsing",
+  "-std=" +
+  std::string(LangStandard::getLangStandardForKind(Std).getName())};
+  auto AI =
+  AnalysisInputs(Code, hasName(TargetFun),
+   [&Options](ASTContext &C, Environment &) {
+ return NoopAnalysis(C, Options);
+   })
+  .withASTBuildArgs(ASTBuildArgs);
+  if (Options.BuiltinTransferOpts &&
+  Options.BuiltinTransferOpts->ContextSensitiveOpts)
+AI = std::move(AI).withContextSensitivity();
   ASSERT_THAT_ERROR(
   checkDataflow(
-  AnalysisInputs(Code, hasName(TargetFun),
-   [Options](ASTContext &C, Environment &) {
- return NoopAnalysis(C, Options);
-   })
-  .withASTBuildArgs(
-  {"-fsyntax-only", "-fno-delayed-template-parsing",
-   "-std=" +
-   std::string(LangStandard::getLangStandardForKind(Std)
-   .getName())}),
+  std::move(AI),
   /*VerifyResults=*/
   [&Match](const llvm::StringMap>
&Results,
@@ -151,6 +157,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -198,6 +205,7 @@
 
 void target() {
   A Foo = Gen();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -238,11 +246,13 @@
 TEST(TransferTest, ClassVarDecl) {
   std::string Code = R"(
 class A {
+ public:
   int Bar;
 };
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -336,6 +346,10 @@
 
 void target() {
   A &Foo = getA();
+  (void)Foo.Bar.FooRef;
+  (void)Foo.Bar.FooPtr;
+  (void)Foo.Bar.BazRef;
+  (void)Foo.Bar.BazPtr;
   // [[p]]
 }
   )";
@@ -478,6 +492,10 @@
 
 void target() {
   A *Foo = getA();
+  (void)Foo->Bar->FooRef;
+  (void)Foo->Bar->FooPtr;
+  (void)Foo->Bar->BazRef;
+  (void)Foo->Bar->BazPtr;
   // [[p]]
 }
   )";
@@ -891,7 +909,7 @@
 };
 
 void target(A Foo) {
-  (void)0;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1052,6 +1070,9 @@
   int APrivate;
 public:
   int APublic;
+
+private:
+  friend void target();
 };
 
 class B : public A {
@@ -1060,10 +1081,20 @@
   int BProtected;
 private:
   int BPrivate;
+
+private:
+  friend void target();
 };
 
 void target() {
   B Foo;
+  (void)Foo.ADefault;
+  (void)Foo.AProtected;
+  (void)Foo.APrivate;
+  (void)Foo.APublic;
+  (void)Foo.BDefault;
+  (void)Foo.BProtected;
+  (void)Foo.BPrivate;
   // [[p]]
 }
   )";
@@ -1202,6 +1233,7 @@
 
 void target() {
   B Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1525,7 +1557,11 @@
   int Bar;
 
   void target() {
-(void)0; // [[p]]
+A a;
+// Mention the fields to ensure they're included in the analysis.
+(void)a.Foo;
+(void)a.Bar;
+// [[p]]
   }
 };
   )";
@@ -1777,6 +1813,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
  

[clang] 5e8f597 - [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2023-01-05T21:46:39Z
New Revision: 5e8f597c2fedc740b71f07dfdb1ef3c2d348b193

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

LOG: [clang][dataflow] Only model struct fields that are used in the function 
being analyzed.

Previously, the model for structs modeled all fields in a struct when
`createValue` was called for that type. This patch adds a prepass on the
function under analysis to discover the fields referenced in the scope and then
limits modeling to only those fields.  This reduces wasted memory usage
(modeling unused fields) which can be important for programss that use large
structs.

Note: This patch obviates the need for https://reviews.llvm.org/D123032.

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

Added: 


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

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index f8ee5864482b3..98135508aabb4 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -54,14 +54,21 @@ llvm::DenseSet getObjectFields(QualType 
Type);
 /// is used during dataflow analysis.
 class DataflowAnalysisContext {
 public:
+  // FIXME: merge with TransferOptions from Transfer.h.
+  struct Options {
+bool EnableContextSensitiveAnalysis;
+  };
+
   /// Constructs a dataflow analysis context.
   ///
   /// Requirements:
   ///
   ///  `S` must not be null.
-  DataflowAnalysisContext(std::unique_ptr S)
+  DataflowAnalysisContext(std::unique_ptr S,
+  Options Opts = {
+  /*EnableContextSensitiveAnalysis=*/false})
   : S(std::move(S)), TrueVal(createAtomicBoolValue()),
-FalseVal(createAtomicBoolValue()) {
+FalseVal(createAtomicBoolValue()), Options(Opts) {
 assert(this->S != nullptr);
   }
 
@@ -253,7 +260,11 @@ class DataflowAnalysisContext {
   /// returns null.
   const ControlFlowContext *getControlFlowContext(const FunctionDecl *F);
 
+  void addFieldsReferencedInScope(llvm::DenseSet Fields);
+
 private:
+  friend class Environment;
+
   struct NullableQualTypeDenseMapInfo : private llvm::DenseMapInfo {
 static QualType getEmptyKey() {
   // Allow a NULL `QualType` by using a 
diff erent value as the empty key.
@@ -265,6 +276,10 @@ class DataflowAnalysisContext {
 using DenseMapInfo::isEqual;
   };
 
+  /// Returns the subset of fields of `Type` that are referenced in the scope 
of
+  /// the analysis.
+  llvm::DenseSet getReferencedFields(QualType Type);
+
   /// Adds all constraints of the flow condition identified by `Token` and all
   /// of its transitive dependencies to `Constraints`. `VisitedTokens` is used
   /// to track tokens of flow conditions that were already visited by recursive
@@ -330,6 +345,8 @@ class DataflowAnalysisContext {
   AtomicBoolValue &TrueVal;
   AtomicBoolValue &FalseVal;
 
+  Options Options;
+
   // Indices that are used to avoid recreating the same composite boolean
   // values.
   llvm::DenseMap, ConjunctionValue *>
@@ -359,6 +376,9 @@ class DataflowAnalysisContext {
   llvm::DenseMap FlowConditionConstraints;
 
   llvm::DenseMap FunctionContexts;
+
+  // All fields referenced (statically) in the scope of the analysis.
+  llvm::DenseSet FieldsReferencedInScope;
 };
 
 } // namespace dataflow

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c1653c2ab4ed2..fbc5f6d2c8891 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -452,6 +452,9 @@ class Environment {
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
+  /// Assigns storage locations and values to all variables in `Vars`.
+  void initVars(llvm::DenseSet Vars);
+
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;
 

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
index af2

[PATCH] D140664: [Sema] Don't mark deleted special member functions as non-trivial

2023-01-05 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson reopened this revision.
royjacobson added a comment.
This revision is now accepted and ready to land.

So, I had a quick look at this. Turns out this fix changed the argument passing 
ABI for those classes on the Sony PS4. This is probably not acceptable :)

Putting this behind an ABI compat/Sony flag is probably good enough in this 
case, will try to write it up next week.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140664

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


[PATCH] D140598: [Clang] Add sanity check in Sema::getDestructorName to prevent nullptr dereference

2023-01-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Also, don't forget to add a release note for the fix. :-)


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

https://reviews.llvm.org/D140598

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


[PATCH] D140598: [Clang] Add sanity check in Sema::getDestructorName to prevent nullptr dereference

2023-01-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:393
 // reasonably apply this fallback for dependent nested-name-specifiers.
-if (SS.getScopeRep()->getPrefix()) {
+if (SS.isSet() && SS.getScopeRep()->getPrefix()) {
   if (ParsedType T = LookupInScope()) {

tahonermann wrote:
> `CXXScopeSpec::isSet()` is apparently (intended to be) deprecated.
> ```
> clang/include/clang/Sema/DeclSpec.h:
>  209   /// Deprecated.  Some call sites intend isNotEmpty() while others 
> intend
>  210   /// isValid().
>  211   bool isSet() const { return getScopeRep() != nullptr; }
> ```
> It sounds like this should instead call `.isValid()` or `.isNotEmpty()`, but 
> I'm not sure which.
We want to use `isValid()` -- `isNotEmpty()` will return `true` when the scope 
spec is present but invalid, so the call to `SS.getScopeRep()->getPrefix()` 
would crash in that case.


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

https://reviews.llvm.org/D140598

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


[PATCH] D138870: clang/AMDGPU: Remove flat-address-space from feature map

2023-01-05 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm closed this revision.
arsenm added a comment.

81849497b42e1a865af8aff65ab768e56a301c87 



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

https://reviews.llvm.org/D138870

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


[clang] 8184949 - clang/AMDGPU: Remove flat-address-space from feature map

2023-01-05 Thread Matt Arsenault via cfe-commits

Author: Matt Arsenault
Date: 2023-01-05T16:35:04-05:00
New Revision: 81849497b42e1a865af8aff65ab768e56a301c87

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

LOG: clang/AMDGPU: Remove flat-address-space from feature map

This was only used for checking if is_shared/is_private were legal,
which we're not bothering to do anymore.

This is apparently visible to more than the target attribute (which
seems to silently ignore unrecognized features), so this has the
potential to break something (i.e. see the OpenMP test change)

Added: 


Modified: 
clang/lib/Basic/Targets/AMDGPU.cpp
clang/test/CodeGenOpenCL/amdgpu-features.cl
clang/test/OpenMP/amdgcn-attributes.cpp
clang/test/OpenMP/metadirective_device_isa_codegen_amdgcn.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/AMDGPU.cpp 
b/clang/lib/Basic/Targets/AMDGPU.cpp
index ecb786482c9a3..7e54f23f5bf99 100644
--- a/clang/lib/Basic/Targets/AMDGPU.cpp
+++ b/clang/lib/Basic/Targets/AMDGPU.cpp
@@ -199,7 +199,6 @@ bool AMDGPUTargetInfo::initFeatureMap(
   Features["dot7-insts"] = true;
   Features["dot8-insts"] = true;
   Features["dl-insts"] = true;
-  Features["flat-address-space"] = true;
   Features["16-bit-insts"] = true;
   Features["dpp"] = true;
   Features["gfx8-insts"] = true;
@@ -223,7 +222,6 @@ bool AMDGPUTargetInfo::initFeatureMap(
   Features["dot6-insts"] = true;
   Features["dot7-insts"] = true;
   Features["dl-insts"] = true;
-  Features["flat-address-space"] = true;
   Features["16-bit-insts"] = true;
   Features["dpp"] = true;
   Features["gfx8-insts"] = true;
@@ -246,7 +244,6 @@ bool AMDGPUTargetInfo::initFeatureMap(
   IsWave32Capable = true;
   Features["dl-insts"] = true;
   Features["ci-insts"] = true;
-  Features["flat-address-space"] = true;
   Features["16-bit-insts"] = true;
   Features["dpp"] = true;
   Features["gfx8-insts"] = true;
@@ -299,7 +296,6 @@ bool AMDGPUTargetInfo::initFeatureMap(
 case GK_GFX701:
 case GK_GFX700:
   Features["ci-insts"] = true;
-  Features["flat-address-space"] = true;
   [[fallthrough]];
 case GK_GFX602:
 case GK_GFX601:

diff  --git a/clang/test/CodeGenOpenCL/amdgpu-features.cl 
b/clang/test/CodeGenOpenCL/amdgpu-features.cl
index 46402c377c335..597c290b86e6b 100644
--- a/clang/test/CodeGenOpenCL/amdgpu-features.cl
+++ b/clang/test/CodeGenOpenCL/amdgpu-features.cl
@@ -55,41 +55,41 @@
 // GFX600: "target-features"="+s-memtime-inst,+wavefrontsize64"
 // GFX601: "target-features"="+s-memtime-inst,+wavefrontsize64"
 // GFX602: "target-features"="+s-memtime-inst,+wavefrontsize64"
-// GFX700: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX701: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX702: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX703: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX704: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX705: 
"target-features"="+ci-insts,+flat-address-space,+s-memtime-inst,+wavefrontsize64"
-// GFX801: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX802: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX803: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX805: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX810: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX900: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX902: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX904: 
"target-features"="+16-bit-insts,+ci-insts,+dpp,+flat-address-space,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX906: 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot2-insts,+dot7-insts,+dpp,+flat-address-space,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64"
-// GFX908: 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot2-insts,+dot3-insts,+dot4-insts,+dot5-insts,+dot6-insts,+dot7-insts,+dpp,+flat-addres

[PATCH] D139935: [NFC] [Doc] Fix example for AnnotateTypeDocs

2023-01-05 Thread Xiang Li 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 rGad48e9669a80: [NFC] [Doc] Fix example for AnnotateTypeDocs 
(authored by python3kgae).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139935

Files:
  clang/include/clang/Basic/AttrDocs.td


Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6705,7 +6705,7 @@
 
 .. code-block:: c++
 
-  int* [[clang::annotate("category1", "foo", 1)]] 
f(int[[clang::annotate("category2")]] *);
+  int* [[clang::annotate_type("category1", "foo", 1)]] 
f(int[[clang::annotate_type("category2")]] *);
 
 The attribute does not have any effect on the semantics of the type system,
 neither type checking rules, nor runtime semantics. In particular:


Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -6705,7 +6705,7 @@
 
 .. code-block:: c++
 
-  int* [[clang::annotate("category1", "foo", 1)]] f(int[[clang::annotate("category2")]] *);
+  int* [[clang::annotate_type("category1", "foo", 1)]] f(int[[clang::annotate_type("category2")]] *);
 
 The attribute does not have any effect on the semantics of the type system,
 neither type checking rules, nor runtime semantics. In particular:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ad48e96 - [NFC] [Doc] Fix example for AnnotateTypeDocs

2023-01-05 Thread Xiang Li via cfe-commits

Author: Xiang Li
Date: 2023-01-05T16:32:02-05:00
New Revision: ad48e9669a80e05c55e35970461b34f04dc0f117

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

LOG: [NFC] [Doc] Fix example for AnnotateTypeDocs

Change clang::annotate into clang::annotate_type.

The example will get error like
error: 'annotate' attribute cannot be applied to types
int* [[clang::annotate("category1", "foo", 1)]] 
f(int[[clang::annotate("category2")]] *);

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 2dc5e7d61817a..6d7a3ffd2d52c 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6705,7 +6705,7 @@ For example:
 
 .. code-block:: c++
 
-  int* [[clang::annotate("category1", "foo", 1)]] 
f(int[[clang::annotate("category2")]] *);
+  int* [[clang::annotate_type("category1", "foo", 1)]] 
f(int[[clang::annotate_type("category2")]] *);
 
 The attribute does not have any effect on the semantics of the type system,
 neither type checking rules, nor runtime semantics. In particular:



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


[PATCH] D140835: [clang-format] Improve UnwrappedLineParser::mightFitOnOneLine()

2023-01-05 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D140835#4028479 , 
@HazardyKnusperkeks wrote:

> In D140835#4028274 , @owenpan wrote:
>
>> If `RemoveBracesLLVM` is false, the line is too long and will wrap.
>
> That's what I fail to see, but if you say so.

The line is 24 characters long, but `ColumnLimit` is set to 20 on line 731.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140835

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


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 48.
ymandel added a comment.

fix broken test (from rebase)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -16,6 +16,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Testing/Support/Error.h"
@@ -39,17 +40,22 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  llvm::StringRef TargetFun = "target") {
   using ast_matchers::hasName;
+  llvm::SmallVector ASTBuildArgs = {
+  "-fsyntax-only", "-fno-delayed-template-parsing",
+  "-std=" +
+  std::string(LangStandard::getLangStandardForKind(Std).getName())};
+  auto AI =
+  AnalysisInputs(Code, hasName(TargetFun),
+   [&Options](ASTContext &C, Environment &) {
+ return NoopAnalysis(C, Options);
+   })
+  .withASTBuildArgs(ASTBuildArgs);
+  if (Options.BuiltinTransferOpts &&
+  Options.BuiltinTransferOpts->ContextSensitiveOpts)
+AI = std::move(AI).withContextSensitivity();
   ASSERT_THAT_ERROR(
   checkDataflow(
-  AnalysisInputs(Code, hasName(TargetFun),
-   [Options](ASTContext &C, Environment &) {
- return NoopAnalysis(C, Options);
-   })
-  .withASTBuildArgs(
-  {"-fsyntax-only", "-fno-delayed-template-parsing",
-   "-std=" +
-   std::string(LangStandard::getLangStandardForKind(Std)
-   .getName())}),
+  std::move(AI),
   /*VerifyResults=*/
   [&Match](const llvm::StringMap>
&Results,
@@ -151,6 +157,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -198,6 +205,7 @@
 
 void target() {
   A Foo = Gen();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -238,11 +246,13 @@
 TEST(TransferTest, ClassVarDecl) {
   std::string Code = R"(
 class A {
+ public:
   int Bar;
 };
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -336,6 +346,10 @@
 
 void target() {
   A &Foo = getA();
+  (void)Foo.Bar.FooRef;
+  (void)Foo.Bar.FooPtr;
+  (void)Foo.Bar.BazRef;
+  (void)Foo.Bar.BazPtr;
   // [[p]]
 }
   )";
@@ -478,6 +492,10 @@
 
 void target() {
   A *Foo = getA();
+  (void)Foo->Bar->FooRef;
+  (void)Foo->Bar->FooPtr;
+  (void)Foo->Bar->BazRef;
+  (void)Foo->Bar->BazPtr;
   // [[p]]
 }
   )";
@@ -891,7 +909,7 @@
 };
 
 void target(A Foo) {
-  (void)0;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1052,6 +1070,9 @@
   int APrivate;
 public:
   int APublic;
+
+private:
+  friend void target();
 };
 
 class B : public A {
@@ -1060,10 +1081,20 @@
   int BProtected;
 private:
   int BPrivate;
+
+private:
+  friend void target();
 };
 
 void target() {
   B Foo;
+  (void)Foo.ADefault;
+  (void)Foo.AProtected;
+  (void)Foo.APrivate;
+  (void)Foo.APublic;
+  (void)Foo.BDefault;
+  (void)Foo.BProtected;
+  (void)Foo.BPrivate;
   // [[p]]
 }
   )";
@@ -1202,6 +1233,7 @@
 
 void target() {
   B Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1525,7 +1557,11 @@
   int Bar;
 
   void target() {
-(void)0; // [[p]]
+A a;
+// Mention the fields to ensure they're included in the analysis.
+(void)a.Foo;
+(void)a.Bar;
+// [[p]]
   }
 };
   )";
@@ -1777,6 +1813,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1814,6 +1851,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1851,6 +1889,7 @@
 void target() {

[PATCH] D141008: [Clang][SPIR-V] Emit target extension types for OpenCL types on SPIR-V.

2023-01-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang-c/Index.h:30
  * The version constants for the libclang API.
  * CINDEX_VERSION_MINOR should increase when there are API additions.
  * CINDEX_VERSION_MAJOR is intended for "major" source/ABI breaking changes.

svenvh wrote:
> I suppose you need to bump `CINDEX_VERSION_MINOR` for the enum additions?
Correct.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141008

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


[PATCH] D139935: [NFC] [Doc] Fix example for AnnotateTypeDocs

2023-01-05 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!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139935

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


[PATCH] D140835: [clang-format] Improve UnwrappedLineParser::mightFitOnOneLine()

2023-01-05 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5751c439be7d: [clang-format] Improve 
UnwrappedLineParser::mightFitOnOneLine() (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140835

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/BracesRemoverTest.cpp


Index: clang/unittests/Format/BracesRemoverTest.cpp
===
--- clang/unittests/Format/BracesRemoverTest.cpp
+++ clang/unittests/Format/BracesRemoverTest.cpp
@@ -828,6 +828,17 @@
"}",
Style);
 
+  verifyFormat("if (foo)\n"
+   "  f();\n"
+   "else if (bar || baz)\n"
+   "  g();",
+   "if (foo) {\n"
+   "  f();\n"
+   "} else if (bar || baz) {\n"
+   "  g();\n"
+   "}",
+   Style);
+
   Style.ColumnLimit = 0;
   verifyFormat("if (a)\n"
"  b234567890223456789032345678904234567890 = "
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -836,6 +836,11 @@
 Length -= OpeningBrace->TokenText.size() + 1;
   }
 
+  if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
+assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
+Length -= FirstToken->TokenText.size() + 1;
+  }
+
   Index = 0;
   for (auto &Token : Tokens) {
 const auto &SavedToken = SavedTokens[Index++];


Index: clang/unittests/Format/BracesRemoverTest.cpp
===
--- clang/unittests/Format/BracesRemoverTest.cpp
+++ clang/unittests/Format/BracesRemoverTest.cpp
@@ -828,6 +828,17 @@
"}",
Style);
 
+  verifyFormat("if (foo)\n"
+   "  f();\n"
+   "else if (bar || baz)\n"
+   "  g();",
+   "if (foo) {\n"
+   "  f();\n"
+   "} else if (bar || baz) {\n"
+   "  g();\n"
+   "}",
+   Style);
+
   Style.ColumnLimit = 0;
   verifyFormat("if (a)\n"
"  b234567890223456789032345678904234567890 = "
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -836,6 +836,11 @@
 Length -= OpeningBrace->TokenText.size() + 1;
   }
 
+  if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
+assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
+Length -= FirstToken->TokenText.size() + 1;
+  }
+
   Index = 0;
   for (auto &Token : Tokens) {
 const auto &SavedToken = SavedTokens[Index++];
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5751c43 - [clang-format] Improve UnwrappedLineParser::mightFitOnOneLine()

2023-01-05 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-01-05T13:23:23-08:00
New Revision: 5751c439be7d00427991e8503e618d0c27a56f89

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

LOG: [clang-format] Improve UnwrappedLineParser::mightFitOnOneLine()

Account for an r_brace that precedes an "else if" statement when
calculating whether the line might fit on one line if the r_brace
is removed.

Fixes #59778.

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/BracesRemoverTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 3be4ef7ca6a1a..8e1ea06779022 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -836,6 +836,11 @@ bool UnwrappedLineParser::mightFitOnOneLine(
 Length -= OpeningBrace->TokenText.size() + 1;
   }
 
+  if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
+assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
+Length -= FirstToken->TokenText.size() + 1;
+  }
+
   Index = 0;
   for (auto &Token : Tokens) {
 const auto &SavedToken = SavedTokens[Index++];

diff  --git a/clang/unittests/Format/BracesRemoverTest.cpp 
b/clang/unittests/Format/BracesRemoverTest.cpp
index 57cf40d4c9e95..ba0b3eb53d155 100644
--- a/clang/unittests/Format/BracesRemoverTest.cpp
+++ b/clang/unittests/Format/BracesRemoverTest.cpp
@@ -828,6 +828,17 @@ TEST_F(BracesRemoverTest, RemoveBraces) {
"}",
Style);
 
+  verifyFormat("if (foo)\n"
+   "  f();\n"
+   "else if (bar || baz)\n"
+   "  g();",
+   "if (foo) {\n"
+   "  f();\n"
+   "} else if (bar || baz) {\n"
+   "  g();\n"
+   "}",
+   Style);
+
   Style.ColumnLimit = 0;
   verifyFormat("if (a)\n"
"  b234567890223456789032345678904234567890 = "



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


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 486659.
ymandel marked an inline comment as done.
ymandel added a comment.

fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -16,6 +16,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Testing/Support/Error.h"
@@ -39,17 +40,22 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  llvm::StringRef TargetFun = "target") {
   using ast_matchers::hasName;
+  llvm::SmallVector ASTBuildArgs = {
+  "-fsyntax-only", "-fno-delayed-template-parsing",
+  "-std=" +
+  std::string(LangStandard::getLangStandardForKind(Std).getName())};
+  auto AI =
+  AnalysisInputs(Code, hasName(TargetFun),
+   [&Options](ASTContext &C, Environment &) {
+ return NoopAnalysis(C, Options);
+   })
+  .withASTBuildArgs(ASTBuildArgs);
+  if (Options.BuiltinTransferOpts &&
+  Options.BuiltinTransferOpts->ContextSensitiveOpts)
+AI = std::move(AI).withContextSensitivity();
   ASSERT_THAT_ERROR(
   checkDataflow(
-  AnalysisInputs(Code, hasName(TargetFun),
-   [Options](ASTContext &C, Environment &) {
- return NoopAnalysis(C, Options);
-   })
-  .withASTBuildArgs(
-  {"-fsyntax-only", "-fno-delayed-template-parsing",
-   "-std=" +
-   std::string(LangStandard::getLangStandardForKind(Std)
-   .getName())}),
+  std::move(AI),
   /*VerifyResults=*/
   [&Match](const llvm::StringMap>
&Results,
@@ -151,6 +157,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -198,6 +205,7 @@
 
 void target() {
   A Foo = Gen();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -238,11 +246,13 @@
 TEST(TransferTest, ClassVarDecl) {
   std::string Code = R"(
 class A {
+ public:
   int Bar;
 };
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -336,6 +346,10 @@
 
 void target() {
   A &Foo = getA();
+  (void)Foo.Bar.FooRef;
+  (void)Foo.Bar.FooPtr;
+  (void)Foo.Bar.BazRef;
+  (void)Foo.Bar.BazPtr;
   // [[p]]
 }
   )";
@@ -478,6 +492,10 @@
 
 void target() {
   A *Foo = getA();
+  (void)Foo->Bar->FooRef;
+  (void)Foo->Bar->FooPtr;
+  (void)Foo->Bar->BazRef;
+  (void)Foo->Bar->BazPtr;
   // [[p]]
 }
   )";
@@ -891,7 +909,7 @@
 };
 
 void target(A Foo) {
-  (void)0;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1052,6 +1070,9 @@
   int APrivate;
 public:
   int APublic;
+
+private:
+  friend void target();
 };
 
 class B : public A {
@@ -1060,10 +1081,20 @@
   int BProtected;
 private:
   int BPrivate;
+
+private:
+  friend void target();
 };
 
 void target() {
   B Foo;
+  (void)Foo.ADefault;
+  (void)Foo.AProtected;
+  (void)Foo.APrivate;
+  (void)Foo.APublic;
+  (void)Foo.BDefault;
+  (void)Foo.BProtected;
+  (void)Foo.BPrivate;
   // [[p]]
 }
   )";
@@ -1202,6 +1233,7 @@
 
 void target() {
   B Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1777,6 +1809,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1814,6 +1847,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1851,6 +1885,7 @@
 void target() {
   A Foo;
   A Bar;
+  (void)Foo.Baz;
   // [[p1]]
   Foo = Bar;
   // [[p2]]
@@ -1913,6 +1948,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Baz;
   A Bar = Foo;
   // [[p]]
 }
@@ -1958,6 +1994,7

[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added a comment.

In D140694#4026244 , @xazax.hun wrote:

> This is a big improvement, I skimmed through it and looks good to me. There 
> might be some sneaky ways to change values of fields without mentioning them, 
> e.g., casting a pointer to a struct to an array of chars. But I think 
> reasoning about those scenarios is probably not something we want to model 
> anytime soon.

Thanks!

> Another pesky scenario when we are not doing context sensitive analysis:
>
>   int* pointsToField = getField(myObj);
>
> But this can be handled correctly in a conservative way buy treating `myObj' 
> as escaped. Overall, I dont anticipate any blockers at the moment.

Agreed. I think any other field access either falls into 1) we don't handle it 
soundly anyhow or 2) a conservative analysis will rule it out.




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:267
 
+  void addFieldsReferencedInScope(llvm::DenseSet Fields);
+

xazax.hun wrote:
> Is there any scenario where check authors might invoke this function? If no, 
> I wonder if it would be better to make this private and make Environment a 
> friend of this class. Keeping the number of public methods minimal could be a 
> great service to future check authors.
Good point. Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

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


[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 486658.
ymandel added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -16,6 +16,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Testing/Support/Error.h"
@@ -39,17 +40,22 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  llvm::StringRef TargetFun = "target") {
   using ast_matchers::hasName;
+  llvm::SmallVector ASTBuildArgs = {
+  "-fsyntax-only", "-fno-delayed-template-parsing",
+  "-std=" +
+  std::string(LangStandard::getLangStandardForKind(Std).getName())};
+  auto AI =
+  AnalysisInputs(Code, hasName(TargetFun),
+   [&Options](ASTContext &C, Environment &) {
+ return NoopAnalysis(C, Options);
+   })
+  .withASTBuildArgs(ASTBuildArgs);
+  if (Options.BuiltinTransferOpts &&
+  Options.BuiltinTransferOpts->ContextSensitiveOpts)
+AI = std::move(AI).withContextSensitivity();
   ASSERT_THAT_ERROR(
   checkDataflow(
-  AnalysisInputs(Code, hasName(TargetFun),
-   [Options](ASTContext &C, Environment &) {
- return NoopAnalysis(C, Options);
-   })
-  .withASTBuildArgs(
-  {"-fsyntax-only", "-fno-delayed-template-parsing",
-   "-std=" +
-   std::string(LangStandard::getLangStandardForKind(Std)
-   .getName())}),
+  std::move(AI),
   /*VerifyResults=*/
   [&Match](const llvm::StringMap>
&Results,
@@ -151,6 +157,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -198,6 +205,7 @@
 
 void target() {
   A Foo = Gen();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -238,11 +246,13 @@
 TEST(TransferTest, ClassVarDecl) {
   std::string Code = R"(
 class A {
+ public:
   int Bar;
 };
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -336,6 +346,10 @@
 
 void target() {
   A &Foo = getA();
+  (void)Foo.Bar.FooRef;
+  (void)Foo.Bar.FooPtr;
+  (void)Foo.Bar.BazRef;
+  (void)Foo.Bar.BazPtr;
   // [[p]]
 }
   )";
@@ -478,6 +492,10 @@
 
 void target() {
   A *Foo = getA();
+  (void)Foo->Bar->FooRef;
+  (void)Foo->Bar->FooPtr;
+  (void)Foo->Bar->BazRef;
+  (void)Foo->Bar->BazPtr;
   // [[p]]
 }
   )";
@@ -891,7 +909,7 @@
 };
 
 void target(A Foo) {
-  (void)0;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1052,6 +1070,9 @@
   int APrivate;
 public:
   int APublic;
+
+private:
+  friend void target();
 };
 
 class B : public A {
@@ -1060,10 +1081,20 @@
   int BProtected;
 private:
   int BPrivate;
+
+private:
+  friend void target();
 };
 
 void target() {
   B Foo;
+  (void)Foo.ADefault;
+  (void)Foo.AProtected;
+  (void)Foo.APrivate;
+  (void)Foo.APublic;
+  (void)Foo.BDefault;
+  (void)Foo.BProtected;
+  (void)Foo.BPrivate;
   // [[p]]
 }
   )";
@@ -1202,6 +1233,7 @@
 
 void target() {
   B Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1777,6 +1809,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1814,6 +1847,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1851,6 +1885,7 @@
 void target() {
   A Foo;
   A Bar;
+  (void)Foo.Baz;
   // [[p1]]
   Foo = Bar;
   // [[p2]]
@@ -1913,6 +1948,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Baz;
   A Bar = Foo;
   // [[p]]
 }
@@ -1958,6 +1994,7 @@
 
 void target() {
   

[PATCH] D140694: [clang][dataflow] Only model struct fields that are used in the function being analyzed.

2023-01-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 486657.
ymandel added a comment.

rebase onto HEAD


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140694

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  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
@@ -16,6 +16,7 @@
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Basic/LangStandard.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Testing/Support/Error.h"
@@ -39,17 +40,22 @@
  LangStandard::Kind Std = LangStandard::lang_cxx17,
  llvm::StringRef TargetFun = "target") {
   using ast_matchers::hasName;
+  llvm::SmallVector ASTBuildArgs = {
+  "-fsyntax-only", "-fno-delayed-template-parsing",
+  "-std=" +
+  std::string(LangStandard::getLangStandardForKind(Std).getName())};
+  auto AI =
+  AnalysisInputs(Code, hasName(TargetFun),
+   [&Options](ASTContext &C, Environment &) {
+ return NoopAnalysis(C, Options);
+   })
+  .withASTBuildArgs(ASTBuildArgs);
+  if (Options.BuiltinTransferOpts &&
+  Options.BuiltinTransferOpts->ContextSensitiveOpts)
+AI = std::move(AI).withContextSensitivity();
   ASSERT_THAT_ERROR(
   checkDataflow(
-  AnalysisInputs(Code, hasName(TargetFun),
-   [Options](ASTContext &C, Environment &) {
- return NoopAnalysis(C, Options);
-   })
-  .withASTBuildArgs(
-  {"-fsyntax-only", "-fno-delayed-template-parsing",
-   "-std=" +
-   std::string(LangStandard::getLangStandardForKind(Std)
-   .getName())}),
+  std::move(AI),
   /*VerifyResults=*/
   [&Match](const llvm::StringMap>
&Results,
@@ -151,6 +157,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -198,6 +205,7 @@
 
 void target() {
   A Foo = Gen();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -238,11 +246,13 @@
 TEST(TransferTest, ClassVarDecl) {
   std::string Code = R"(
 class A {
+ public:
   int Bar;
 };
 
 void target() {
   A Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -336,6 +346,10 @@
 
 void target() {
   A &Foo = getA();
+  (void)Foo.Bar.FooRef;
+  (void)Foo.Bar.FooPtr;
+  (void)Foo.Bar.BazRef;
+  (void)Foo.Bar.BazPtr;
   // [[p]]
 }
   )";
@@ -478,6 +492,10 @@
 
 void target() {
   A *Foo = getA();
+  (void)Foo->Bar->FooRef;
+  (void)Foo->Bar->FooPtr;
+  (void)Foo->Bar->BazRef;
+  (void)Foo->Bar->BazPtr;
   // [[p]]
 }
   )";
@@ -891,7 +909,7 @@
 };
 
 void target(A Foo) {
-  (void)0;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1052,6 +1070,9 @@
   int APrivate;
 public:
   int APublic;
+
+private:
+  friend void target();
 };
 
 class B : public A {
@@ -1060,10 +1081,20 @@
   int BProtected;
 private:
   int BPrivate;
+
+private:
+  friend void target();
 };
 
 void target() {
   B Foo;
+  (void)Foo.ADefault;
+  (void)Foo.AProtected;
+  (void)Foo.APrivate;
+  (void)Foo.APublic;
+  (void)Foo.BDefault;
+  (void)Foo.BProtected;
+  (void)Foo.BPrivate;
   // [[p]]
 }
   )";
@@ -1202,6 +1233,7 @@
 
 void target() {
   B Foo;
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1777,6 +1809,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1814,6 +1847,7 @@
 
 void target() {
   A Foo = A();
+  (void)Foo.Bar;
   // [[p]]
 }
   )";
@@ -1851,6 +1885,7 @@
 void target() {
   A Foo;
   A Bar;
+  (void)Foo.Baz;
   // [[p1]]
   Foo = Bar;
   // [[p2]]
@@ -1913,6 +1948,7 @@
 
 void target() {
   A Foo;
+  (void)Foo.Baz;
   A Bar = Foo;
   // [[p]]
 }
@@ -1958,6 +1994,7 @@
 
 void target() {
   

[PATCH] D141058: [clang-tidy] fix wrong fixup for bugprone-implicit-widening-of-multiplication-result

2023-01-05 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp:107
 << E->getSourceRange();
+auto LocForEndOfToken =
+Lexer::getLocForEndOfToken(E->getEndLoc(), 0, SM, LangOpts);

Please don't use `auto` unless type is explicitly stated in same statement or 
iterator.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp:221
 << IndexExpr->getSourceRange();
+auto LocForEndOfToken =
+Lexer::getLocForEndOfToken(IndexExpr->getEndLoc(), 0, SM, LangOpts);

Ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141058

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


[PATCH] D140507: Parse: handle another case of invalid handling for attributes

2023-01-05 Thread Saleem Abdulrasool via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG179d24d764ac: Parse: handle another case of invalid handling 
for attributes (authored by compnerd).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140507

Files:
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/test/Parser/cxx-attributes.cpp


Index: clang/test/Parser/cxx-attributes.cpp
===
--- clang/test/Parser/cxx-attributes.cpp
+++ clang/test/Parser/cxx-attributes.cpp
@@ -3,6 +3,8 @@
 // GH#58229 - rejects-valid
 __attribute__((__visibility__("default"))) [[nodiscard]] int f();
 [[nodiscard]] __attribute__((__visibility__("default"))) int f();
+extern "C" __attribute__((__visibility__("default"))) [[nodiscard]]
+int g() { return 32; }
 
 class c {
   virtual void f1(const char* a, ...)
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -359,8 +359,11 @@
 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
 
   ParsedAttributes DeclAttrs(AttrFactory);
-  MaybeParseCXX11Attributes(DeclAttrs);
-  ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
+  ParsedAttributes DeclSpecAttrs(AttrFactory);
+
+  while (MaybeParseCXX11Attributes(DeclAttrs) ||
+ MaybeParseGNUAttributes(DeclSpecAttrs))
+;
 
   if (Tok.isNot(tok::l_brace)) {
 // Reset the source range in DS, as the leading "extern"
@@ -369,7 +372,7 @@
 DS.SetRangeEnd(SourceLocation());
 // ... but anyway remember that such an "extern" was seen.
 DS.setExternInLinkageSpec(true);
-ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs, &DS);
+ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs, &DS);
 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  getCurScope(), LinkageSpec, SourceLocation())
: nullptr;
@@ -411,7 +414,7 @@
 default:
   ParsedAttributes DeclAttrs(AttrFactory);
   MaybeParseCXX11Attributes(DeclAttrs);
-  ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs);
+  ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
   continue;
 }
 


Index: clang/test/Parser/cxx-attributes.cpp
===
--- clang/test/Parser/cxx-attributes.cpp
+++ clang/test/Parser/cxx-attributes.cpp
@@ -3,6 +3,8 @@
 // GH#58229 - rejects-valid
 __attribute__((__visibility__("default"))) [[nodiscard]] int f();
 [[nodiscard]] __attribute__((__visibility__("default"))) int f();
+extern "C" __attribute__((__visibility__("default"))) [[nodiscard]]
+int g() { return 32; }
 
 class c {
   virtual void f1(const char* a, ...)
Index: clang/lib/Parse/ParseDeclCXX.cpp
===
--- clang/lib/Parse/ParseDeclCXX.cpp
+++ clang/lib/Parse/ParseDeclCXX.cpp
@@ -359,8 +359,11 @@
 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
 
   ParsedAttributes DeclAttrs(AttrFactory);
-  MaybeParseCXX11Attributes(DeclAttrs);
-  ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
+  ParsedAttributes DeclSpecAttrs(AttrFactory);
+
+  while (MaybeParseCXX11Attributes(DeclAttrs) ||
+ MaybeParseGNUAttributes(DeclSpecAttrs))
+;
 
   if (Tok.isNot(tok::l_brace)) {
 // Reset the source range in DS, as the leading "extern"
@@ -369,7 +372,7 @@
 DS.SetRangeEnd(SourceLocation());
 // ... but anyway remember that such an "extern" was seen.
 DS.setExternInLinkageSpec(true);
-ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs, &DS);
+ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs, &DS);
 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  getCurScope(), LinkageSpec, SourceLocation())
: nullptr;
@@ -411,7 +414,7 @@
 default:
   ParsedAttributes DeclAttrs(AttrFactory);
   MaybeParseCXX11Attributes(DeclAttrs);
-  ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs);
+  ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
   continue;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 179d24d - Parse: handle another case of invalid handling for attributes

2023-01-05 Thread Saleem Abdulrasool via cfe-commits

Author: Saleem Abdulrasool
Date: 2023-01-05T20:53:52Z
New Revision: 179d24d764ac68220047a8771e1bb06a7cb2a0da

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

LOG: Parse: handle another case of invalid handling for attributes

clang would improperly disallow GNU attributes before C++ standard
attributes when a declaration had a linkage specifier.  Handle this
similarly to the previous case of invalid parsing.  We now better match
the parsing rules from GCC.

Differential Revision: https://reviews.llvm.org/D140507
Reviewed By: aaron.ballman

Added: 


Modified: 
clang/lib/Parse/ParseDeclCXX.cpp
clang/test/Parser/cxx-attributes.cpp

Removed: 




diff  --git a/clang/lib/Parse/ParseDeclCXX.cpp 
b/clang/lib/Parse/ParseDeclCXX.cpp
index 53afdd7e7291d..b3ab5bcb238ab 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -359,8 +359,11 @@ Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, 
DeclaratorContext Context) {
 Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
 
   ParsedAttributes DeclAttrs(AttrFactory);
-  MaybeParseCXX11Attributes(DeclAttrs);
-  ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
+  ParsedAttributes DeclSpecAttrs(AttrFactory);
+
+  while (MaybeParseCXX11Attributes(DeclAttrs) ||
+ MaybeParseGNUAttributes(DeclSpecAttrs))
+;
 
   if (Tok.isNot(tok::l_brace)) {
 // Reset the source range in DS, as the leading "extern"
@@ -369,7 +372,7 @@ Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, 
DeclaratorContext Context) {
 DS.SetRangeEnd(SourceLocation());
 // ... but anyway remember that such an "extern" was seen.
 DS.setExternInLinkageSpec(true);
-ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs, &DS);
+ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs, &DS);
 return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  getCurScope(), LinkageSpec, SourceLocation())
: nullptr;
@@ -411,7 +414,7 @@ Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, 
DeclaratorContext Context) {
 default:
   ParsedAttributes DeclAttrs(AttrFactory);
   MaybeParseCXX11Attributes(DeclAttrs);
-  ParseExternalDeclaration(DeclAttrs, EmptyDeclSpecAttrs);
+  ParseExternalDeclaration(DeclAttrs, DeclSpecAttrs);
   continue;
 }
 

diff  --git a/clang/test/Parser/cxx-attributes.cpp 
b/clang/test/Parser/cxx-attributes.cpp
index 27cb8547c8b71..b46326c4d474f 100644
--- a/clang/test/Parser/cxx-attributes.cpp
+++ b/clang/test/Parser/cxx-attributes.cpp
@@ -3,6 +3,8 @@
 // GH#58229 - rejects-valid
 __attribute__((__visibility__("default"))) [[nodiscard]] int f();
 [[nodiscard]] __attribute__((__visibility__("default"))) int f();
+extern "C" __attribute__((__visibility__("default"))) [[nodiscard]]
+int g() { return 32; }
 
 class c {
   virtual void f1(const char* a, ...)



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


[PATCH] D140843: [clang-format] fix template closer followed by >

2023-01-05 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

In D140843#4028142 , @MyDeveloperDay 
wrote:

> I'd like one of @owenpan, @HazardyKnusperkeks  or @rymiel to comment before 
> commit, just to get another view.

Perhaps clang-format should never insert a space in `>>`.


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

https://reviews.llvm.org/D140843

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


[PATCH] D140860: [Diagnostics][NFC] Fix -Wlogical-op-parentheses warning inconsistency for const and constexpr values

2023-01-05 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D140860#4028089 , @hazohelet wrote:

> As you point out, enhancement may be more accurate than bug fix.
> There are rare cases where enabling a warning for missing parentheses in 
> `constexpr` logical expressions can be helpful, I think. For example, 
> consider the following code:
>
>   constexpr A = ...;
>   constexpr B = ...;
>   constexpr C = ...;
>   
>   static_assert(!(A && B || C));
>
> In this case, the static assertion will only be successful if `(A && B || C)` 
> evaluates to `false`, which is equivalent to the following combinations of 
> values for `A`, `B`, and `C`:
>
>   (A, B, C) = (T, F, F) (F, T, F) (F, F, F)
>
> Note that `T` means `true` and `F` means `false`. Here, `C` is always 
> `false`, so `A && B || C` matches the case of `a && b || 0`. Thus, the 
> warning is not issued before this patch.
> If the programmer is not careful and assumes that `(A && B || C)` is 
> equivalent to `(A && (B || C))`, then they expect the values of `A`, `B`, and 
> `C` to also include the following combinations:
>
>   (A, B, C) = (F, T, T) (F, F, T)
>
> This would require the programmer to consider additional, unnecessary 
> combinations after the successful static assertion.
>
> Enabling a warning for missing parentheses in this scenario could help 
> prevent the programmer from making this mistake.

Fair enough. I guess the same argument applies to the non-static case too. I 
think it was original mostly motivated by people using `&& "This is the reason 
for the assert"` without parentheses around the LHS & that was generally fine. 
So, so long as a string literal still does the suppression, it's probably fine.


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

https://reviews.llvm.org/D140860

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


[PATCH] D140584: [Clang] Refactor "Designators" into a unified implementation [NFC]

2023-01-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Drive by comment (I'll give a more thorough review when I have a moment): 
precommit CI seems to have found an issue to address.

`Assertion failed: false && "Invalid accessor", file 
C:\ws\w5\llvm-project\premerge-checks\clang\include\clang/AST/Designator.h, 
line 276`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140584

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


[clang] 8641687 - Revert "Revert "[-Wunsafe-buffer-usage] Add a new `forEachDescendant` matcher that skips callable declarations""

2023-01-05 Thread via cfe-commits

Author: ziqingluo-90
Date: 2023-01-05T12:04:13-08:00
New Revision: 8641687a4300ef3e9ef43eda46f6d2ea4e021dd9

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

LOG: Revert "Revert "[-Wunsafe-buffer-usage] Add a new `forEachDescendant` 
matcher that skips callable declarations""

This reverts commit f58b025354ee2d3bcd7ab2399a11429ec940c1e0.

 The previous revert reverts a patch that causes compilation problem on
 windows which can be reproduced using `-fdelayed-template-parsing`.
 I'm now to revert the patch back and commit a fix next.

Added: 


Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index a699d27c1544c..29c8dbb45fe9f 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -8,12 +8,111 @@
 
 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "llvm/ADT/SmallVector.h"
 
 using namespace llvm;
 using namespace clang;
 using namespace ast_matchers;
 
+namespace clang::ast_matchers::internal {
+// A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
+// except for those belonging to a 
diff erent callable of "n".
+class MatchDescendantVisitor
+: public RecursiveASTVisitor {
+public:
+  typedef RecursiveASTVisitor VisitorBase;
+
+  // Creates an AST visitor that matches `Matcher` on all
+  // descendants of a given node "n" except for the ones
+  // belonging to a 
diff erent callable of "n".
+  MatchDescendantVisitor(const DynTypedMatcher *Matcher, ASTMatchFinder 
*Finder,
+ BoundNodesTreeBuilder *Builder,
+ ASTMatchFinder::BindKind Bind)
+  : Matcher(Matcher), Finder(Finder), Builder(Builder), Bind(Bind),
+Matches(false) {}
+
+  // Returns true if a match is found in a subtree of `DynNode`, which belongs
+  // to the same callable of `DynNode`.
+  bool findMatch(const DynTypedNode &DynNode) {
+Matches = false;
+if (const Stmt *StmtNode = DynNode.get()) {
+  TraverseStmt(const_cast(StmtNode));
+  *Builder = ResultBindings;
+  return Matches;
+}
+return false;
+  }
+
+  // The following are overriding methods from the base visitor class.
+  // They are public only to allow CRTP to work. They are *not *part
+  // of the public API of this class.
+
+  // For the matchers so far used in safe buffers, we only need to match
+  // `Stmt`s.  To override more as needed.
+
+  bool TraverseDecl(Decl *Node) {
+if (!Node)
+  return true;
+if (!match(*Node))
+  return false;
+// To skip callables:
+if (isa(Node))
+  return true;
+// Traverse descendants
+return VisitorBase::TraverseDecl(Node);
+  }
+
+  bool TraverseStmt(Stmt *Node, DataRecursionQueue *Queue = nullptr) {
+if (!Node)
+  return true;
+if (!match(*Node))
+  return false;
+// To skip callables:
+if (isa(Node))
+  return true;
+return VisitorBase::TraverseStmt(Node);
+  }
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+  bool shouldVisitImplicitCode() const {
+// TODO: let's ignore implicit code for now
+return false;
+  }
+
+private:
+  // Sets 'Matched' to true if 'Matcher' matches 'Node'
+  //
+  // Returns 'true' if traversal should continue after this function
+  // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
+  template  bool match(const T &Node) {
+BoundNodesTreeBuilder RecursiveBuilder(*Builder);
+
+if (Matcher->matches(DynTypedNode::create(Node), Finder,
+ &RecursiveBuilder)) {
+  ResultBindings.addMatch(RecursiveBuilder);
+  Matches = true;
+  if (Bind != ASTMatchFinder::BK_All)
+return false; // Abort as soon as a match is found.
+}
+return true;
+  }
+
+  const DynTypedMatcher *const Matcher;
+  ASTMatchFinder *const Finder;
+  BoundNodesTreeBuilder *const Builder;
+  BoundNodesTreeBuilder ResultBindings;
+  const ASTMatchFinder::BindKind Bind;
+  bool Matches;
+};
+
+AST_MATCHER_P(Stmt, forEveryDescendant, Matcher, innerMatcher) {
+  MatchDescendantVisitor Visitor(new DynTypedMatcher(innerMatcher), Finder,
+ Builder, ASTMatchFinder::BK_All);
+  return Visitor.findMatch(DynTypedNode::create(Node));
+}
+} // namespace clang::ast_matchers::internal
+
 namespace {
 // Because the analysis revolves around variables and their types, we'll need 
to
 // track uses of variables (aka DeclRefExprs).
@@ -398,7 +497,7 @@ static std::pair 
findGadgets(const Decl *D) {
 
   // clang-format off
   M.ad

[clang] ef47a0a - [Fix]"[-Wunsafe-buffer-usage] Add a new `forEachDescendant` matcher that skips callable declarations"

2023-01-05 Thread via cfe-commits

Author: ziqingluo-90
Date: 2023-01-05T12:04:13-08:00
New Revision: ef47a0a711f12add401394f7af07a0b4d1635b56

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

LOG: [Fix]"[-Wunsafe-buffer-usage] Add a new `forEachDescendant` matcher that 
skips callable declarations"

The original patch in commit b2ac5fd724c44cf662caed84bd8f84af574b981d
causes compilation errors which can be reproduced by the
`-fdelayed-template-parsing` flag.  This commit fixes the problem.

Related differential revision: https://reviews.llvm.org/D138329

Added: 


Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 29c8dbb45fe9f..80a54c3ad38b7 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -15,7 +15,7 @@ using namespace llvm;
 using namespace clang;
 using namespace ast_matchers;
 
-namespace clang::ast_matchers::internal {
+namespace clang::ast_matchers {
 // A `RecursiveASTVisitor` that traverses all descendants of a given node "n"
 // except for those belonging to a 
diff erent callable of "n".
 class MatchDescendantVisitor
@@ -26,9 +26,10 @@ class MatchDescendantVisitor
   // Creates an AST visitor that matches `Matcher` on all
   // descendants of a given node "n" except for the ones
   // belonging to a 
diff erent callable of "n".
-  MatchDescendantVisitor(const DynTypedMatcher *Matcher, ASTMatchFinder 
*Finder,
- BoundNodesTreeBuilder *Builder,
- ASTMatchFinder::BindKind Bind)
+  MatchDescendantVisitor(const internal::DynTypedMatcher *Matcher,
+ internal::ASTMatchFinder *Finder,
+ internal::BoundNodesTreeBuilder *Builder,
+ internal::ASTMatchFinder::BindKind Bind)
   : Matcher(Matcher), Finder(Finder), Builder(Builder), Bind(Bind),
 Matches(false) {}
 
@@ -86,32 +87,32 @@ class MatchDescendantVisitor
   // Returns 'true' if traversal should continue after this function
   // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
   template  bool match(const T &Node) {
-BoundNodesTreeBuilder RecursiveBuilder(*Builder);
+internal::BoundNodesTreeBuilder RecursiveBuilder(*Builder);
 
 if (Matcher->matches(DynTypedNode::create(Node), Finder,
  &RecursiveBuilder)) {
   ResultBindings.addMatch(RecursiveBuilder);
   Matches = true;
-  if (Bind != ASTMatchFinder::BK_All)
+  if (Bind != internal::ASTMatchFinder::BK_All)
 return false; // Abort as soon as a match is found.
 }
 return true;
   }
 
-  const DynTypedMatcher *const Matcher;
-  ASTMatchFinder *const Finder;
-  BoundNodesTreeBuilder *const Builder;
-  BoundNodesTreeBuilder ResultBindings;
-  const ASTMatchFinder::BindKind Bind;
+  const internal::DynTypedMatcher *const Matcher;
+  internal::ASTMatchFinder *const Finder;
+  internal::BoundNodesTreeBuilder *const Builder;
+  internal::BoundNodesTreeBuilder ResultBindings;
+  const internal::ASTMatchFinder::BindKind Bind;
   bool Matches;
 };
 
-AST_MATCHER_P(Stmt, forEveryDescendant, Matcher, innerMatcher) {
+AST_MATCHER_P(Stmt, forEveryDescendant, internal::Matcher, innerMatcher) 
{
   MatchDescendantVisitor Visitor(new DynTypedMatcher(innerMatcher), Finder,
  Builder, ASTMatchFinder::BK_All);
   return Visitor.findMatch(DynTypedNode::create(Node));
 }
-} // namespace clang::ast_matchers::internal
+} // namespace clang::ast_matchers
 
 namespace {
 // Because the analysis revolves around variables and their types, we'll need 
to



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


[PATCH] D140817: [Driver] move NetBSD header search path management to the driver

2023-01-05 Thread Vlad Vereschaka via Phabricator via cfe-commits
vvereschaka added a comment.

Hi @brad ,

would you fix the tests
https://lab.llvm.org/buildbot/#/builders/60/builds/10125

looks like the problem is here:

  // DRIVER-PASS-INCLUDES:  "-internal-externc-isystem" "/usr/include"

could be another path instead of "/usr/include".

this one should work for the most cases

  // DRIVER-PASS-INCLUDES:  "-internal-externc-isystem" "{{.*}}/usr/include"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140817

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


[PATCH] D140639: clang: Fix handling of __builtin_elementwise_copysign

2023-01-05 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm updated this revision to Diff 486643.
arsenm added a comment.

Return S.Diag


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

https://reviews.llvm.org/D140639

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/builtins-elementwise-math.c

Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -1,5 +1,8 @@
 // RUN: %clang_cc1 -std=c99 %s -pedantic -verify -triple=x86_64-apple-darwin9
 
+typedef double double2 __attribute__((ext_vector_type(2)));
+typedef double double4 __attribute__((ext_vector_type(4)));
+typedef float float2 __attribute__((ext_vector_type(2)));
 typedef float float4 __attribute__((ext_vector_type(4)));
 typedef int int3 __attribute__((ext_vector_type(3)));
 typedef unsigned unsigned3 __attribute__((ext_vector_type(3)));
@@ -13,6 +16,11 @@
 typedef int bar;
 bar b;
 
+__attribute__((address_space(1))) float float_as_one;
+typedef float waffle;
+waffle waf;
+
+
 void test_builtin_elementwise_abs(int i, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
   struct Foo s = __builtin_elementwise_abs(i);
   // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
@@ -406,12 +414,12 @@
   // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
 }
 
-void test_builtin_elementwise_copysign(int i, short s, double d, float4 v, int3 iv, unsigned3 uv, int *p) {
+void test_builtin_elementwise_copysign(int i, short s, double d, float f, float4 v, int3 iv, unsigned3 uv, int *p) {
   i = __builtin_elementwise_copysign(p, d);
-  // expected-error@-1 {{arguments are of different types ('int *' vs 'double')}}
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int *')}}
 
-  struct Foo foo = __builtin_elementwise_copysign(i, i);
-  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'int'}}
+  i = __builtin_elementwise_copysign(i, i);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
 
   i = __builtin_elementwise_copysign(i);
   // expected-error@-1 {{too few arguments to function call, expected 2, have 1}}
@@ -423,40 +431,81 @@
   // expected-error@-1 {{too many arguments to function call, expected 2, have 3}}
 
   i = __builtin_elementwise_copysign(v, iv);
-  // expected-error@-1 {{arguments are of different types ('float4' (vector of 4 'float' values) vs 'int3' (vector of 3 'int' values))}}
+  // expected-error@-1 {{2nd argument must be a floating point type (was 'int3' (vector of 3 'int' values))}}
 
   i = __builtin_elementwise_copysign(uv, iv);
-  // expected-error@-1 {{arguments are of different types ('unsigned3' (vector of 3 'unsigned int' values) vs 'int3' (vector of 3 'int' values))}}
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned3' (vector of 3 'unsigned int' values))}}
 
   s = __builtin_elementwise_copysign(i, s);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
+
+  f = __builtin_elementwise_copysign(f, i);
+  // expected-error@-1 {{2nd argument must be a floating point type (was 'int')}}
+
+  f = __builtin_elementwise_copysign(i, f);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
 
   enum e { one,
two };
   i = __builtin_elementwise_copysign(one, two);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
 
   enum f { three };
   enum f x = __builtin_elementwise_copysign(one, three);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
 
   _BitInt(32) ext; // expected-warning {{'_BitInt' in C17 and earlier is a Clang extension}}
   ext = __builtin_elementwise_copysign(ext, ext);
+  // expected-error@-1 {{1st argument must be a floating point type (was '_BitInt(32)')}}
 
-  const int ci;
-  i = __builtin_elementwise_copysign(ci, i);
-  i = __builtin_elementwise_copysign(i, ci);
-  i = __builtin_elementwise_copysign(ci, ci);
+  const float cf32;
+  f = __builtin_elementwise_copysign(cf32, f);
+  f = __builtin_elementwise_copysign(f, cf32);
+  f = __builtin_elementwise_copysign(cf32, f);
 
-  i = __builtin_elementwise_copysign(i, int_as_one); // ok (attributes don't match)?
-  i = __builtin_elementwise_copysign(i, b);  // ok (sugar doesn't match)?
+  f = __builtin_elementwise_copysign(f, float_as_one); // ok (attributes don't match)?
+  f = __builtin_elementwise_copysign(f, waf);  // ok (sugar doesn't match)?
 
-  int A[10];
+  float A[10];
   A = __builtin_elementwise_copysign(A, A);
-  // expected-error@-1 {{1st argument must be a vector, integer or floating point type (was 'int *')}}
+  // expected-error@-1 {{1st argument must be a floating point type (wa

  1   2   3   >