[PATCH] D120793: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Iain Sandoe via Phabricator via cfe-commits
iains accepted this revision.
iains added a comment.
This revision is now accepted and ready to land.

other than the two nits, LGTM




Comment at: clang/include/clang/Sema/Sema.h:2996-2997
   /// \param ImportLoc The location of the 'import' keyword.
   /// \param Path The module toplevel name as an access path.
-  /// \param Partition The module partition name as an access path.
+  /// \param IsPartition If we are dealing with partitions.
   DeclResult ActOnModuleImport(SourceLocation StartLoc,

maybe:
"If the name is for a partition."


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120793

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


[PATCH] D120793: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Iain Sandoe via Phabricator via cfe-commits
iains added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:415
+  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
 }
 

it looks like there is an extra blank line before the closing brace..


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120793

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


[PATCH] D117887: [NVPTX] Expose float tys min, max, abs, neg as builtins

2022-03-02 Thread Jakub Chlanda via Phabricator via cfe-commits
jchlanda added a comment.
Herald added a project: All.

In D117887#3352079 , @tra wrote:

> In D117887#3351257 , @jchlanda 
> wrote:
>
>> @tra thank you for landing the patches, it seems that the clang part 
>> (builtin declarations and tests) have been dropped, only `llvm` dir changes 
>> made it through. Is there any way I could fix it (same goes for the other 
>> two patches in this stack)?
>
> Somehow `arc export | git apply` didn't pick clang changes when I was 
> transferring the patch from the phabricator. I'll re-fetch the patches and 
> will land the missing pieces shortly.
>
> I'm not sure how the you've submitted the patch to phabricator. In general, 
> it works best when the patch is supplied as a gic commit diff, with the 
> author metadata, etc. 
> Or via `arc diff`. See for the details. 
> https://llvm.org/docs/Phabricator.html#phabricator-reviews

I went with the web interface as described here: 
https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface
 
with `git diff -U99 ...` didn't want to bite the bullet of `arc`, hoping 
that github PRs will soon be a thing.

All working now, thank you for resolving that so quickly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117887

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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-03-02 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 412334.
Herald added a project: All.

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

https://reviews.llvm.org/D116593

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
@@ -109,7 +109,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
@@ -381,3 +381,21 @@
   // CHECK-FIXES: void templateFunction(ExpensiveToCopyType E) {
   E.constReference();
 }
+
+template  T templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:73: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template  T templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return T();
+}
+
+template <> bool templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:69: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template <> bool templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return true;
+}
+
+template <> int templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:68: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template <> int templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return 0;
+}
Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
@@ -69,7 +69,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -116,6 +116,10 @@
   ` related to passing
   arguments that refer to program elements without a trivial identifier.
 
+- Fixed a crash in :doc:`performance-unnecessary-value-param
+  ` when the specialization
+  template has an unnecessary value paramter. Removed the fix for a template.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -51,18 +51,6 @@
   return Matches.empty();
 }
 
-bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
-  if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
-if (SpecializationInfo->getTemplateSpecializationKind() ==
-TSK_ExplicitSpecialization)
-  return true;
-  if (const auto *Method = llvm::dyn_cast(&Function))
-if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
-Method->getMemberSpecializationInfo()->isExplicitSpecialization())
-  return true;
-  return false;
-}
-
 } // namespace
 
 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
@@ -146,11 +134,12 @@
   // 2. the function is virtual as it might break overrides
   // 3. the function is referenced outside of a call expression within the
   //compilation unit as the signature change could introduce build errors.
-  // 4. the function is an explicit template specialization.
+  // 4. the function is a primary template or an explicit template
+  // specialization.
   const auto *Method = llvm::dyn_cast(Function);
   if (Param->getBeginLoc().isMacroID() || (Method && Method->isVirtual()) ||
   isReferencedOutsideOfCallExpr(*Func

[PATCH] D120764: [C++20][Modules] Improve efficiency of isModuleParition method.

2022-03-02 Thread Iain Sandoe via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG17ce5497aa01: [C++20][Modules] Improve efficiency of 
isModulePartition method. (authored by iains).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120764

Files:
  clang/include/clang/Basic/Module.h


Index: clang/include/clang/Basic/Module.h
===
--- clang/include/clang/Basic/Module.h
+++ clang/include/clang/Basic/Module.h
@@ -515,12 +515,14 @@
   }
 
   /// Is this a module partition.
-  bool isModulePartition() const { return Name.find(':') != std::string::npos; 
}
+  bool isModulePartition() const {
+return Kind == ModulePartitionInterface ||
+   Kind == ModulePartitionImplementation;
+  }
 
   /// Get the primary module interface name from a partition.
   StringRef getPrimaryModuleInterfaceName() const {
-if (Kind == ModulePartitionInterface ||
-Kind == ModulePartitionImplementation) {
+if (isModulePartition()) {
   auto pos = Name.find(':');
   return StringRef(Name.data(), pos);
 }


Index: clang/include/clang/Basic/Module.h
===
--- clang/include/clang/Basic/Module.h
+++ clang/include/clang/Basic/Module.h
@@ -515,12 +515,14 @@
   }
 
   /// Is this a module partition.
-  bool isModulePartition() const { return Name.find(':') != std::string::npos; }
+  bool isModulePartition() const {
+return Kind == ModulePartitionInterface ||
+   Kind == ModulePartitionImplementation;
+  }
 
   /// Get the primary module interface name from a partition.
   StringRef getPrimaryModuleInterfaceName() const {
-if (Kind == ModulePartitionInterface ||
-Kind == ModulePartitionImplementation) {
+if (isModulePartition()) {
   auto pos = Name.find(':');
   return StringRef(Name.data(), pos);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 17ce549 - [C++20][Modules] Improve efficiency of isModulePartition method.

2022-03-02 Thread Iain Sandoe via cfe-commits

Author: Iain Sandoe
Date: 2022-03-02T08:31:46Z
New Revision: 17ce5497aa016707b31a2e99a05ec7451ba4014d

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

LOG: [C++20][Modules] Improve efficiency of isModulePartition method.

The original implementation of this used the presence of a ":" in the module
name as the key, but since we now generate modules with the correct kind, we
can just test that.

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

Added: 


Modified: 
clang/include/clang/Basic/Module.h

Removed: 




diff  --git a/clang/include/clang/Basic/Module.h 
b/clang/include/clang/Basic/Module.h
index ac3bb1b3ef109..5b97044524553 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -515,12 +515,14 @@ class Module {
   }
 
   /// Is this a module partition.
-  bool isModulePartition() const { return Name.find(':') != std::string::npos; 
}
+  bool isModulePartition() const {
+return Kind == ModulePartitionInterface ||
+   Kind == ModulePartitionImplementation;
+  }
 
   /// Get the primary module interface name from a partition.
   StringRef getPrimaryModuleInterfaceName() const {
-if (Kind == ModulePartitionInterface ||
-Kind == ModulePartitionImplementation) {
+if (isModulePartition()) {
   auto pos = Name.find(':');
   return StringRef(Name.data(), pos);
 }



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


[PATCH] D116593: Fix `performance-unnecessary-value-param` for template specialization

2022-03-02 Thread gehry via Phabricator via cfe-commits
Sockke updated this revision to Diff 412340.

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

https://reviews.llvm.org/D116593

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param.cpp
@@ -109,7 +109,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
@@ -381,3 +381,21 @@
   // CHECK-FIXES: void templateFunction(ExpensiveToCopyType E) {
   E.constReference();
 }
+
+template  T templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:73: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template  T templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return T();
+}
+
+template <> bool templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:69: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template <> bool templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return true;
+}
+
+template <> int templateSpecializationFunction(ExpensiveToCopyType E) {
+  // CHECK-MESSAGES: [[@LINE-1]]:68: warning: the parameter 'E' is copied
+  // CHECK-FIXES-NOT: template <> int templateSpecializationFunction(const ExpensiveToCopyType& E) {
+  return 0;
+}
Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-value-param-delayed.cpp
@@ -69,7 +69,7 @@
 
 template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType S, T V) {
   // CHECK-MESSAGES: [[@LINE-1]]:90: warning: the const qualified parameter 'S'
-  // CHECK-FIXES: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
+  // CHECK-FIXES-NOT: template  void templateWithNonTemplatizedParameter(const ExpensiveToCopyType& S, T V) {
 }
 
 void instantiated() {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -116,6 +116,10 @@
   ` when a pure virtual function
   overrided has a const return type. Removed the fix for a virtual function.
 
+- Fixed a crash in :doc:`performance-unnecessary-value-param
+  ` when the specialization
+  template has an unnecessary value paramter. Removed the fix for a template.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
@@ -51,18 +51,6 @@
   return Matches.empty();
 }
 
-bool isExplicitTemplateSpecialization(const FunctionDecl &Function) {
-  if (const auto *SpecializationInfo = Function.getTemplateSpecializationInfo())
-if (SpecializationInfo->getTemplateSpecializationKind() ==
-TSK_ExplicitSpecialization)
-  return true;
-  if (const auto *Method = llvm::dyn_cast(&Function))
-if (Method->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
-Method->getMemberSpecializationInfo()->isExplicitSpecialization())
-  return true;
-  return false;
-}
-
 } // namespace
 
 UnnecessaryValueParamCheck::UnnecessaryValueParamCheck(
@@ -146,11 +134,12 @@
   // 2. the function is virtual as it might break overrides
   // 3. the function is referenced outside of a call expression within the
   //compilation unit as the signature change could introduce build errors.
-  // 4. the function is an explicit template specialization.
+  // 4. the function is a primary template or an explicit template
+  // specialization.
   const auto *Method = llvm::dyn_cast(Function);
   if (Param->getBeginLoc().isMacroID() || (Method && Method->isVirtual()) ||
   isReferencedOutsideOfCallExpr(*Function, *Result.C

[clang] 28efb1c - [pseudo] Fix an out-of-bound error in LRTable::find.

2022-03-02 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-03-02T09:53:52+01:00
New Revision: 28efb1ccf5eabd25119a3a7df2c2c1f1407dbfec

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

LOG: [pseudo] Fix an out-of-bound error in LRTable::find.

The linear scan should not escape the TargetedStates range.

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

Added: 


Modified: 
clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
clang/test/Syntax/lr-build-basic.test

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp 
b/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
index 23c455941ff5b..4f1494fff277d 100644
--- a/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ b/clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -110,14 +110,13 @@ llvm::ArrayRef LRTable::find(StateID 
Src, SymbolID ID) const {
 
   assert(llvm::is_sorted(TargetedStates) &&
  "subrange of the StateIdx should be sorted!");
-  const LRTable::StateID *It = llvm::partition_point(
+  const LRTable::StateID *Start = llvm::partition_point(
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
-return {};
-  size_t Start = It - States.data(), End = Start;
-  while (End < States.size() && States[End] == Src)
+  const LRTable::StateID *End = Start;
+  while (End != TargetedStates.end() && *End == Src)
 ++End;
-  return llvm::makeArrayRef(&Actions[Start], End - Start);
+  return llvm::makeArrayRef(&Actions[Start - States.data()],
+/*length=*/End - Start);
 }
 
 } // namespace pseudo

diff  --git a/clang/test/Syntax/lr-build-basic.test 
b/clang/test/Syntax/lr-build-basic.test
index d6538338991e1..d02fdaefd7c2c 100644
--- a/clang/test/Syntax/lr-build-basic.test
+++ b/clang/test/Syntax/lr-build-basic.test
@@ -1,24 +1,29 @@
 _ := expr
-expr := IDENTIFIER
+expr := id
+id := IDENTIFIER
 
 # RUN: clang-pseudo -grammar %s -print-graph | FileCheck %s 
--check-prefix=GRAPH
 #  GRAPH: States:
 # GRPAH-NEXT: State 0
 # GRPAH-NEXT: _ :=  • expr
-# GRPAH-NEXT: expr :=  • IDENTIFIER
+# GRPAH-NEXT: expr :=  • id
+# GRPAH-NEXT: id :=  • IDENTIFIER
 # GRPAH-NEXT: State 1
 # GRPAH-NEXT: _ := expr • 
 # GRPAH-NEXT: State 2
-# GRPAH-NEXT: expr := IDENTIFIER • 
-# GRPAH-NEXT: 0 ->[expr] 1
-# GRPAH-NEXT: 0 ->[IDENTIFIER] 2
+# GRPAH-NEXT: expr := id • 
+# GRPAH-NEXT: State 3
+# GRPAH-NEXT: id := IDENTIFIER • 
 
 # RUN: clang-pseudo -grammar %s -print-table | FileCheck %s 
--check-prefix=TABLE
 #  TABLE: LRTable:
 # TABLE-NEXT: State 0
-# TABLE-NEXT: 'IDENTIFIER': shift state 2
+# TABLE-NEXT: 'IDENTIFIER': shift state 3
 # TABLE-NEXT: 'expr': go to state 1
+# TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
 # TABLE-NEXT: 'EOF': accept
 # TABLE-NEXT: State 2
-# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
+# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
+# TABLE-NEXT: State 3
+# TABLE-NEXT: 'EOF': reduce by rule 2 'id := IDENTIFIER'



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


[PATCH] D120723: [pseudo] Fix an out-of-bound error in LRTable::find.

2022-03-02 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rG28efb1ccf5ea: [pseudo] Fix an out-of-bound error in 
LRTable::find. (authored by hokein).
Herald added a project: All.

Changed prior to commit:
  https://reviews.llvm.org/D120723?vs=412085&id=412341#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120723

Files:
  clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
  clang/test/Syntax/lr-build-basic.test


Index: clang/test/Syntax/lr-build-basic.test
===
--- clang/test/Syntax/lr-build-basic.test
+++ clang/test/Syntax/lr-build-basic.test
@@ -1,24 +1,29 @@
 _ := expr
-expr := IDENTIFIER
+expr := id
+id := IDENTIFIER
 
 # RUN: clang-pseudo -grammar %s -print-graph | FileCheck %s 
--check-prefix=GRAPH
 #  GRAPH: States:
 # GRPAH-NEXT: State 0
 # GRPAH-NEXT: _ :=  • expr
-# GRPAH-NEXT: expr :=  • IDENTIFIER
+# GRPAH-NEXT: expr :=  • id
+# GRPAH-NEXT: id :=  • IDENTIFIER
 # GRPAH-NEXT: State 1
 # GRPAH-NEXT: _ := expr • 
 # GRPAH-NEXT: State 2
-# GRPAH-NEXT: expr := IDENTIFIER • 
-# GRPAH-NEXT: 0 ->[expr] 1
-# GRPAH-NEXT: 0 ->[IDENTIFIER] 2
+# GRPAH-NEXT: expr := id • 
+# GRPAH-NEXT: State 3
+# GRPAH-NEXT: id := IDENTIFIER • 
 
 # RUN: clang-pseudo -grammar %s -print-table | FileCheck %s 
--check-prefix=TABLE
 #  TABLE: LRTable:
 # TABLE-NEXT: State 0
-# TABLE-NEXT: 'IDENTIFIER': shift state 2
+# TABLE-NEXT: 'IDENTIFIER': shift state 3
 # TABLE-NEXT: 'expr': go to state 1
+# TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
 # TABLE-NEXT: 'EOF': accept
 # TABLE-NEXT: State 2
-# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
+# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
+# TABLE-NEXT: State 3
+# TABLE-NEXT: 'EOF': reduce by rule 2 'id := IDENTIFIER'
Index: clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
===
--- clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -110,14 +110,13 @@
 
   assert(llvm::is_sorted(TargetedStates) &&
  "subrange of the StateIdx should be sorted!");
-  const LRTable::StateID *It = llvm::partition_point(
+  const LRTable::StateID *Start = llvm::partition_point(
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
-return {};
-  size_t Start = It - States.data(), End = Start;
-  while (End < States.size() && States[End] == Src)
+  const LRTable::StateID *End = Start;
+  while (End != TargetedStates.end() && *End == Src)
 ++End;
-  return llvm::makeArrayRef(&Actions[Start], End - Start);
+  return llvm::makeArrayRef(&Actions[Start - States.data()],
+/*length=*/End - Start);
 }
 
 } // namespace pseudo


Index: clang/test/Syntax/lr-build-basic.test
===
--- clang/test/Syntax/lr-build-basic.test
+++ clang/test/Syntax/lr-build-basic.test
@@ -1,24 +1,29 @@
 _ := expr
-expr := IDENTIFIER
+expr := id
+id := IDENTIFIER
 
 # RUN: clang-pseudo -grammar %s -print-graph | FileCheck %s --check-prefix=GRAPH
 #  GRAPH: States:
 # GRPAH-NEXT: State 0
 # GRPAH-NEXT: _ :=  • expr
-# GRPAH-NEXT: expr :=  • IDENTIFIER
+# GRPAH-NEXT: expr :=  • id
+# GRPAH-NEXT: id :=  • IDENTIFIER
 # GRPAH-NEXT: State 1
 # GRPAH-NEXT: _ := expr • 
 # GRPAH-NEXT: State 2
-# GRPAH-NEXT: expr := IDENTIFIER • 
-# GRPAH-NEXT: 0 ->[expr] 1
-# GRPAH-NEXT: 0 ->[IDENTIFIER] 2
+# GRPAH-NEXT: expr := id • 
+# GRPAH-NEXT: State 3
+# GRPAH-NEXT: id := IDENTIFIER • 
 
 # RUN: clang-pseudo -grammar %s -print-table | FileCheck %s --check-prefix=TABLE
 #  TABLE: LRTable:
 # TABLE-NEXT: State 0
-# TABLE-NEXT: 'IDENTIFIER': shift state 2
+# TABLE-NEXT: 'IDENTIFIER': shift state 3
 # TABLE-NEXT: 'expr': go to state 1
+# TABLE-NEXT: 'id': go to state 2
 # TABLE-NEXT: State 1
 # TABLE-NEXT: 'EOF': accept
 # TABLE-NEXT: State 2
-# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := IDENTIFIER'
+# TABLE-NEXT: 'EOF': reduce by rule 1 'expr := id'
+# TABLE-NEXT: State 3
+# TABLE-NEXT: 'EOF': reduce by rule 2 'id := IDENTIFIER'
Index: clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
===
--- clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
+++ clang/lib/Tooling/Syntax/Pseudo/LRTable.cpp
@@ -110,14 +110,13 @@
 
   assert(llvm::is_sorted(TargetedStates) &&
  "subrange of the StateIdx should be sorted!");
-  const LRTable::StateID *It = llvm::partition_point(
+  const LRTable::StateID *Start = llvm::partition_point(
   TargetedStates, [&Src](LRTable::StateID S) { return S < Src; });
-  if (It == TargetedStates.end())
-return {};
-  si

[clang] ae60884 - [clang][dataflow] Add flow condition constraints to Environment

2022-03-02 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-03-02T08:57:27Z
New Revision: ae60884dfe16a8f9382d778e4eef61bf9703e1f5

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

LOG: [clang][dataflow] Add flow condition constraints to Environment

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.

Reviewed-by: ymandel, xazax.hun

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

Added: 
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp

Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/CMakeLists.txt
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
clang/unittests/Analysis/FlowSensitive/TestingSupport.h
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index 52f738d59b812..8df88301dff83 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -17,6 +17,7 @@
 
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
+#include "clang/Analysis/FlowSensitive/Solver.h"
 #include "clang/Analysis/FlowSensitive/StorageLocation.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "llvm/ADT/DenseMap.h"
@@ -33,9 +34,19 @@ namespace dataflow {
 /// is used during dataflow analysis.
 class DataflowAnalysisContext {
 public:
-  DataflowAnalysisContext()
-  : TrueVal(takeOwnership(std::make_unique())),
-FalseVal(takeOwnership(std::make_unique())) {}
+  /// Constructs a dataflow analysis context.
+  ///
+  /// Requirements:
+  ///
+  ///  `S` must not be null.
+  DataflowAnalysisContext(std::unique_ptr S)
+  : S(std::move(S)), TrueVal(createAtomicBoolValue()),
+FalseVal(createAtomicBoolValue()) {
+assert(this->S != nullptr);
+  }
+
+  /// Returns the SAT solver instance that is available in this context.
+  Solver &getSolver() const { return *S; }
 
   /// Takes ownership of `Loc` and returns a reference to it.
   ///
@@ -119,7 +130,30 @@ class DataflowAnalysisContext {
 return Value ? TrueVal : FalseVal;
   }
 
+  /// Creates an atomic boolean value.
+  AtomicBoolValue &createAtomicBoolValue() {
+return takeOwnership(std::make_unique());
+  }
+
+  /// Returns a boolean value that represents the conjunction of `LHS` and
+  /// `RHS`. Subsequent calls with the same arguments, regardless of their
+  /// order, will return the same result. If the given boolean values represent
+  /// the same value, the result will be the value itself.
+  BoolValue &getOrCreateConjunctionValue(BoolValue &LHS, BoolValue &RHS);
+
+  /// Returns a boolean value that represents the disjunction of `LHS` and
+  /// `RHS`. Subsequent calls with the same arguments, regardless of their
+  /// order, will return the same result. If the given boolean values represent
+  /// the same value, the result will be the value itself.
+  BoolValue &getOrCreateDisjunctionValue(BoolValue &LHS, BoolValue &RHS);
+
+  /// Returns a boolean value that represents the negation of `Val`. Subsequent
+  /// calls with the same argument will return the same result.
+  BoolValue &getOrCreateNegationValue(BoolValue &Val);
+
 private:
+  std::unique_ptr S;
+
   // Storage for the state of a program.
   std::vector> Locs;
   std::vector> Vals;
@@ -134,9 +168,16 @@ class DataflowAnalysisContext {
 
   StorageLocation *ThisPointeeLoc = nullptr;
 
-  // FIXME: Add support for boolean expressions.
   AtomicBoolValue &TrueVal;
   AtomicBoolValue &FalseVal;
+
+  // Indices that are used to avoid recreating the same composite boolean
+  // values.
+  llvm::DenseMap, ConjunctionValue *>
+  ConjunctionVals;
+  llvm::DenseMap, DisjunctionValue *>
+  DisjunctionVals;
+  llvm::DenseMap NegationVals;
 };
 
 } // namespace dataflow

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index d82b8b4386d18..6150d0d8f5c1d 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -235,6 +235,56 @@ class Environment {
 return DACtx->getBoolLiteralValue(Value);
   }
 
+  /// Returns an atomic boole

[PATCH] D120711: [clang][dataflow] Add flow condition constraints to Environment

2022-03-02 Thread Stanislav Gatev 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 rGae60884dfe16: [clang][dataflow] Add flow condition 
constraints to Environment (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120711

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/CMakeLists.txt
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
  clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTest.cpp
  clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
  clang/unittests/Analysis/FlowSensitive/TestingSupport.h
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -68,7 +69,7 @@
   ControlFlowContext::build(nullptr, Body, &AST->getASTContext()));
 
   AnalysisT Analysis = MakeAnalysis(AST->getASTContext());
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx);
 
   return runDataflowAnalysis(CFCtx, Analysis, Env);
Index: clang/unittests/Analysis/FlowSensitive/TestingSupport.h
===
--- clang/unittests/Analysis/FlowSensitive/TestingSupport.h
+++ clang/unittests/Analysis/FlowSensitive/TestingSupport.h
@@ -23,6 +23,7 @@
 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Serialization/PCHContainerOperations.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
@@ -104,7 +105,7 @@
   if (!CFCtx)
 return CFCtx.takeError();
 
-  DataflowAnalysisContext DACtx;
+  DataflowAnalysisContext DACtx(std::make_unique());
   Environment Env(DACtx, *F);
   auto Analysis = MakeAnalysis(Context, Env);
 
Index: clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
===
--- /dev/null
+++ clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -0,0 +1,57 @@
+//===- unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace {
+
+using namespace clang;
+using namespace dataflow;
+
+class EnvironmentTest : public ::testing::Test {
+  DataflowAnalysisContext Context;
+
+protected:
+  EnvironmentTest()
+  : Context(std::make_unique()), Env(Context) {}
+
+  Environment Env;
+};
+
+TEST_F(EnvironmentTest, MakeImplicationReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeImplication(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, MakeIffReturnsTrueGivenSameArgs) {
+  auto &X = Env.makeAtomicBoolValue();
+  auto &XEqX = Env.makeIff(X, X);
+  EXPECT_EQ(&XEqX, &Env.getBoolLiteralValue(true));
+}
+
+TEST_F(EnvironmentTest, FlowCondition) {
+  EXPECT_TRUE(Env.flowConditionImplies(Env.getBoolLiteralValue(true)));
+  EXPECT_FALSE(Env.flowConditionImplies(Env.getBoolLiteralValue(false)));
+
+  auto &X = Env.makeAtomicBoolValue();
+  EXPECT_FALSE(Env.flowConditionImplies(X));
+
+  Env.addToFlowCondition(X);
+  EXPECT_TRUE(Env.flowConditionImplies(X));
+
+  auto &NotX = Env.makeNot(X);
+  EXPECT_FALSE(Env.flowConditionImplies(NotX));
+}
+
+} // namespace
Index: clang/unittests/Analysis/FlowSensitive/DataflowAnalysisContextTe

[clang] 7f99e18 - [pseudo] Add a print-grammar option in the tool

2022-03-02 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-03-02T10:05:49+01:00
New Revision: 7f99e1870f776a25e03526e3190105c094750d98

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

LOG: [pseudo] Add a print-grammar option in the tool

This is helpful for debugging purposes.

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

Added: 


Modified: 
clang/tools/clang-pseudo/ClangPseudo.cpp

Removed: 




diff  --git a/clang/tools/clang-pseudo/ClangPseudo.cpp 
b/clang/tools/clang-pseudo/ClangPseudo.cpp
index 2d6fbdb83944c..59db927d8e081 100644
--- a/clang/tools/clang-pseudo/ClangPseudo.cpp
+++ b/clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -24,6 +24,7 @@ using llvm::cl::opt;
 
 static opt
 Grammar("grammar", desc("Parse and check a BNF grammar file."), init(""));
+static opt PrintGrammar("print-grammar", desc("Print the grammar."));
 static opt PrintGraph("print-graph",
 desc("Print the LR graph for the grammar"));
 static opt PrintTable("print-table",
@@ -60,6 +61,8 @@ int main(int argc, char *argv[]) {
 }
 llvm::outs() << llvm::formatv("grammar file {0} is parsed successfully\n",
   Grammar);
+if (PrintGrammar)
+  llvm::outs() << G->dump();
 if (PrintGraph)
   llvm::outs() << 
clang::syntax::pseudo::LRGraph::buildLR0(*G).dumpForTests(
   *G);



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


[PATCH] D120724: [pseudo] Add a print-grammar option in the tool

2022-03-02 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7f99e1870f77: [pseudo] Add a print-grammar option in the 
tool (authored by hokein).
Herald added a project: All.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120724

Files:
  clang/tools/clang-pseudo/ClangPseudo.cpp


Index: clang/tools/clang-pseudo/ClangPseudo.cpp
===
--- clang/tools/clang-pseudo/ClangPseudo.cpp
+++ clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -24,6 +24,7 @@
 
 static opt
 Grammar("grammar", desc("Parse and check a BNF grammar file."), init(""));
+static opt PrintGrammar("print-grammar", desc("Print the grammar."));
 static opt PrintGraph("print-graph",
 desc("Print the LR graph for the grammar"));
 static opt PrintTable("print-table",
@@ -60,6 +61,8 @@
 }
 llvm::outs() << llvm::formatv("grammar file {0} is parsed successfully\n",
   Grammar);
+if (PrintGrammar)
+  llvm::outs() << G->dump();
 if (PrintGraph)
   llvm::outs() << 
clang::syntax::pseudo::LRGraph::buildLR0(*G).dumpForTests(
   *G);


Index: clang/tools/clang-pseudo/ClangPseudo.cpp
===
--- clang/tools/clang-pseudo/ClangPseudo.cpp
+++ clang/tools/clang-pseudo/ClangPseudo.cpp
@@ -24,6 +24,7 @@
 
 static opt
 Grammar("grammar", desc("Parse and check a BNF grammar file."), init(""));
+static opt PrintGrammar("print-grammar", desc("Print the grammar."));
 static opt PrintGraph("print-graph",
 desc("Print the LR graph for the grammar"));
 static opt PrintTable("print-table",
@@ -60,6 +61,8 @@
 }
 llvm::outs() << llvm::formatv("grammar file {0} is parsed successfully\n",
   Grammar);
+if (PrintGrammar)
+  llvm::outs() << G->dump();
 if (PrintGraph)
   llvm::outs() << clang::syntax::pseudo::LRGraph::buildLR0(*G).dumpForTests(
   *G);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120712: [clang-format][docs] handle explicit enum values

2022-03-02 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I have left, (some quite harsh opinions on this idea here, I'm sorry):
https://github.com/llvm/llvm-project/issues/54137

If you do want to contribute can I suggest you start with an item off this 
list, I think it will give you good insight into what is involved with making a 
change, you might not then think changing every option is such a brilliant idea 
;-)

https://github.com/llvm/llvm-project/issues?q=is%3Aopen+label%3A%22good+first+issue%22+label%3Aclang-format

I don't want to put you off, and I don't want to discourage your contributions, 
Sometimes its better to just start with a issue, lets gain mutual trust and 
respect then the grand ideas are much easier for us to swallow, especially for 
those of us who have perhaps become a little more cynical. (Sorry!)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120712

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


[clang] 05d7e9f - [pseudo] fix some comment nits, NFC.

2022-03-02 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-03-02T10:19:17+01:00
New Revision: 05d7e9f68ef005c43576278fe5d7ac03869974f3

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

LOG: [pseudo] fix some comment nits, NFC.

Added: 


Modified: 
clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp 
b/clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
index f07d8b106806..aaf9cad31961 100644
--- a/clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
+++ b/clang/lib/Tooling/Syntax/Pseudo/LRTableBuild.cpp
@@ -73,7 +73,7 @@ class LRTable::Builder {
   Table.Actions.push_back(E.Act);
   Table.States.push_back(E.State);
 }
-// Initialize the terminal and nonterminal idx, all ranges are empty by
+// Initialize the terminal and nonterminal offset, all ranges are empty by
 // default.
 Table.TerminalOffset = std::vector(GT.Terminals.size() + 1, 0);
 Table.NontermOffset = std::vector(GT.Nonterminals.size() + 1, 0);
@@ -127,7 +127,7 @@ LRTable LRTable::buildSLR(const Grammar &G) {
   }
   if (!I.hasNext()) {
 // If we've reached the end of a rule A := ..., then we can reduce if
-// the next token is in the follow set of A".
+// the next token is in the follow set of A.
 for (SymbolID Follow : FollowSets[G.lookupRule(I.rule()).Target]) {
   assert(isToken(Follow));
   Build.insert({SID, Follow, Action::reduce(I.rule())});



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


[PATCH] D120720: [clang][AVR] Implement standard calling convention for AVR and AVRTiny

2022-03-02 Thread Ben Shi via Phabricator via cfe-commits
benshi001 updated this revision to Diff 412357.

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

https://reviews.llvm.org/D120720

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/lib/Basic/Targets/AVR.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/avr/argument.c

Index: clang/test/CodeGen/avr/argument.c
===
--- /dev/null
+++ clang/test/CodeGen/avr/argument.c
@@ -0,0 +1,167 @@
+// RUN: %clang_cc1 -triple avr -target-cpu atmega328 -emit-llvm %s -o - \
+// RUN: | FileCheck %s --check-prefix AVR
+// RUN: %clang_cc1 -triple avr -target-cpu attiny40 -emit-llvm %s -o - \
+// RUN: | FileCheck %s --check-prefix TINY
+
+// NOTE: All arguments are passed in memory for functions with variable arguments.
+// AVR:  define {{.*}} i8 @foo0(i8 {{.*}}, i8 {{.*}}, ...)
+// TINY: define {{.*}} i8 @foo0(i8 {{.*}}, i8 {{.*}}, ...)
+// AVR-NOT:  define {{.*}} i8 @foo0(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}}, ...)
+// TINY-NOT: define {{.*}} i8 @foo0(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}}, ...)
+char foo0(char a, char b, ...) {
+  return a + b;
+}
+
+// NOTE: The char type argument is passed via registers on both avr and avrtiny.
+// AVR:  define {{.*}} @foo1({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} @foo1({{.*}}, i8 {{.*}} signext {{.*}})
+struct s08 {
+  char arr[8];
+};
+struct s06 {
+  char arr[6];
+};
+struct s08 foo1(struct s06 s6, char a) {
+  struct s08 s8;
+  s8.arr[a] = s6.arr[a];
+  return s8;
+}
+
+// NOTE: The char type argument is passed via registers on both avr and avrtiny.
+// AVR:  define {{.*}} void @foo2({{.*}}, {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} void @foo2({{.*}}, {{.*}}, i8 {{.*}} signext {{.*}})
+struct s09 {
+  char arr[9];
+};
+struct s04 {
+  char arr[4];
+};
+struct s09 foo2(struct s04 s4, char a) {
+  struct s09 s9;
+  s9.arr[a] = s4.arr[a];
+  return s9;
+}
+
+// NOTE: The char type argument is passed via registers on avr but via stack on avrtiny.
+// AVR:  define {{.*}} void @foo3({{.*}}, {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} void @foo3({{.*}}, {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} void @foo3({{.*}}, {{.*}}, i8 {{.*}})
+struct s09 foo3(struct s06 s6, char a) {
+  struct s09 s9;
+  s9.arr[a] = s6.arr[a];
+  return s9;
+}
+
+// NOTE: The char type argument is passed via stack on both avr and avrtiny.
+// AVR:  define {{.*}} void @foo4({{.*}}, i8 {{.*}}, ...)
+// TINY: define {{.*}} void @foo4({{.*}}, i8 {{.*}}, ...)
+// AVR-NOT:  define {{.*}} i8 @foo4({{.*}}, i8 {{.*}} signext {{.*}}, ...)
+// TINY-NOT: define {{.*}} i8 @foo4({{.*}}, i8 {{.*}} signext {{.*}}, ...)
+struct s09 foo4(char b, ...) {
+  struct s09 s9;
+  s9.arr[b] = b;
+  return s9;
+}
+
+// NOTE: The char type argument is passed via stack on both avr and avrtiny.
+// AVR:  define {{.*}} void @foo5({{.*}}, {{.*}}, i8 {{.*}})
+// TINY: define {{.*}} void @foo5({{.*}}, {{.*}}, i8 {{.*}})
+// AVR-NOT:  define {{.*}} void @foo5({{.*}}, {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} void @foo5({{{.*}}, {.*}}, i8 {{.*}} signext {{.*}})
+struct s15 {
+  char arr[15];
+};
+struct s09 foo5(struct s15 sx, char a) {
+  struct s09 s9;
+  s9.arr[a] = sx.arr[a];
+  return s9;
+}
+
+// NOTE: The char type argument is passed via registers on both avr and avrtiny.
+// AVR:  define {{.*}} i8 @foo6({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} i8 @foo6({{.*}}, i8 {{.*}} signext {{.*}})
+char foo6(struct s06 s, char b) {
+  return s.arr[b];
+}
+
+// NOTE: The char type argument is passed via stack on both avr and avrtiny.
+// AVR:  define {{.*}} @foo7({{.*}}, i8 {{.*}})
+// TINY: define {{.*}} @foo7({{.*}}, i8 {{.*}})
+// AVR-NOT:  define {{.*}} @foo7({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} @foo7({{.*}}, i8 {{.*}} signext {{.*}})
+struct s17 {
+  char arr[17];
+};
+char foo7(struct s17 s, char c) {
+  return s.arr[c];
+}
+
+// NOTE: The char type argument is passed via registers on avr but via stack on avrtiny.
+// AVR:  define {{.*}} @foo8({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} @foo8({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} @foo8({{.*}}, i8 {{.*}})
+struct s07 {
+  char arr[7];
+};
+char foo8(struct s07 s, char a) {
+  return s.arr[a];
+}
+
+// NOTE: All arguments are passed via registers on both avr and avrtiny.
+// AVR:  define {{.*}} i8 @foo9(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}})
+// TINY: define {{.*}} i8 @foo9(i8 {{.*}} signext {{.*}}, i8 {{.*}} signext {{.*}})
+char foo9(char a, char b) {
+  return a + b;
+}
+
+// NOTE: All arguments are passed via stack on both avr and avrtiny.
+// AVR:  define {{.*}} i8 @foo10({{.*}}, i8 {{.*}})
+// TINY: define {{.*}} i8 @foo10({{.*}}, i8 {{.*}})
+// AVR-NOT:  define {{.*}} i8 @foo10({{.*}}, i8 {{.*}} signext {{.*}})
+// TINY-NOT: define {{.*}} i8 @foo10({{.*}}, i8 {{.*}

[clang] d813116 - [NFC][Lexer] Remove getLangOpts function from Lexer

2022-03-02 Thread Dawid Jurczak via cfe-commits

Author: Dawid Jurczak
Date: 2022-03-02T11:17:05+01:00
New Revision: d813116c9deaa960ddcce5b4b161ea589d6e9a34

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

LOG: [NFC][Lexer] Remove getLangOpts function from Lexer

Given that there is only one external user of Lexer::getLangOpts
we can remove getter entirely without much pain.

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

Added: 


Modified: 
clang/include/clang/Lex/Lexer.h
clang/lib/Lex/Lexer.cpp
clang/lib/Lex/ModuleMap.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/Lexer.h b/clang/include/clang/Lex/Lexer.h
index e4dbb6b4af6f0..c64a5756ac419 100644
--- a/clang/include/clang/Lex/Lexer.h
+++ b/clang/include/clang/Lex/Lexer.h
@@ -183,10 +183,6 @@ class Lexer : public PreprocessorLexer {
SourceLocation ExpansionLocEnd,
unsigned TokLen, Preprocessor &PP);
 
-  /// getLangOpts - Return the language features currently enabled.
-  /// NOTE: this lexer modifies features as a file is parsed!
-  const LangOptions &getLangOpts() const { return LangOpts; }
-
   /// getFileLoc - Return the File Location for the file we are lexing out of.
   /// The physical location encodes the location where the characters come 
from,
   /// the virtual location encodes where we should *claim* the characters came

diff  --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index 63ad43842adde..6e8072fb1b2d9 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -1194,11 +1194,11 @@ static char GetTrigraphCharForLetter(char Letter) {
 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
 /// return the result character.  Finally, emit a warning about trigraph use
 /// whether trigraphs are enabled or not.
-static char DecodeTrigraphChar(const char *CP, Lexer *L) {
+static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
   char Res = GetTrigraphCharForLetter(*CP);
   if (!Res || !L) return Res;
 
-  if (!L->getLangOpts().Trigraphs) {
+  if (!Trigraphs) {
 if (!L->isLexingRawMode())
   L->Diag(CP-2, diag::trigraph_ignored);
 return 0;
@@ -1372,7 +1372,8 @@ char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned 
&Size,
   if (Ptr[0] == '?' && Ptr[1] == '?') {
 // If this is actually a legal trigraph (not something like "??x"), emit
 // a trigraph warning.  If so, and if trigraphs are enabled, return it.
-if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
+if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
+LangOpts.Trigraphs)) {
   // Remember that this token needs to be cleaned.
   if (Tok) Tok->setFlag(Token::NeedsCleaning);
 
@@ -2543,8 +2544,8 @@ bool Lexer::SaveLineComment(Token &Result, const char 
*CurPtr) {
 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
 /// character (either \\n or \\r) is part of an escaped newline sequence.  
Issue
 /// a diagnostic if so.  We know that the newline is inside of a block comment.
-static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
-  Lexer *L) {
+static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
+  bool Trigraphs) {
   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
 
   // Position of the first trigraph in the ending sequence.
@@ -2595,7 +2596,7 @@ static bool isEndOfBlockCommentWithEscapedNewLine(const 
char *CurPtr,
   if (TrigraphPos) {
 // If no trigraphs are enabled, warn that we ignored this trigraph and
 // ignore this * character.
-if (!L->getLangOpts().Trigraphs) {
+if (!Trigraphs) {
   if (!L->isLexingRawMode())
 L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
   return false;
@@ -2725,7 +2726,8 @@ bool Lexer::SkipBlockComment(Token &Result, const char 
*CurPtr,
 break;
 
   if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
-if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
+if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
+  LangOpts.Trigraphs)) {
   // We found the final */, though it had an escaped newline between 
the
   // * and /.  We're done!
   break;

diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 824b2bb192909..a5eca402c43bf 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -1625,7 +1625,7 @@ SourceLocation ModuleMapParser::consumeToken() {
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
 un

[PATCH] D120404: [NFC][Lexer] Remove getLangOpts function from Lexer

2022-03-02 Thread Dawid Jurczak via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd813116c9dea: [NFC][Lexer] Remove getLangOpts function from 
Lexer (authored by yurai007).
Herald added a project: All.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120404

Files:
  clang/include/clang/Lex/Lexer.h
  clang/lib/Lex/Lexer.cpp
  clang/lib/Lex/ModuleMap.cpp


Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1625,7 +1625,7 @@
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
 unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+Lexer::getSpelling(LToken, Start, SourceMgr, Map.LangOpts);
 uint64_t Value;
 if (StringRef(Start, Length).getAsInteger(0, Value)) {
   Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
Index: clang/lib/Lex/Lexer.cpp
===
--- clang/lib/Lex/Lexer.cpp
+++ clang/lib/Lex/Lexer.cpp
@@ -1194,11 +1194,11 @@
 /// prefixed with ??, emit a trigraph warning.  If trigraphs are enabled,
 /// return the result character.  Finally, emit a warning about trigraph use
 /// whether trigraphs are enabled or not.
-static char DecodeTrigraphChar(const char *CP, Lexer *L) {
+static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
   char Res = GetTrigraphCharForLetter(*CP);
   if (!Res || !L) return Res;
 
-  if (!L->getLangOpts().Trigraphs) {
+  if (!Trigraphs) {
 if (!L->isLexingRawMode())
   L->Diag(CP-2, diag::trigraph_ignored);
 return 0;
@@ -1372,7 +1372,8 @@
   if (Ptr[0] == '?' && Ptr[1] == '?') {
 // If this is actually a legal trigraph (not something like "??x"), emit
 // a trigraph warning.  If so, and if trigraphs are enabled, return it.
-if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
+if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
+LangOpts.Trigraphs)) {
   // Remember that this token needs to be cleaned.
   if (Tok) Tok->setFlag(Token::NeedsCleaning);
 
@@ -2543,8 +2544,8 @@
 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
 /// character (either \\n or \\r) is part of an escaped newline sequence.  
Issue
 /// a diagnostic if so.  We know that the newline is inside of a block comment.
-static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
-  Lexer *L) {
+static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
+  bool Trigraphs) {
   assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
 
   // Position of the first trigraph in the ending sequence.
@@ -2595,7 +2596,7 @@
   if (TrigraphPos) {
 // If no trigraphs are enabled, warn that we ignored this trigraph and
 // ignore this * character.
-if (!L->getLangOpts().Trigraphs) {
+if (!Trigraphs) {
   if (!L->isLexingRawMode())
 L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
   return false;
@@ -2725,7 +2726,8 @@
 break;
 
   if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
-if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
+if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
+  LangOpts.Trigraphs)) {
   // We found the final */, though it had an escaped newline between 
the
   // * and /.  We're done!
   break;
Index: clang/include/clang/Lex/Lexer.h
===
--- clang/include/clang/Lex/Lexer.h
+++ clang/include/clang/Lex/Lexer.h
@@ -183,10 +183,6 @@
SourceLocation ExpansionLocEnd,
unsigned TokLen, Preprocessor &PP);
 
-  /// getLangOpts - Return the language features currently enabled.
-  /// NOTE: this lexer modifies features as a file is parsed!
-  const LangOptions &getLangOpts() const { return LangOpts; }
-
   /// getFileLoc - Return the File Location for the file we are lexing out of.
   /// The physical location encodes the location where the characters come 
from,
   /// the virtual location encodes where we should *claim* the characters came


Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1625,7 +1625,7 @@
 SpellingBuffer.resize(LToken.getLength() + 1);
 const char *Start = SpellingBuffer.data();
 unsigned Length =
-Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
+Lexer::getSpelling(LToken, Start, SourceMgr, Map.L

[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120806

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -583,6 +583,28 @@
"  }\n"
"g();");
 
+  verifyFormat("if consteval {\n}");
+  verifyFormat("if !consteval {\n}");
+  verifyFormat("if consteval {\n} else {\n}");
+  verifyFormat("if !consteval {\n} else {\n}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}");
+  verifyFormat("if CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+
   verifyFormat("if (a)\n"
"  g();");
   verifyFormat("if (a) {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2384,10 +2384,16 @@
 
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
-  if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  if (FormatTok->is(tok::exclaim))
 nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
+  if (FormatTok->is(tok::kw_consteval)) {
+nextToken();
+  } else {
+if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  nextToken();
+if (FormatTok->is(tok::l_paren))
+  parseParens();
+  }
   HandleAttributes();
 
   bool NeedsUnwrappedLine = false;


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -583,6 +583,28 @@
"  }\n"
"g();");
 
+  verifyFormat("if consteval {\n}");
+  verifyFormat("if !consteval {\n}");
+  verifyFormat("if consteval {\n} else {\n}");
+  verifyFormat("if !consteval {\n} else {\n}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}");
+  verifyFormat("if CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+
   verifyFormat("if (a)\n"
"  g();");
   verifyFormat("if (a) {\n"
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2384,10 +2384,16 @@
 
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
-  if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  if (FormatTok->is(tok::exclaim))
 nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
+  if (FormatTok->is(tok::kw_consteval)) {
+nextToken();
+  } else {
+if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  nextToken();
+if (FormatTok->is(tok::l_paren))
+  parseParens();
+  }
   HandleAttributes();
 
   bool NeedsUnwrappedLine = false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D120449: [RISCV][RVV] Add strict vfcvt intrinsics that have side effects for dynamically-set rounding mode

2022-03-02 Thread Kito Cheng via Phabricator via cfe-commits
kito-cheng added inline comments.



Comment at: llvm/lib/Target/RISCV/RISCVISelLowering.cpp:4683
+Ops.push_back(VL);
+Ops.push_back(DAG.getUNDEF(XLenVT)); // Policy
+  }

Is this operand for tail policy? if so why this is `UNDEF`? I guess this should 
be `TAIL_AGNOSTIC` rather than `UNDEF`?



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td:4673
 
//===--===//
-defm PseudoVFCVT_XU_F : VPseudoVCVTI_V;
-defm PseudoVFCVT_X_F : VPseudoVCVTI_V;
+let mayRaiseFPException = true in {
 defm PseudoVFCVT_RTZ_XU_F : VPseudoVCVTI_V;

I saw all other target using `0`/`1` rather than `true`/`false` including 
`RISCVInstrInfoF.td`/`RISCVInstrInfoD.td`when setting mayRaiseFPException, 
maybe we should keep it consistent? 



Comment at: llvm/lib/Target/RISCV/RISCVInstrInfoVPseudos.td:4673
 
//===--===//
-defm PseudoVFCVT_XU_F : VPseudoVCVTI_V;
-defm PseudoVFCVT_X_F : VPseudoVCVTI_V;
+let mayRaiseFPException = true in {
 defm PseudoVFCVT_RTZ_XU_F : VPseudoVCVTI_V;

kito-cheng wrote:
> I saw all other target using `0`/`1` rather than `true`/`false` including 
> `RISCVInstrInfoF.td`/`RISCVInstrInfoD.td`when setting mayRaiseFPException, 
> maybe we should keep it consistent? 
And I think we should also set `mayRaiseFPException` in `RISCVInstrInfoV.td`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120449

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


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-02 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:561
+  std::make_unique(triple);
+  CodeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*TLII));
+

schweitz wrote:
> Got jumbled around somehow. TLII is allocated at line 559-560. Since you are 
> checking allocations with assert in other places, why not here? TLII is 
> immediately dereferenced on line 561, without an assertion check.
Thanks for clarifying. One `assert` coming this way :)



Comment at: flang/lib/Optimizer/Support/FIRContext.cpp:19
 
-static constexpr const char *tripleName = "fir.triple";
+static constexpr const char *tripleName = "llvm.target_triple";
 

schweitz wrote:
> awarzynski wrote:
> > schweitz wrote:
> > > Why is this being changed? This is a FIR specific attribute.
> > The driver assumes that when compiling a Fortran file, a valid triple will 
> > be present in the generated LLVM IR file. Currently, `fir.tiple` is just 
> > dropped and the generated LLVM IR module contains no triple. For 
> > `-emit-obj`/`-S` to work, we do need to make sure that a valid triple is 
> > actually there.
> > 
> > We could add logic to translate `fir.triple` to `llvm.target_triple` (in 
> > the FIR --> LLVM MLIR translation layer), but why bother if it's not used 
> > anywhere? Instead, Flang could use `llvm.target_triple` from the very 
> > beginning. This way, no extra functionality is needed (`llvm.target_triple` 
> > is preserved when translating from FIR to LLVM MLIR and then included in 
> > the generated LLVM IR module).
> > 
> > AFAIK, `fir-triple` is never used anywhere. In fact, it's already been 
> > removed from [[ 
> > https://github.com/flang-compiler/f18-llvm-project/blob/fir-dev/flang/lib/Optimizer/Support/FIRContext.cpp#L19
> >  | fir-dev ]].
> > 
> Thanks for the update. I'm glad to see MLIR decided to use my module 
> attribute trick here. :)
> 
> Given this, there is no reason to "block copy" the name of the attribute over 
> to FIR. Just use the `mlir::LLVM::LLVMDialect::getTargetTripleAttrName()` 
> method. The FIR attribute can then be retired and removed along with the 
> setter and getter.
I wasn't aware of `getTargetTripleAttrName`, thanks! I will use that instead.

 As for `setTargetTriple` and `getTargetTriple`, we'd need a bit more work to 
remove them. I suggest doing that in a separate patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

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


[PATCH] D120331: [clang-tidy][run-clang-tidy.py] Add --config-file= option

2022-03-02 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth accepted this revision.
JonasToth added a comment.
This revision is now accepted and ready to land.
Herald added a project: All.

LGTM, but please adjust the naming nit to a better name.

do you have commit rights? Otherwise someone (e.g. me) could commit on your 
behalf, of course with a remark that its your contribution :)




Comment at: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py:228
   'default')
-  parser.add_argument('-config', default=None,
+  group = parser.add_mutually_exclusive_group()
+  group.add_argument('-config', default=None,

nit: i think `config_group` or so would be better to show that its only 
config-related. This name is too generic i feel.



Comment at: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py:236
   'each source file in its parent directories.')
+  parser.add_argument('-config-file', default=None,
+  help='Specify the path of .clang-tidy or custom config'

SAtacker wrote:
> JonasToth wrote:
> > please ensure that those option exclude each other. right now it could be 
> > used with both options which is a contradiction for `clang-tidy`
> Do you mean mutual exclusion? From the docs: 
> https://docs.python.org/3/library/argparse.html#mutual-exclusion
Yes, thanks :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120331

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


[PATCH] D120646: [clang][scan-build] Change mode of installation for scan-build.1

2022-03-02 Thread Manas Gupta via Phabricator via cfe-commits
manas added a comment.
Herald added a project: All.

Buildbots are happy. I think we can land this. @steakhal do you mind landing it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120646

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


[PATCH] D120646: [clang][scan-build] Change mode of installation for scan-build.1

2022-03-02 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3ca109855709: [clang][scan-build] Change mode of 
installation for scan-build.1 (authored by manas, committed by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120646

Files:
  clang/tools/scan-build/CMakeLists.txt


Index: clang/tools/scan-build/CMakeLists.txt
===
--- clang/tools/scan-build/CMakeLists.txt
+++ clang/tools/scan-build/CMakeLists.txt
@@ -74,7 +74,7 @@
  "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
 list(APPEND Depends 
"${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}")
-install(PROGRAMS man/${ManPage}
+install(FILES man/${ManPage}
 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
 COMPONENT scan-build)
   endforeach()


Index: clang/tools/scan-build/CMakeLists.txt
===
--- clang/tools/scan-build/CMakeLists.txt
+++ clang/tools/scan-build/CMakeLists.txt
@@ -74,7 +74,7 @@
  "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
 list(APPEND Depends "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}")
-install(PROGRAMS man/${ManPage}
+install(FILES man/${ManPage}
 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
 COMPONENT scan-build)
   endforeach()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 3ca1098 - [clang][scan-build] Change mode of installation for scan-build.1

2022-03-02 Thread Balazs Benics via cfe-commits

Author: Manas
Date: 2022-03-02T13:12:08+01:00
New Revision: 3ca1098557091247524acef9a3759379ba7a3e59

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

LOG: [clang][scan-build] Change mode of installation for scan-build.1

Currently, manpage for scan-build is installed as a program, with
permission of 755. This patch makes installation of scan-build.1 as
file, with 644 permission.

Patch by Manas.

Reviewed By: steakhal

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

Added: 


Modified: 
clang/tools/scan-build/CMakeLists.txt

Removed: 




diff  --git a/clang/tools/scan-build/CMakeLists.txt 
b/clang/tools/scan-build/CMakeLists.txt
index 4a578b4c6f3ed..ef687b0e90a17 100644
--- a/clang/tools/scan-build/CMakeLists.txt
+++ b/clang/tools/scan-build/CMakeLists.txt
@@ -74,7 +74,7 @@ if(CLANG_INSTALL_SCANBUILD)
  "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/man/${ManPage})
 list(APPEND Depends 
"${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_MANDIR}/man1/${ManPage}")
-install(PROGRAMS man/${ManPage}
+install(FILES man/${ManPage}
 DESTINATION "${CMAKE_INSTALL_MANDIR}/man1"
 COMPONENT scan-build)
   endforeach()



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


[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

LFTM

Do we also need to consider this in the context of "AllowShortIfStatments"?  
(that would be in a different review in my view)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


[clang] 1e78d07 - [clang-offload-bundler] Fix typo in a test case

2022-03-02 Thread Saiyedul Islam via cfe-commits

Author: Saiyedul Islam
Date: 2022-03-02T13:33:56Z
New Revision: 1e78d07dc9cdb786eadb30dd4a4f9b2c5d8ba8eb

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

LOG: [clang-offload-bundler] Fix typo in a test case

Intermediate file of one of the test was getting overwritten due
to name clash.

Added: 


Modified: 
clang/test/Driver/clang-offload-bundler.c

Removed: 




diff  --git a/clang/test/Driver/clang-offload-bundler.c 
b/clang/test/Driver/clang-offload-bundler.c
index 3fde2233fe72..cb4092a8eaef 100644
--- a/clang/test/Driver/clang-offload-bundler.c
+++ b/clang/test/Driver/clang-offload-bundler.c
@@ -406,8 +406,8 @@
 // Create few code object bundles and archive them to create an input archive
 // RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,openmp-amdgcn-amd-amdhsa-gfx906,openmp-amdgcn-amd-amdhsa--gfx908
 -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.simple.bundle
 // RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,openmp-amdgcn-amd-amdhsa--gfx903 
-inputs=%t.o,%t.tgt1 -outputs=%t.simple1.bundle
-// RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,hip-amdgcn-amd-amdhsa--gfx906 
-inputs=%t.o,%t.tgt1 -outputs=%t.simple1.bundle
-// RUN: llvm-ar cr %t.input-archive.a %t.simple.bundle %t.simple1.bundle
+// RUN: clang-offload-bundler -type=o 
-targets=host-%itanium_abi_triple,hip-amdgcn-amd-amdhsa--gfx906 
-inputs=%t.o,%t.tgt1 -outputs=%t.simple2.bundle
+// RUN: llvm-ar cr %t.input-archive.a %t.simple.bundle %t.simple1.bundle 
%t.simple2.bundle
 
 // RUN: clang-offload-bundler -unbundle -type=a 
-targets=openmp-amdgcn-amd-amdhsa-gfx906,openmp-amdgcn-amd-amdhsa-gfx908 
-inputs=%t.input-archive.a 
-outputs=%t-archive-gfx906-simple.a,%t-archive-gfx908-simple.a
 // RUN: llvm-ar t %t-archive-gfx906-simple.a | FileCheck %s 
-check-prefix=GFX906



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


[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Johel Ernesto Guerrero Peña via Phabricator via cfe-commits
JohelEGP added a comment.

In D120806#3354119 , @MyDeveloperDay 
wrote:

> LFTM
>
> Do we also need to consider this in the context of "AllowShortIfStatments"?  
> (that would be in a different review in my view)

Definitely. Since it didn't work at all, I reported it without a 
`.clang-format`. I was hoping it'd play well with `AllowShortIfStatments` out 
of the box.
I'm currently building `HEAD` with this patch to reformat my code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

I'll handle `AllowShortIfStatements` and update this review. Should be pretty 
straightforward.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


[PATCH] D120568: [flang][driver] Add support for -S and implement -c/-emit-obj

2022-03-02 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 412386.
awarzynski added a comment.

- Got rid of `tripleName`
- Added an assert for the newly created TLII
- Rebased
- Added `#includes` missing after the rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120568

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/lib/Optimizer/Support/FIRContext.cpp
  flang/test/CMakeLists.txt
  flang/test/Driver/code-gen-aarch64.f90
  flang/test/Driver/code-gen-x86.f90
  flang/test/Driver/code-gen.f90
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/emit-asm-aarch64.f90
  flang/test/Driver/emit-asm-x86.f90
  flang/test/Driver/syntax-only.f90
  flang/test/Fir/target-rewrite-triple.fir
  flang/test/lit.cfg.py
  flang/test/lit.site.cfg.py.in
  flang/tools/flang-driver/fc1_main.cpp
  flang/unittests/Frontend/CMakeLists.txt
  flang/unittests/Frontend/FrontendActionTest.cpp
  llvm/include/llvm/IR/PassInstrumentation.h

Index: llvm/include/llvm/IR/PassInstrumentation.h
===
--- llvm/include/llvm/IR/PassInstrumentation.h
+++ llvm/include/llvm/IR/PassInstrumentation.h
@@ -60,6 +60,9 @@
 
 class PreservedAnalyses;
 class StringRef;
+// This forward declaration is required to avoid clashes with a similarly named
+// class in other sub-projects (e.g. MLIR).
+class PassInstrumentation;
 
 /// This class manages callbacks registration, as well as provides a way for
 /// PassInstrumentation to pass control to the registered callbacks.
Index: flang/unittests/Frontend/FrontendActionTest.cpp
===
--- flang/unittests/Frontend/FrontendActionTest.cpp
+++ flang/unittests/Frontend/FrontendActionTest.cpp
@@ -11,6 +11,7 @@
 #include "flang/Frontend/FrontendOptions.h"
 #include "flang/FrontendTool/Utils.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/raw_ostream.h"
 
 #include "gtest/gtest.h"
@@ -188,4 +189,35 @@
   EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data())
   .contains("define void @_QQmain()"));
 }
+
+TEST_F(FrontendActionTest, EmitAsm) {
+  // Populate the input file with the pre-defined input and flush it.
+  *(inputFileOs_) << "end program";
+  inputFileOs_.reset();
+
+  // Set-up the action kind.
+  compInst_.invocation().frontendOpts().programAction = EmitAssembly;
+  compInst_.invocation().preprocessorOpts().noReformat = true;
+
+  // Initialise LLVM backend
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
+  // Set-up the output stream. We are using output buffer wrapped as an output
+  // stream, as opposed to an actual file (or a file descriptor).
+  llvm::SmallVector outputFileBuffer;
+  std::unique_ptr outputFileStream(
+  new llvm::raw_svector_ostream(outputFileBuffer));
+  compInst_.set_outputStream(std::move(outputFileStream));
+
+  // Execute the action.
+  bool success = ExecuteCompilerInvocation(&compInst_);
+
+  // Validate the expected output.
+  EXPECT_TRUE(success);
+  EXPECT_TRUE(!outputFileBuffer.empty());
+
+  EXPECT_TRUE(llvm::StringRef(outputFileBuffer.data()).contains("_QQmain"));
+}
 } // namespace
Index: flang/unittests/Frontend/CMakeLists.txt
===
--- flang/unittests/Frontend/CMakeLists.txt
+++ flang/unittests/Frontend/CMakeLists.txt
@@ -1,3 +1,7 @@
+set(LLVM_LINK_COMPONENTS
+  ${LLVM_TARGETS_TO_BUILD}
+)
+
 add_flang_unittest(FlangFrontendTests
   CompilerInstanceTest.cpp
   FrontendActionTest.cpp
Index: flang/tools/flang-driver/fc1_main.cpp
===
--- flang/tools/flang-driver/fc1_main.cpp
+++ flang/tools/flang-driver/fc1_main.cpp
@@ -20,6 +20,7 @@
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Option/OptTable.h"
+#include "llvm/Support/TargetSelect.h"
 
 #include 
 
@@ -48,6 +49,11 @@
   bool success =
   CompilerInvocation::CreateFromArgs(flang->invocation(), argv, diags);
 
+  // Initialize targets first, so that --version shows registered targets.
+  llvm::InitializeAllTargets();
+  llvm::InitializeAllTargetMCs();
+  llvm::InitializeAllAsmPrinters();
+
   diagsBuffer->FlushDiagnostics(flang->diagnostics());
 
   if (!success)
Index: flang/test/lit.site.cfg.py.in
===
--- flang/test/lit.site.cfg.py.in
+++ flang/test/lit.site.cfg.py.in
@@ -18,6 +18,7 @@
 config.flang_standalone_build = @FLANG_STANDALONE_BUILD@
 config.has_pl

[PATCH] D120331: [clang-tidy][run-clang-tidy.py] Add --config-file= option

2022-03-02 Thread Shreyas via Phabricator via cfe-commits
SAtacker added a comment.

In D120331#3354021 , @JonasToth wrote:

> LGTM, but please adjust the naming nit to a better name.

Thanks for the review again. 
Will rename the `group` to `config_group` as you suggested and I feel that too.

> do you have commit rights? Otherwise someone (e.g. me) could commit on your 
> behalf, of course with a remark that its your contribution :)
>
> (btw. go ahead and ping me again, I am busy with too many things right now :/)

I don't have the access to land this commit into the llvm-project. Until then I 
shall trust this wonderful process :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120331

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets updated this revision to Diff 412391.
phyBrackets added a comment.
Herald added a project: All.

Created the separate test file for UninitializedRead checker


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/bstring.c
  clang/test/Analysis/bstring_UninitRead.c

Index: clang/test/Analysis/bstring_UninitRead.c
===
--- /dev/null
+++ clang/test/Analysis/bstring_UninitRead.c
@@ -0,0 +1,116 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.cstring \
+// RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false  
+//
+// RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.cstring \
+// RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false
+//
+// RUN: %clang_analyze_cc1 -verify %s -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.cstring \
+// RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false
+//
+// RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.cstring \
+// RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false
+
+// This file is generally for the alpha.unix.cstring.UninitializedRead Checker, the reason for putting it into
+// the separate file because the checker is break the some existing test cases in bstring.c file , so we don't 
+// wanna mess up with some existing test case so it's better to create separate file for it, this file also include 
+// the broken test for the reference in future about the broken tests.
+
+#ifdef USE_BUILTINS
+# define BUILTIN(f) __builtin_ ## f
+#else /* USE_BUILTINS */
+# define BUILTIN(f) f
+#endif /* USE_BUILTINS */
+
+typedef typeof(sizeof(int)) size_t;
+
+void clang_analyzer_eval(int);
+
+
+
+#ifdef VARIANT
+
+#define __memcpy_chk BUILTIN(__memcpy_chk)
+void *__memcpy_chk(void *restrict s1, const void *restrict s2, size_t n,
+   size_t destlen);
+
+#define memcpy(a,b,c) __memcpy_chk(a,b,c,(size_t)-1)
+
+#else /* VARIANT */
+
+#define memcpy BUILTIN(memcpy)
+void *memcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+#endif /* VARIANT */
+
+void top(char *dst) {
+  char buf[10];
+  memcpy(dst, buf, 10); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  (void)buf;
+}
+
+//===--===
+// mempcpy()
+//===--===
+
+#ifdef VARIANT
+
+#define __mempcpy_chk BUILTIN(__mempcpy_chk)
+void *__mempcpy_chk(void *restrict s1, const void *restrict s2, size_t n,
+   size_t destlen);
+
+#define mempcpy(a,b,c) __mempcpy_chk(a,b,c,(size_t)-1)
+
+#else /* VARIANT */
+
+#define mempcpy BUILTIN(mempcpy)
+void *mempcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+#endif /* VARIANT */
+
+void mempcpy14() {
+  int src[] = {1, 2, 3, 4};
+  int dst[5] = {0};
+  int *p;
+
+  p = mempcpy(dst, src, 4 * sizeof(int)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  // FIXME: This behaviour is actually Unexpected and needs to be fix, 
+  // mempcpy seems to consider the src buffered byte as uninitialized
+  // and returning undef which is actually not the case It should return something like Unknown .
+
+  clang_analyzer_eval(p == &dst[4]); // no-warning (above is fatal)
+}
+
+struct st {
+  int i;
+  int j;
+};
+
+
+void mempcpy15() {
+  struct st s1 = {0};
+  struct st s2;
+  struct st *p1;
+  struct st *p2;
+
+  p1 = (&s2) + 1;
+  p2 = mempcpy(&s2, &s1, sizeof(struct st)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  // FIXME: It seems same as mempcpy14() case.
+  
+  clang_analyzer_eval(p1 == p2); // no-warning (above is fatal)
+}
Index: clang/test/Analysis/bstring.c
===
--- clang/test/Analysis/bstring.c
+++ clang/test/Analysis/bstring.c
@@ -2,13 +2,15 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug

[PATCH] D120255: [Concepts] Check constraints for explicit template instantiations

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

In D120255#3352920 , @royjacobson 
wrote:

> In D120255#3352755 , @erichkeane 
> wrote:
>
>> Hmm... doing FileCheck in a Sema test is highly irregular.  I would expect 
>> us to be able to test this in the type system in some way.  Something like 
>> `A<3>::f()` is invalid (see -verify).
>>
>> Also, please add all the context (as requested above!) with the -U stuff.
>
> I couldn't think of a way to "internally" know whether some function got 
> instantiated. I also saw some other instantiation tests do it this way 
> (SemaTemplate/instantiate-friend-function.cpp, 
> SemaTemplate/inject-templated-friend.cpp). But I'm really not familiar enough 
> with the code structure to have an opinion about this..
>
> Also, as I wrote in the description - function explicit instantiation doesn't 
> check constraints either but it's a different code path, so, `A<3>::f()` 
> currently fails for the wrong reason. It will just try to instantiate the 
> first function it finds and then fail the static assert and not the 
> constraint.
> (Or worse, fail the internal assert in `SemaTemplate.cpp:10161` if clang was 
> built with assertions).

The only other idea I have (other than finding a static-assert of some sort) is 
to do an AST level test instead, so use `-ast-dump` and check that it 
appears/not appears in the AST instead?  That way at least the ordering will be 
more reliable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120255

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


[PATCH] D120255: [Concepts] Check constraints for explicit template instantiations

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/SemaTemplate/constraints-instantiation.cpp:3-8
+// void PR46029::A<1>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi1EE1fEv
+// void PR46029::A<2>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi2EE1fEv
+// void PR46029::A<3>::f()
+// CHECK-NOT: define {{.*}} @_ZN7PR460291AILi3EE1fEv

I think it might be better to test this via an `-ast-dump` test (which lives in 
the `AST` test directory) rather than emitting LLVM IR to determine whether 
something was instantiated or not.

Btw, when you convert the test to use `-ast-dump`, be sure to make use of 
regexes for things like line, column numbers, pointer values, etc so that the 
test is easier to edit without breaking.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120255

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added a comment.

Hey @NoQ and @steakhal , will you just check , if everything looks fine or not! 
The test cases run successfully tho now!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120331: [clang-tidy][run-clang-tidy.py] Add --config-file= option

2022-03-02 Thread Shreyas via Phabricator via cfe-commits
SAtacker updated this revision to Diff 412397.
SAtacker added a comment.

[clang-tidy][run-clang-tidy.py] Rename `group` to `config_group`

Signed-off-by: Shreyas Atre 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120331

Files:
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -96,8 +96,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter, use_color):
+extra_arg, extra_arg_before, quiet, config_path,
+config, line_filter, use_color):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary]
   if allow_enabling_alpha_checkers:
@@ -127,7 +127,9 @@
   start.append('-p=' + build_path)
   if quiet:
   start.append('-quiet')
-  if config:
+  if config_path:
+  start.append('--config-file=' + config_path)
+  elif config:
   start.append('-config=' + config)
   start.append(f)
   return start
@@ -188,8 +190,8 @@
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter,
- args.use_color)
+ args.quiet, args.config_path, args.config,
+ args.line_filter, args.use_color)
 
 proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
 output, err = proc.communicate()
@@ -223,7 +225,8 @@
   parser.add_argument('-checks', default=None,
   help='checks filter, when not specified, use clang-tidy '
   'default')
-  parser.add_argument('-config', default=None,
+  config_group = parser.add_mutually_exclusive_group()
+  config_group.add_argument('-config', default=None,
   help='Specifies a configuration in YAML/JSON format: '
   '  -config="{Checks: \'*\', '
   '   CheckOptions: [{key: x, '
@@ -231,6 +234,12 @@
   'When the value is empty, clang-tidy will '
   'attempt to find a file named .clang-tidy for '
   'each source file in its parent directories.')
+  config_group.add_argument('-config-file', default=None,
+  help='Specify the path of .clang-tidy or custom config '
+  'file: e.g. -config-file=/some/path/myTidyConfigFile. '
+  'This option internally works exactly the same way as '
+  '-config option after reading specified config file. '
+  'Use either -config-file or -config, not both.')
   parser.add_argument('-header-filter', default=None,
   help='regular expression matching the names of the '
   'headers to output diagnostics from. Diagnostics from '
@@ -283,8 +292,8 @@
  None, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
- args.quiet, args.config, args.line_filter,
- args.use_color)
+ args.quiet, args.config_path, args.config,
+ args.line_filter, args.use_color)
 invocation.append('-list-checks')
 invocation.append('-')
 if args.quiet:


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -96,8 +96,8 @@
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
 header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config,
-line_filter, use_color):
+extra_arg, extra_arg_before, quiet, config_path,
+config, line_filter, use_color):
   """Gets a command line for clang-tidy."""
   start = [clang_tidy_binary]
   if allow_enabling_alpha_checkers:
@@ -127,7 +127,9 @@
   start.append('-p=' + build_path)
   if quiet:
   start.append(

[PATCH] D120812: [AST] Use RecoveryExpr to model a DeclRefExpr which refers to an invalid Decl.

2022-03-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a project: clang.

Previously, we didin't build a DeclRefExpr which refers to an invalid 
declaration.

In this patch, we handle this case by building an empty RecoveryExpr,
which will preserve more broken code (AST parent nodes that contain the
RecoveryExpr is preserved in the AST).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120812

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/Sema/ms-inline-asm.c
  clang/test/SemaCXX/constructor-initializer.cpp
  clang/test/SemaCXX/copy-assignment.cpp


Index: clang/test/SemaCXX/copy-assignment.cpp
===
--- clang/test/SemaCXX/copy-assignment.cpp
+++ clang/test/SemaCXX/copy-assignment.cpp
@@ -114,6 +114,7 @@
 namespace test1 {
   template class A : public unknown::X { // expected-error 
{{undeclared identifier 'unknown'}} expected-error {{expected class name}}
 A(UndeclaredType n) : X(n) {} // expected-error {{unknown type name 
'UndeclaredType'}}
+// expected-error@-1 {{member initializer 'X' does not name a non-static 
data member or base class}}
   };
   template class B : public A {
 virtual void foo() {}
Index: clang/test/SemaCXX/constructor-initializer.cpp
===
--- clang/test/SemaCXX/constructor-initializer.cpp
+++ clang/test/SemaCXX/constructor-initializer.cpp
@@ -249,7 +249,7 @@
   class B : public A {
   public:
 B(const String& s, int e=0) // expected-error {{unknown type name}} 
-  : A(e), m_String(s) , m_ErrorStr(__null) {} // expected-error {{no 
matching constructor}} expected-error {{does not name}}
+  : A(e), m_String(s) , m_ErrorStr(__null) {} // expected-error {{no 
matching constructor}} expected-error {{does not name}} expected-error {{member 
initializer 'm_ErrorStr' does not name}}
 B(const B& e)
   : A(e), m_String(e.m_String), m_ErrorStr(__null) { // expected-error 
2{{does not name}} \
   // expected-error {{no member named 'm_String' in 'test3::B'}}
Index: clang/test/Sema/ms-inline-asm.c
===
--- clang/test/Sema/ms-inline-asm.c
+++ clang/test/Sema/ms-inline-asm.c
@@ -78,7 +78,6 @@
   __asm { mov eax, [eax] UndeclaredId } // expected-error {{unknown token in 
expression}} expected-error {{use of undeclared label 'UndeclaredId'}}
 
   // FIXME: Only emit one diagnostic here.
-  // expected-error@+3 {{use of undeclared label 'A'}}
   // expected-error@+2 {{unexpected type name 'A': expected expression}}
   // expected-error@+1 {{unknown token in expression}}
   __asm { mov eax, [eax] A }
Index: clang/test/AST/ast-dump-recovery.cpp
===
--- clang/test/AST/ast-dump-recovery.cpp
+++ clang/test/AST/ast-dump-recovery.cpp
@@ -401,3 +401,13 @@
   // CHECK-NEXT:   |-IntegerLiteral {{.*}} 'int' 7
   // CHECK-NEXT:   `-IntegerLiteral {{.*}} 'int' 8
 }
+
+void RecoveryExprForInvalidDecls(Unknown InvalidDecl) {
+  InvalidDecl + 1;
+  // CHECK:  BinaryOperator {{.*}}
+  // CHECK-NEXT: |-RecoveryExpr {{.*}} ''
+  // CHECK-NEXT: `-IntegerLiteral {{.*}} 'int' 1
+  InvalidDecl();
+  // CHECK:  CallExpr {{.*}}
+  // CHECK-NEXT: `-RecoveryExpr {{.*}} ''
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -3228,8 +3228,12 @@
  "Cannot refer unambiguously to a function template");
 
   SourceLocation Loc = NameInfo.getLoc();
-  if (CheckDeclInExpr(*this, Loc, D))
-return ExprError();
+  if (CheckDeclInExpr(*this, Loc, D)) {
+// Recovery from invalid cases (e.g. D is an invalid Decl).
+// We use the dependent type for the RecoveryExpr to prevent bogus 
follow-up
+// diagnostics, as invalid decls use int as a fallback type.
+return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), 
{});
+  }
 
   if (TemplateDecl *Template = dyn_cast(D)) {
 // Specifically diagnose references to class templates that are missing


Index: clang/test/SemaCXX/copy-assignment.cpp
===
--- clang/test/SemaCXX/copy-assignment.cpp
+++ clang/test/SemaCXX/copy-assignment.cpp
@@ -114,6 +114,7 @@
 namespace test1 {
   template class A : public unknown::X { // expected-error {{undeclared identifier 'unknown'}} expected-error {{expected class name}}
 A(UndeclaredType n) : X(n) {} // expected-error {{unknown type name 'UndeclaredType'}}
+// expected-error@-1 {{member initializer 'X' does not name a non-static data member or base class}}
   };
   template class B : public A {
 virtual void foo() {}
Index: clang/test/SemaCXX/constructor-initializer.cpp
===

[PATCH] D120812: [AST] Use RecoveryExpr to model a DeclRefExpr which refers to an invalid Decl.

2022-03-02 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/test/SemaCXX/copy-assignment.cpp:117
 A(UndeclaredType n) : X(n) {} // expected-error {{unknown type name 
'UndeclaredType'}}
+// expected-error@-1 {{member initializer 'X' does not name a non-static 
data member or base class}}
   };

This is a bogus diagnostic "accidentally" caused by this change, this is an 
existing problem in clang where we discard ill-formed base specifier.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120812

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


[PATCH] D120464: [clang][modules] Report module maps affecting `no_undeclared_includes` modules

2022-03-02 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/test/Modules/add-remove-irrelevant-module-map.m:36-38
+#if __has_include("d.h") // This should use 'd.modulemap' in order to 
determine that 'd.h'
+ // doesn't exist for 'c' because of its 
'[no_undeclared_includes]'.
+#endif

dexonsmith wrote:
> Would it be useful to also add a `#error` or similar inside the `#if`?
Yes, that makes sense. I'll add it before comitting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120464

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


[PATCH] D120465: [clang][deps] Generate necessary "-fmodule-map-file=" arguments, disable implicit module maps

2022-03-02 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:112
 
 void dependencies::detail::collectPCMAndModuleMapPaths(
 llvm::ArrayRef Modules,

dexonsmith wrote:
> Should this be renamed?
Yes, that would make sense.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:125-126
   PCMPaths.push_back(LookupPCMPath(MID).str());
-  if (!M.ClangModuleMapFile.empty())
-ModMapPaths.push_back(M.ClangModuleMapFile);
 }

dexonsmith wrote:
> Can you clarify why this is safe to remove, even though sometimes we do need 
> to add module map files?
This collects the module map files of transitive dependencies. We used it to 
generate `-fmodule-map-file=` arguments for builds of modules.

However, with explicit modules, it's not necessary to provide 
`-fmodule-map-file=` arguments of (transitive) dependencies at all. The module 
map semantics are basically serialized in the PCM files themselves. That's why 
this is safe to remove.

The new code below handles a special case (`[no_undeclared_includes]`) where we 
still need to generate some `-fmodule-map-file=` arguments. Semantics of such 
module maps will not be found in any PCM, since we don't import the modules 
they describe.

Note that caller of this function used to pass 
`FrontendOptions::ModuleMapFiles` member as `ModMapPaths`. The member is now 
being initialized in the new code below.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:269-273
+  // However, some module maps loaded implicitly during the dependency scan can
+  // describe anti-dependencies. That happens when the current module is marked
+  // as '[no_undeclared_includes]', doesn't 'use' module from such module map,
+  // but tries to import it anyway. We need to tell the explicit build about
+  // such module map for it to have the same semantics as the implicit build.

dexonsmith wrote:
> Is there another long-term solution to this that could be pointed at with a 
> FIXME? E.g., could the module map be encoded redundantly here? If so, what 
> else would need to change to make that okay?
I'm not sure I understand why this would warrant "long-term solution" or a 
FIXME. This code handles an existing feature that just happens to be a corner 
case from the dependency scanning point of view. (You can read up on the 
feature [[ https://clang.llvm.org/docs/Modules.html | here ]].)

What do you mean by encoding the module map redundantly?



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:275-278
+// We don't have a good way to determine which module map described the
+// anti-dependency (let alone what's the corresponding top-level module
+// map). We simply specify all the module maps in the order they were 
loaded
+// during the implicit build during scan.

dexonsmith wrote:
> Is there a FIXME to leave behind for tracking the anti-dependencies?
That's a good idea. I left a FIXME in D120464 to specifically serialize the 
information on anti-dependency introducing module maps here: D120464, but it 
would make sense to mention it here too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120465

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


[PATCH] D120793: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 412404.
ChuanqiXu added a comment.

Address comments.


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

https://reviews.llvm.org/D120793

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaModule.cpp

Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -365,13 +365,10 @@
 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path,
-   ModuleIdPath Partition) {
+   bool IsPartition) {
 
-  bool IsPartition = !Partition.empty();
   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
-  assert((!IsPartition || Path.empty()) &&
- "trying to import a partition with its named module specified?");
 
   // For a C++20 module name, flatten into a single identifier with the source
   // location of the first component.
@@ -386,9 +383,9 @@
 // otherwise, the name of the importing named module.
 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
 ModuleName += ":";
-ModuleName += stringFromPath(Partition);
-ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Partition[0].second};
-Partition = ModuleIdPath(ModuleNameLoc);
+ModuleName += stringFromPath(Path);
+ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
+Path = ModuleIdPath(ModuleNameLoc);
   } else if (Cxx20Mode) {
 ModuleName = stringFromPath(Path);
 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
@@ -410,13 +407,11 @@
   }
 
   Module *Mod = getModuleLoader().loadModule(
-  ImportLoc, IsPartition ? Partition : Path, Module::AllVisible,
-  /*IsInclusionDirective=*/false);
+  ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
   if (!Mod)
 return true;
 
-  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod,
-   IsPartition ? Partition : Path);
+  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
 }
 
 /// Determine whether \p D is lexically within an export-declaration.
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2420,7 +2420,7 @@
 
   // For C++20 modules, we can have "name" or ":Partition name" as valid input.
   SmallVector, 2> Path;
-  SmallVector, 2> Partition;
+  bool IsPartition = false;
   Module *HeaderUnit = nullptr;
   if (Tok.is(tok::header_name)) {
 // This is a header import that the preprocessor decided we should skip
@@ -2435,10 +2435,12 @@
 SourceLocation ColonLoc = ConsumeToken();
 if (!getLangOpts().CPlusPlusModules)
   Diag(ColonLoc, diag::err_unsupported_module_partition)
-  << SourceRange(ColonLoc, Partition.back().second);
+  << SourceRange(ColonLoc, Path.back().second);
 // Recover by leaving partition empty.
-else if (ParseModuleName(ColonLoc, Partition, /*IsImport*/ true))
+else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
   return nullptr;
+else
+  IsPartition = true;
   } else {
 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
   return nullptr;
@@ -2457,7 +2459,6 @@
 
   // Diagnose mis-imports.
   bool SeenError = true;
-  bool HasPart = !Partition.empty();
   switch (ImportState) {
   case Sema::ModuleImportState::ImportAllowed:
 SeenError = false;
@@ -2465,7 +2466,7 @@
   case Sema::ModuleImportState::FirstDecl:
   case Sema::ModuleImportState::NotACXX20Module:
 // We can only import a partition within a module purview.
-if (HasPart)
+if (IsPartition)
   Diag(ImportLoc, diag::err_partition_import_outside_module);
 else
   SeenError = false;
@@ -2474,7 +2475,7 @@
 // We can only have pre-processor directives in the global module
 // fragment.  We can, however have a header unit import here.
 if (!HeaderUnit)
-  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 0;
+  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0;
 else
   SeenError = false;
 break;
@@ -2485,7 +2486,7 @@
   SeenError = false;
 break;
   case Sema::ModuleImportState::PrivateFragment:
-Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 1;
+Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1;
 break;
   }
   if (SeenError) {
@@ -2497,9 +2498,9 @@
   if (HeaderUnit)
 Import =
 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
-  else if (!Path.empty() || !Partition.empty()

[PATCH] D120793: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:415
+  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
 }
 

iains wrote:
> it looks like there is an extra blank line before the closing brace..
No, it isn't. It shows by the review page.


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

https://reviews.llvm.org/D120793

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


[PATCH] D120812: [AST] Use RecoveryExpr to model a DeclRefExpr which refers to an invalid Decl.

2022-03-02 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Very nice! I thought we had considered and rejected this in the past, but I 
think it was rather allowing lookup to find invalid decls in cases where it 
doesn't today.




Comment at: clang/test/SemaCXX/constructor-initializer.cpp:252
 B(const String& s, int e=0) // expected-error {{unknown type name}} 
-  : A(e), m_String(s) , m_ErrorStr(__null) {} // expected-error {{no 
matching constructor}} expected-error {{does not name}}
+  : A(e), m_String(s) , m_ErrorStr(__null) {} // expected-error {{no 
matching constructor}} expected-error {{does not name}} expected-error {{member 
initializer 'm_ErrorStr' does not name}}
 B(const B& e)

update the other expected-error to to say what it refers to, too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120812

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


[PATCH] D93298: [RISCV] add the MC layer support of Zfinx extension

2022-03-02 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added a comment.

@achieveartificialintelligence thank you for looking into this, sorry for the 
late reply!

It looks like the latest version addresses @nikic's IR reproducer with 
`-mtriple=riscv32`.

There seems to be an error trying this out with `-mtriple=riscv64`:

  % cat test.ll
  define float @test(float %x) {
%1 = tail call float asm sideeffect alignstack "mv a0, a0", 
"={x10},{x10}"(float 0.00e+00)
ret float 0.00e+00
  }
  % llc -mtriple=riscv32 -mattr=+d test.ll
  % llc -mtriple=riscv64 -mattr=+d test.ll
  error: couldn't allocate output register for constraint '{x10}'

I'm not sure if this is intended to work `-mtriple=riscv64`, but judging by the 
newly added test `RUN: llc -mtriple=riscv64 ...` line it seems like it should?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

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


[clang] 3eb2da7 - [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-03-02T23:06:36+08:00
New Revision: 3eb2da76d77044802135350668da16d433a7c7b6

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

LOG: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and 
Parition

Reviewed By: iains

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

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Parse/Parser.cpp
clang/lib/Sema/SemaModule.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d905db93ccfff..9496d72cadcab 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2994,11 +2994,11 @@ class Sema final {
   /// \param ExportLoc The location of the 'export' keyword, if any.
   /// \param ImportLoc The location of the 'import' keyword.
   /// \param Path The module toplevel name as an access path.
-  /// \param Partition The module partition name as an access path.
+  /// \param IsPartition If the name is for a partition.
   DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path,
-   ModuleIdPath Partition = {});
+   bool IsPartition = false);
   DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,

diff  --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index b7e4be6e436e3..bc5b504ad1b8f 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -2420,7 +2420,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
 
   // For C++20 modules, we can have "name" or ":Partition name" as valid input.
   SmallVector, 2> Path;
-  SmallVector, 2> Partition;
+  bool IsPartition = false;
   Module *HeaderUnit = nullptr;
   if (Tok.is(tok::header_name)) {
 // This is a header import that the preprocessor decided we should skip
@@ -2435,10 +2435,12 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
 SourceLocation ColonLoc = ConsumeToken();
 if (!getLangOpts().CPlusPlusModules)
   Diag(ColonLoc, diag::err_unsupported_module_partition)
-  << SourceRange(ColonLoc, Partition.back().second);
+  << SourceRange(ColonLoc, Path.back().second);
 // Recover by leaving partition empty.
-else if (ParseModuleName(ColonLoc, Partition, /*IsImport*/ true))
+else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
   return nullptr;
+else
+  IsPartition = true;
   } else {
 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
   return nullptr;
@@ -2457,7 +2459,6 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
 
   // Diagnose mis-imports.
   bool SeenError = true;
-  bool HasPart = !Partition.empty();
   switch (ImportState) {
   case Sema::ModuleImportState::ImportAllowed:
 SeenError = false;
@@ -2465,7 +2466,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   case Sema::ModuleImportState::FirstDecl:
   case Sema::ModuleImportState::NotACXX20Module:
 // We can only import a partition within a module purview.
-if (HasPart)
+if (IsPartition)
   Diag(ImportLoc, diag::err_partition_import_outside_module);
 else
   SeenError = false;
@@ -2474,7 +2475,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
 // We can only have pre-processor directives in the global module
 // fragment.  We can, however have a header unit import here.
 if (!HeaderUnit)
-  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 0;
+  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0;
 else
   SeenError = false;
 break;
@@ -2485,7 +2486,7 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   SeenError = false;
 break;
   case Sema::ModuleImportState::PrivateFragment:
-Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 1;
+Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1;
 break;
   }
   if (SeenError) {
@@ -2497,9 +2498,9 @@ Decl *Parser::ParseModuleImport(SourceLocation AtLoc,
   if (HeaderUnit)
 Import =
 Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, HeaderUnit);
-  else if (!Path.empty() || !Partition.empty())
+  else if (!Path.empty())
 Import = Actions.ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Path,
-   Partition);
+   IsPartition);
   ExpectAndConsumeSemi(diag::err_module_expected_semi);
   if (Import.isInvalid())
 return nullptr;

diff  -

[PATCH] D120793: [NFC] [C++20] [Modules] Simplify ActOnModuleImport by merging Path and Parition

2022-03-02 Thread Chuanqi Xu 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 rG3eb2da76d770: [NFC] [C++20] [Modules] Simplify 
ActOnModuleImport by merging Path and Parition (authored by ChuanqiXu).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120793

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaModule.cpp

Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -365,13 +365,10 @@
 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path,
-   ModuleIdPath Partition) {
+   bool IsPartition) {
 
-  bool IsPartition = !Partition.empty();
   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
-  assert((!IsPartition || Path.empty()) &&
- "trying to import a partition with its named module specified?");
 
   // For a C++20 module name, flatten into a single identifier with the source
   // location of the first component.
@@ -386,9 +383,9 @@
 // otherwise, the name of the importing named module.
 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
 ModuleName += ":";
-ModuleName += stringFromPath(Partition);
-ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Partition[0].second};
-Partition = ModuleIdPath(ModuleNameLoc);
+ModuleName += stringFromPath(Path);
+ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
+Path = ModuleIdPath(ModuleNameLoc);
   } else if (Cxx20Mode) {
 ModuleName = stringFromPath(Path);
 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
@@ -410,13 +407,11 @@
   }
 
   Module *Mod = getModuleLoader().loadModule(
-  ImportLoc, IsPartition ? Partition : Path, Module::AllVisible,
-  /*IsInclusionDirective=*/false);
+  ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
   if (!Mod)
 return true;
 
-  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod,
-   IsPartition ? Partition : Path);
+  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
 }
 
 /// Determine whether \p D is lexically within an export-declaration.
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -2420,7 +2420,7 @@
 
   // For C++20 modules, we can have "name" or ":Partition name" as valid input.
   SmallVector, 2> Path;
-  SmallVector, 2> Partition;
+  bool IsPartition = false;
   Module *HeaderUnit = nullptr;
   if (Tok.is(tok::header_name)) {
 // This is a header import that the preprocessor decided we should skip
@@ -2435,10 +2435,12 @@
 SourceLocation ColonLoc = ConsumeToken();
 if (!getLangOpts().CPlusPlusModules)
   Diag(ColonLoc, diag::err_unsupported_module_partition)
-  << SourceRange(ColonLoc, Partition.back().second);
+  << SourceRange(ColonLoc, Path.back().second);
 // Recover by leaving partition empty.
-else if (ParseModuleName(ColonLoc, Partition, /*IsImport*/ true))
+else if (ParseModuleName(ColonLoc, Path, /*IsImport*/ true))
   return nullptr;
+else
+  IsPartition = true;
   } else {
 if (ParseModuleName(ImportLoc, Path, /*IsImport*/ true))
   return nullptr;
@@ -2457,7 +2459,6 @@
 
   // Diagnose mis-imports.
   bool SeenError = true;
-  bool HasPart = !Partition.empty();
   switch (ImportState) {
   case Sema::ModuleImportState::ImportAllowed:
 SeenError = false;
@@ -2465,7 +2466,7 @@
   case Sema::ModuleImportState::FirstDecl:
   case Sema::ModuleImportState::NotACXX20Module:
 // We can only import a partition within a module purview.
-if (HasPart)
+if (IsPartition)
   Diag(ImportLoc, diag::err_partition_import_outside_module);
 else
   SeenError = false;
@@ -2474,7 +2475,7 @@
 // We can only have pre-processor directives in the global module
 // fragment.  We can, however have a header unit import here.
 if (!HeaderUnit)
-  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 0;
+  Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 0;
 else
   SeenError = false;
 break;
@@ -2485,7 +2486,7 @@
   SeenError = false;
 break;
   case Sema::ModuleImportState::PrivateFragment:
-Diag(ImportLoc, diag::err_import_in_wrong_fragment) << HasPart << 1;
+Diag(ImportLoc, diag::err_import_in_wrong_fragment) << IsPartition << 1;
 b

[PATCH] D120474: [clang][deps] Remove '-fmodules-cache-path=' arguments

2022-03-02 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp:36
+  llvm::erase_if(Args, [](const std::string &Arg) {
+return Arg.find("-fmodules-cache-path=") == 0;
+  });

dexonsmith wrote:
> Is that the only one to remove? (asking because you dropped the FIXME, which 
> suggested it might only be one example)
> 
> Also, could this just be an assertion, since 
> `makeInvocationForModuleBuildWithoutPaths()` is already clearing things?
> - In other words, why do you need this in two places?
> - And if you do need it in both, does the test cover both, or should there be 
> another test or RUN line for the other code path?
Ah, there are some others (e.g. `-fmodules-prune-interval=`, 
`-fmodules-prune-after=`) so you're right dropping the FIXME might be a bit 
hasty. I'll update the fixme instead of removing it.

This cannot be an assertion unfortunately. 
`makeInvocationForModuleBuildWithoutPaths()` is clearing the modules cache path 
in the **-cc1** command lines for building **modules**. This however, is 
dealing with the **driver** command line for building the original 
**translation unit**, which doesn't go through the `CompilerInvocation` 
machinery at all. We're relying on textual manipulation here at this moment. 
(TU command lines are driver command lines that might expand into multiple 
commands and therefore are not guaranteed to be representable by single 
`CompilerInvocation`.)

The test I touched covers only this change to the driver command line for 
building the TU. The error (`-Wunused-command-line-argument`) I test is only 
produced by the driver. This means the other change (clearing modules cache 
path in -cc1 `CompilerInvocation`) is just a preventive measure, not necessary 
to make the updated test pass and not testable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120474

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


[PATCH] D120814: [clang-tidy] Add check to perfer pre-increment over post-increment

2022-03-02 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik created this revision.
philnik added reviewers: aaron.ballman, JonasToth.
Herald added subscribers: carlosgalvezp, xazax.hun, mgorny.
Herald added a project: All.
philnik requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120814

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/clang-tidy/performance/UsePreincrementCheck.cpp
  clang-tools-extra/clang-tidy/performance/UsePreincrementCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance-use-preincrement.rst
  clang-tools-extra/test/clang-tidy/checkers/performance-use-preincrement.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-use-preincrement.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance-use-preincrement.cpp
@@ -0,0 +1,23 @@
+// RUN: %check_clang_tidy %s performance-use-preincrement %t
+
+void positivePostincrement() {
+  int I = 0;
+  I++;
+  // CHECK-MESSAGES: [[@LINE-1]]:4: warning: Preincrement could be used instead of postincrement. [performance-use-preincrement]
+}
+
+void negativePreincrement() {
+  int I = 0;
+  ++I;
+}
+
+void negativeUsedPostincrement() {
+  int I = 0;
+  int J = I++;
+  ++J;
+  J = I++;
+}
+
+int negativeReturn(int &I) {
+  return I++;
+}
Index: clang-tools-extra/docs/clang-tidy/checks/performance-use-preincrement.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/performance-use-preincrement.rst
@@ -0,0 +1,7 @@
+.. title:: clang-tidy - performance-use-preincrement
+
+performance-use-preincrement
+
+
+Checks that preincrement is used when there is no need for postincrement.
+This can lead to improved performance with iterators that are not trivially copyable.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -84,7 +84,7 @@
`bugprone-posix-return `_, "Yes"
`bugprone-redundant-branch-condition `_, "Yes"
`bugprone-reserved-identifier `_, "Yes"
-   `bugprone-shared-ptr-array-mismatch `_, "Yes"
+   `bugprone-shared-ptr-array-mismatch `_,
`bugprone-signal-handler `_,
`bugprone-signed-char-misuse `_,
`bugprone-sizeof-container `_,
@@ -286,6 +286,7 @@
`performance-type-promotion-in-math-fn `_, "Yes"
`performance-unnecessary-copy-initialization `_, "Yes"
`performance-unnecessary-value-param `_, "Yes"
+   `performance-use-preincrement `_, "Yes"
`portability-restrict-system-includes `_, "Yes"
`portability-simd-intrinsics `_,
`readability-avoid-const-params-in-decls `_, "Yes"
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -103,6 +103,11 @@
 
   Finds initializations of C++ shared pointers to non-array type that are initialized with an array.
 
+- New :doc:`performance-use-preincrement
+  ` check.
+
+  FIXME: add release notes.
+
 New check aliases
 ^
 
Index: clang-tools-extra/clang-tidy/performance/UsePreincrementCheck.h
===
--- /dev/null
+++ clang-tools-extra/clang-tidy/performance/UsePreincrementCheck.h
@@ -0,0 +1,34 @@
+//===--- UsePreincrementCheck.h - clang-tidy *- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_USEPREINCREMENTCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_USEPREINCREMENTCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace performance {
+
+/// Checks that preincrement is used when there is no need for postincrement
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/performance-use-preincrement.html
+class UsePreincrementCheck : public ClangTidyCheck {
+public:
+  UsePreincrementCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};
+
+} // namespace performance
+} // namespac

[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Please mark the done comments as "done" with the corresponding button prior to 
submitting an update.




Comment at: clang/test/Analysis/bstring_UninitRead.c:67-85
+//===--===
+// mempcpy()
+//===--===
+
+#ifdef VARIANT
+
+#define __mempcpy_chk BUILTIN(__mempcpy_chk)

I don't think you should copy these as well.
The matching logic is already tested in `bstring.c`.

That being said, a single `RUN` line should be enough in this file.



Comment at: clang/test/Analysis/bstring_UninitRead.c:91-94
+  p = mempcpy(dst, src, 4 * sizeof(int)); // expected-warning{{Bytes string 
function accesses uninitialized/garbage values}}
+  // FIXME: This behaviour is actually Unexpected and needs to be fix, 
+  // mempcpy seems to consider the src buffered byte as uninitialized
+  // and returning undef which is actually not the case It should return 
something like Unknown .




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[clang] ca94f28 - [clang] ExprEngine::VisitCXXNewExpr - remove superfluous nullptr tests

2022-03-02 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2022-03-02T15:59:10Z
New Revision: ca94f28d15d53bb77ad347d6e374486475f86121

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

LOG: [clang] ExprEngine::VisitCXXNewExpr - remove superfluous nullptr tests

FD has already been dereferenced

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index ba105f34a9158..0a6127d800152 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
@@ -883,13 +883,10 @@ void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, 
ExplodedNode *Pred,
 // where new can return NULL. If we end up supporting that option, we can
 // consider adding a check for it here.
 // C++11 [basic.stc.dynamic.allocation]p3.
-if (FD) {
-  QualType Ty = FD->getType();
-  if (const auto *ProtoType = Ty->getAs())
-if (!ProtoType->isNothrow())
-  if (auto dSymVal = symVal.getAs())
-State = State->assume(*dSymVal, true);
-}
+if (const auto *ProtoType = FD->getType()->getAs())
+  if (!ProtoType->isNothrow())
+if (auto dSymVal = symVal.getAs())
+  State = State->assume(*dSymVal, true);
   }
 
   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
@@ -914,7 +911,7 @@ void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, 
ExplodedNode *Pred,
   // CXXNewExpr, we need to make sure that the constructed object is not
   // immediately invalidated here. (The placement call should happen before
   // the constructor call anyway.)
-  if (FD && FD->isReservedGlobalPlacementOperator()) {
+  if (FD->isReservedGlobalPlacementOperator()) {
 // Non-array placement new should always return the placement location.
 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),



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


[PATCH] D120360: [libTooling] Generalize string explanation as Any metadata

2022-03-02 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Looks really good!




Comment at: clang/include/clang/Tooling/Transformer/RewriteRule.h:64
 
 using TextGenerator = std::shared_ptr>;
 

(and move down to after `Generator` def.)



Comment at: clang/include/clang/Tooling/Transformer/RewriteRule.h:291
 
-  /// DEPRECATED: use `::clang::transformer::RootID` instead.
-  static const llvm::StringRef RootID;
+template  struct RewriteRuleWith : RewriteRuleBase {
+  SmallVector, 1> Metadata;

Please comment.



Comment at: clang/include/clang/Tooling/Transformer/RewriteRule.h:300
 /// Constructs a simple \c RewriteRule.
 RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
+ EditGenerator Edits);

Maybe add an adaptor for edit generator like we do in Stencil::cat. That will 
allow us to collapse the 6 overloads (2 * 3) into 2 (for makerule) + 3 (for the 
adaptor).  Only saves 1 but I think it will clearer and more flexible for the 
future.



Comment at: clang/include/clang/Tooling/Transformer/RewriteRule.h:507
 
 /// Returns the \c Case of \c Rule that was selected in the match result.
 /// Assumes a matcher built with \c buildMatcher.

please update



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:22
+
+namespace internal_transformer {
+/// Implementation details of \c Transformer with type erasure around

in RewriteRule.h, we use "detail". Maybe do the same here?



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:48
+/// \c RewriteRule.
+class PlainConsumer final : public TransformerImpl {
+  transformer::RewriteRule Rule;

I'm afraid the use of the name `Consumer` (here and below) might be confused 
with the `Consumer` argument.  What about just `Impl` or something similar?



Comment at: clang/include/clang/Tooling/Transformer/Transformer.h:116
+  explicit Transformer(transformer::RewriteRuleWith Rule,
+   ConsumerFn Consumer);
 

why won't we have the same SFINAE here to ensure ConsumerFn is invocable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120360

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


[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Johel Ernesto Guerrero Peña via Phabricator via cfe-commits
JohelEGP accepted this revision.
JohelEGP added a comment.

My few cases format consistently with the condition case:

  diff
  diff --git a/tests/integration/test.waarudo.io.dynamic.cpp 
b/tests/integration/test.waarudo.io.dynamic.cpp
  index be5a626..e1265b9 100644
  --- a/tests/integration/test.waarudo.io.dynamic.cpp
  +++ b/tests/integration/test.waarudo.io.dynamic.cpp
  @@ -21,7 +21,7 @@ public:
 }
   
 constexpr ~input_source() {
  -if (std::is_constant_evaluated()) {
  +if consteval {
 expects(input_byte == previous_input_byte);
   } else {
 std::ofstream{"test.waarudo.io.dynamic.previous.input.byte.txt"} << 
"waarudo::byte{'"
  @@ -37,7 +37,7 @@ public:
 [[nodiscard]] constexpr waarudo::output_bytes output() override { return 
{&output_byte, 1z}; }
   
 constexpr ~output_destination() {
  -if (std::is_constant_evaluated()) {
  +if consteval {
 expects(output_byte == previous_output_byte);
   } else {
 std::cout << std::bit_cast(output_byte);
  diff --git a/tests/waarudo.test.utilities.cpp 
b/tests/waarudo.test.utilities.cpp
  index ed82b2b..f4ec8e3 100644
  --- a/tests/waarudo.test.utilities.cpp
  +++ b/tests/waarudo.test.utilities.cpp
  @@ -13,7 +13,7 @@ export template concept constant_invocable = 
requires { typename std::in
   export using waarudo::expects;
   
   export constexpr void runtime(void (*const f)()) {
  -  if (not std::is_constant_evaluated()) f();
  +  if not consteval { f(); }
   }
   
   template F> void visit_values(F f) {

Thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added inline comments.



Comment at: clang/test/Analysis/bstring_UninitRead.c:67-85
+//===--===
+// mempcpy()
+//===--===
+
+#ifdef VARIANT
+
+#define __mempcpy_chk BUILTIN(__mempcpy_chk)

steakhal wrote:
> I don't think you should copy these as well.
> The matching logic is already tested in `bstring.c`.
> 
> That being said, a single `RUN` line should be enough in this file.
I'm not able to run test successfully with single RUN , 
```
// RUN: -analyzer-checker=alpha.unix.cstring.UninitializedRead

```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120824: [clang][ASTImporter] Fix a bug when importing CXXDefaultInitExpr.

2022-03-02 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, martong, gamesh411, Szelethus, dkrupp.
Herald added a reviewer: a.sidorin.
Herald added a reviewer: shafik.
Herald added a reviewer: Szelethus.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The "in-class initializer" expression should be set in the field of a
default initialization expression before this expression node is created.
The `CXXDefaultInitExpr` objects are created after the AST is loaded and
at import not present in the "To" AST. And the in-class initializers of
the used fields can be missing too, these must be set at import.

This fixes a github issue #54061.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120824

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/test/Analysis/Inputs/ctu-cxxdefaultinitexpr-import.cpp
  clang/test/Analysis/ctu-cxxdefaultinitexpr.cpp
  clang/unittests/AST/ASTImporterTest.cpp

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -530,6 +530,21 @@
has(floatLiteral(equals(1.0);
 }
 
+const internal::VariadicDynCastAllOfMatcher
+cxxDefaultInitExpr;
+
+TEST_P(ImportExpr, ImportCXXDefaultInitExpr) {
+  MatchVerifier Verifier;
+  testImport("class declToImport { int DefInit = 5; }; declToImport X;",
+ Lang_CXX11, "", Lang_CXX11, Verifier,
+ cxxRecordDecl(hasDescendant(cxxConstructorDecl(
+ hasAnyConstructorInitializer(cxxCtorInitializer(
+ withInitializer(cxxDefaultInitExpr(;
+  testImport(
+  "struct X { int A = 5; }; X declToImport{};", Lang_CXX17, "", Lang_CXX17,
+  Verifier,
+  varDecl(hasInitializer(initListExpr(hasInit(0, cxxDefaultInitExpr());
+}
 
 const internal::VariadicDynCastAllOfMatcher vaArgExpr;
 
Index: clang/test/Analysis/ctu-cxxdefaultinitexpr.cpp
===
--- /dev/null
+++ clang/test/Analysis/ctu-cxxdefaultinitexpr.cpp
@@ -0,0 +1,35 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: clang-extdef-mapping %S/Inputs/ctu-cxxdefaultinitexpr-import.cpp -- -std=c++17 > %t/externalDefMap.txt
+// RUN: sed -i "s:%S/Inputs/ctu-cxxdefaultinitexpr-import.cpp:ctu-cxxdefaultinitexpr-import.cpp.ast:g" %t/externalDefMap.txt
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -std=c++17 \
+// RUN:   -emit-pch -o %t/ctu-cxxdefaultinitexpr-import.cpp.ast %S/Inputs/ctu-cxxdefaultinitexpr-import.cpp
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -std=c++17 -analyze \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-config experimental-enable-naive-ctu-analysis=true \
+// RUN:   -analyzer-config ctu-dir=%t \
+// RUN:   -verify %s
+
+// Check that importing this code does not cause crash.
+// expected-no-diagnostics
+
+namespace QHashPrivate {
+template  int b;
+struct Data;
+} // namespace QHashPrivate
+
+struct QDomNodePrivate {};
+template  struct QMultiHash {
+  QHashPrivate::Data *d = nullptr;
+};
+
+struct QDomNamedNodeMapPrivate {
+  QMultiHash<> map;
+};
+struct QDomElementPrivate : QDomNodePrivate {
+  QDomElementPrivate();
+  void importee();
+  QMultiHash<> *m_attr = nullptr;
+};
+// - common part end -
+
+void importer(QDomElementPrivate x) { x.importee(); }
Index: clang/test/Analysis/Inputs/ctu-cxxdefaultinitexpr-import.cpp
===
--- /dev/null
+++ clang/test/Analysis/Inputs/ctu-cxxdefaultinitexpr-import.cpp
@@ -0,0 +1,26 @@
+namespace QHashPrivate {
+template  int b;
+struct Data;
+} // namespace QHashPrivate
+
+struct QDomNodePrivate {};
+template  struct QMultiHash {
+  QHashPrivate::Data *d = nullptr;
+};
+
+struct QDomNamedNodeMapPrivate {
+  QMultiHash<> map;
+};
+struct QDomElementPrivate : QDomNodePrivate {
+  QDomElementPrivate();
+  void importee();
+  QMultiHash<> *m_attr = nullptr;
+};
+// - common part end -
+
+QDomElementPrivate::QDomElementPrivate() : m_attr{new QMultiHash<>} {}
+void QDomElementPrivate::importee() { (void)QMultiHash<>{}; }
+struct foo {
+  QDomElementPrivate m = {};
+  static const int value = (QHashPrivate::b, 22);
+};
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3646,19 +3646,23 @@
 // initializer of a FieldDecl might not had been instantiated in the
 // "To" context.  However, the "From" context might instantiated that,
 // thus we have to merge that.
+// Note: `hasInClassInitializer()` is not the same as non-null
+// `getInClassInitializer()` value.
 if (Expr *FromInitializer = D->getInClassInitializer()) {
-  // We don't have ye

[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Great, I'll add a few test cases when landing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


[clang] 13351fd - [clang-format] Recognize "if consteval".

2022-03-02 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-02T17:46:45+01:00
New Revision: 13351fdf8cb448ffd60727f031df0d7cb348e48a

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

LOG: [clang-format] Recognize "if consteval".

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

Reviewed By: MyDeveloperDay, JohelEGP

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 8f034a8ce1599..46562f7ae8b84 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2384,10 +2384,16 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
-  if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  if (FormatTok->is(tok::exclaim))
 nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
+  if (FormatTok->is(tok::kw_consteval)) {
+nextToken();
+  } else {
+if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  nextToken();
+if (FormatTok->is(tok::l_paren))
+  parseParens();
+  }
   HandleAttributes();
 
   bool NeedsUnwrappedLine = false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 5fa56a9048b03..94f6dea1a2ed4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -583,6 +583,29 @@ TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
"  }\n"
"g();");
 
+  verifyFormat("if consteval {\n}");
+  verifyFormat("if !consteval {\n}");
+  verifyFormat("if not consteval {\n}");
+  verifyFormat("if consteval {\n} else {\n}");
+  verifyFormat("if !consteval {\n} else {\n}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}");
+  verifyFormat("if CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+
   verifyFormat("if (a)\n"
"  g();");
   verifyFormat("if (a) {\n"
@@ -1569,6 +1592,9 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if consteval {}", AllowSimpleBracedStatements);
+  verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
+  verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
@@ -1577,9 +1603,13 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if (true) { fff(); }",



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


[PATCH] D120806: [clang-format] Recognize "if consteval".

2022-03-02 Thread Marek Kurdej via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG13351fdf8cb4: [clang-format] Recognize "if 
consteval". (authored by curdeius).

Changed prior to commit:
  https://reviews.llvm.org/D120806?vs=412366&id=412444#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120806

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -583,6 +583,29 @@
"  }\n"
"g();");
 
+  verifyFormat("if consteval {\n}");
+  verifyFormat("if !consteval {\n}");
+  verifyFormat("if not consteval {\n}");
+  verifyFormat("if consteval {\n} else {\n}");
+  verifyFormat("if !consteval {\n} else {\n}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}");
+  verifyFormat("if CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+
   verifyFormat("if (a)\n"
"  g();");
   verifyFormat("if (a) {\n"
@@ -1569,6 +1592,9 @@
   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if consteval {}", AllowSimpleBracedStatements);
+  verifyFormat("if !consteval {}", AllowSimpleBracedStatements);
+  verifyFormat("if CONSTEVAL {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
@@ -1577,9 +1603,13 @@
   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if consteval { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("if CONSTEVAL { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("MYIF consteval { f(); }", AllowSimpleBracedStatements);
+  verifyFormat("MYIF CONSTEVAL { f(); }", AllowSimpleBracedStatements);
   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
   verifyFormat("if (true) { fff(); }",
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -2384,10 +2384,16 @@
 
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
-  if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  if (FormatTok->is(tok::exclaim))
 nextToken();
-  if (FormatTok->is(tok::l_paren))
-parseParens();
+  if (FormatTok->is(tok::kw_consteval)) {
+nextToken();
+  } else {
+if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
+  nextToken();
+if (FormatTok->is(tok::l_paren))
+  parseParens();
+  }
   HandleAttributes();
 
   bool NeedsUnwrappedLine = false;


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -583,6 +583,29 @@
"  }\n"
"g();");
 
+  verifyFormat("if consteval {\n}");
+  verifyFormat("if !consteval {\n}");
+  verifyFormat("if not consteval {\n}");
+  verifyFormat("if consteval {\n} else {\n}");
+  verifyFormat("if !consteval {\n} else {\n}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !consteval {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if consteval {\n"
+   "  f();\n"
+   "} else {\n"
+   "  g();\n"
+   "}");
+  verifyFormat("if CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if !CONSTEVAL {\n"
+   "  f();\n"
+   "}");
+
   verifyFormat("if (a)\n"
"  g();");
   verifyFormat("if (a) {\n"
@@ -1569,6 +1592,9 @@
   verifyFormat("if (true) 

[PATCH] D53847: [C++2a] P0634r3: Down with typename!

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.
Herald added a project: All.

In D53847#3252460 , @cjdb wrote:

> What's the status of this patch?

It appears to me that the 'delta' right now is a couple of cases where this 
patch doesn't properly diagnose/warn (see the convo in SemaTemplate.cpp )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D53847

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


[PATCH] D120710: [clang-format] QualifierOrder does not reorder template arguments

2022-03-02 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.
Herald added a project: All.



Comment at: clang/unittests/Format/QualifierFixerTest.cpp:910
+   Style);
+  verifyFormat("TemplateType t;", "TemplateType t;", Style);
+}

HazardyKnusperkeks wrote:
> As far as I understand stuff like `` worked before? But 
> maybe still add it as test case.
It didn't work before at all.
+1 for adding a test with a longer name.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120710

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


[clang] d112cc2 - [NFC][Clang][OpaquePtr] Remove the call to Address::deprecated in

2022-03-02 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2022-03-02T08:58:00-08:00
New Revision: d112cc27569b8329b4c9090265b809d459a4a5a8

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

LOG: [NFC][Clang][OpaquePtr] Remove the call to Address::deprecated in
CreatePointerBitCastOrAddrSpaceCast

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

Added: 


Modified: 
clang/lib/CodeGen/CGAtomic.cpp
clang/lib/CodeGen/CGBuilder.h
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
clang/lib/CodeGen/CGStmtOpenMP.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index 3eefe753bbe6a..dee0cb64be97b 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -304,7 +304,8 @@ Address AtomicInfo::CreateTempAlloca() const {
   // Cast to pointer to value type for bitfields.
   if (LVal.isBitField())
 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
-TempAlloca, getAtomicAddress().getType());
+TempAlloca, getAtomicAddress().getType(),
+getAtomicAddress().getElementType());
   return TempAlloca;
 }
 

diff  --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index 27ced0cec041b..c087aa4635881 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -171,10 +171,11 @@ class CGBuilderTy : public CGBuilderBaseTy {
 
   using CGBuilderBaseTy::CreatePointerBitCastOrAddrSpaceCast;
   Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty,
+  llvm::Type *ElementTy,
   const llvm::Twine &Name = "") {
 llvm::Value *Ptr =
 CreatePointerBitCastOrAddrSpaceCast(Addr.getPointer(), Ty, Name);
-return Address::deprecated(Ptr, Addr.getAlignment());
+return Address(Ptr, ElementTy, Addr.getAlignment());
   }
 
   /// Given

diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 8f1e60805356e..ad8019989dac8 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2707,7 +2707,7 @@ LValue CodeGenFunction::EmitDeclRefLValue(const 
DeclRefExpr *E) {
 auto *PTy = llvm::PointerType::get(
 VarTy, getContext().getTargetAddressSpace(VD->getType()));
 if (PTy != Addr.getType())
-  Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
+  Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
   } else {
 // Should we be using the alignment of the constant pointer we emitted?
 CharUnits Alignment =

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index c392e37452a78..399b2f63e8443 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -2502,9 +2502,8 @@ void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction 
&CGF,
 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
-Address CL =
-  CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
-  CGF.VoidPtrTy);
+Address CL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
+CopyprivateList, CGF.VoidPtrTy, CGF.Int8Ty);
 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
 llvm::Value *Args[] = {
 emitUpdateLocation(CGF, Loc), // ident_t *
@@ -3647,12 +3646,12 @@ emitProxyTaskFunction(CodeGenModule &CGM, 
SourceLocation Loc,
 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
   }
 
-  llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
-   TaskPrivatesMap,
-   CGF.Builder
-   .CreatePointerBitCastOrAddrSpaceCast(
-   TDBase.getAddress(CGF), CGF.VoidPtrTy)
-   .getPointer()};
+  llvm::Value *CommonArgs[] = {
+  GtidParam, PartidParam, PrivatesParam, TaskPrivatesMap,
+  CGF.Builder
+  .CreatePointerBitCastOrAddrSpaceCast(TDBase.getAddress(CGF),
+   CGF.VoidPtrTy, CGF.Int8Ty)
+  .getPointer()};
   SmallVector CallArgs(std::begin(CommonArgs),
   std::end(CommonArgs));
   if (isOpenMPTaskLoopDirective(Kind)) {
@@ -3872,7 +3871,8 @@ static void emitPrivatesInit(CodeGenFunction &CGF,
   (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
 SrcBase = CGF.MakeAddrLValue(
 CGF.Builder.CreatePoint

[PATCH] D120757: [NFC][Clang][OpaquePtr] Remove the call to Address::deprecated in CreatePointerBitCastOrAddrSpaceCast

2022-03-02 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd112cc27569b: [NFC][Clang][OpaquePtr] Remove the call to 
Address::deprecated in (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120757

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGBuilder.h
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp

Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -670,7 +670,8 @@
 LV.setAddress(WrapperCGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
 LV.getAddress(WrapperCGF),
 PI->getType()->getPointerTo(
-LV.getAddress(WrapperCGF).getAddressSpace(;
+LV.getAddress(WrapperCGF).getAddressSpace()),
+PI->getType()));
   CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc());
 } else {
   auto EI = VLASizes.find(Arg);
@@ -7000,10 +7001,11 @@
   EmitLoadOfPointer(PrivAddr, getContext()
   .getPointerType(OrigVD->getType())
   ->castAs());
-llvm::Type *RealTy =
-ConvertTypeForMem(OrigVD->getType().getNonReferenceType())
-->getPointerTo();
-PrivAddr = Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy);
+llvm::Type *RealElTy =
+ConvertTypeForMem(OrigVD->getType().getNonReferenceType());
+llvm::Type *RealTy = RealElTy->getPointerTo();
+PrivAddr =
+Builder.CreatePointerBitCastOrAddrSpaceCast(PrivAddr, RealTy, RealElTy);
 
 (void)PrivateScope.addPrivate(OrigVD, [PrivAddr]() { return PrivAddr; });
   }
Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -1716,7 +1716,8 @@
  CastTy->hasSignedIntegerRepresentation());
   Address CastItem = CGF.CreateMemTemp(CastTy);
   Address ValCastItem = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
-  CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()));
+  CastItem, Val->getType()->getPointerTo(CastItem.getAddressSpace()),
+  Val->getType());
   CGF.EmitStoreOfScalar(Val, ValCastItem, /*Volatile=*/false, ValTy,
 LValueBaseInfo(AlignmentSource::Type),
 TBAAAccessInfo());
@@ -1779,7 +1780,7 @@
   Address ElemPtr = DestAddr;
   Address Ptr = SrcAddr;
   Address PtrEnd = Bld.CreatePointerBitCastOrAddrSpaceCast(
-  Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy);
+  Bld.CreateConstGEP(SrcAddr, 1), CGF.VoidPtrTy, CGF.Int8Ty);
   for (int IntSize = 8; IntSize >= 1; IntSize /= 2) {
 if (Size < CharUnits::fromQuantity(IntSize))
   continue;
@@ -1787,9 +1788,10 @@
 CGF.getContext().toBits(CharUnits::fromQuantity(IntSize)),
 /*Signed=*/1);
 llvm::Type *IntTy = CGF.ConvertTypeForMem(IntType);
-Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo());
-ElemPtr =
-Bld.CreatePointerBitCastOrAddrSpaceCast(ElemPtr, IntTy->getPointerTo());
+Ptr = Bld.CreatePointerBitCastOrAddrSpaceCast(Ptr, IntTy->getPointerTo(),
+  IntTy);
+ElemPtr = Bld.CreatePointerBitCastOrAddrSpaceCast(
+ElemPtr, IntTy->getPointerTo(), IntTy);
 if (Size.getQuantity() / IntSize > 1) {
   llvm::BasicBlock *PreCondBB = CGF.createBasicBlock(".shuffle.pre_cond");
   llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".shuffle.then");
@@ -3545,7 +3547,7 @@
   if (isOpenMPLoopBoundSharingDirective(D.getDirectiveKind())) {
 Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
 Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
-Src, CGF.SizeTy->getPointerTo());
+Src, CGF.SizeTy->getPointerTo(), CGF.SizeTy);
 llvm::Value *LB = CGF.EmitLoadOfScalar(
 TypedAddress,
 /*Volatile=*/false,
@@ -3555,7 +3557,7 @@
 ++Idx;
 Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, Idx);
 TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
-Src, CGF.SizeTy->getPointerTo());
+Src, CGF.SizeTy->getPointerTo(), CGF.SizeTy);
 llvm::Value *UB = CGF.EmitLoadOfScalar(
 TypedAddress,
 /*Volatile=*/false,
@@ -3570,7 +3572,8 @@
   QualType ElemTy = CurField->getType();
   Address Src = Bld.CreateConstInBoundsGEP(SharedArgListAddress, I + Idx);
   Address TypedAddress = Bld.CreatePointerBitCastOrAddrSpaceCast(
-  Src, CGF.ConvertTypeForMem(CGFContext.getPointerType(ElemTy)));
+

[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/test/Analysis/bstring_UninitRead.c:1-84
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=unix.cstring \
+// RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-checker=debug.ExprInspection \
+// RUN:   -analyzer-config eagerly-assume=false  
+//

I was thinking about something like this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added inline comments.



Comment at: clang/test/Analysis/bstring_UninitRead.c:67-85
+//===--===
+// mempcpy()
+//===--===
+
+#ifdef VARIANT
+
+#define __mempcpy_chk BUILTIN(__mempcpy_chk)

phyBrackets wrote:
> steakhal wrote:
> > I don't think you should copy these as well.
> > The matching logic is already tested in `bstring.c`.
> > 
> > That being said, a single `RUN` line should be enough in this file.
> I'm not able to run test successfully with single RUN , 
> ```
> // RUN: -analyzer-checker=alpha.unix.cstring.UninitializedRead
> 
> ```
wait , I think I got this! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets updated this revision to Diff 412452.
phyBrackets added a comment.

Remove unneccesary RUN and some macros definitions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/bstring.c
  clang/test/Analysis/bstring_UninitRead.c

Index: clang/test/Analysis/bstring_UninitRead.c
===
--- /dev/null
+++ clang/test/Analysis/bstring_UninitRead.c
@@ -0,0 +1,59 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN: -analyzer-checker=alpha.unix.cstring 
+
+
+// This file is generally for the alpha.unix.cstring.UninitializedRead Checker, the reason for putting it into
+// the separate file because the checker is break the some existing test cases in bstring.c file , so we don't 
+// wanna mess up with some existing test case so it's better to create separate file for it, this file also include 
+// the broken test for the reference in future about the broken tests.
+
+
+typedef typeof(sizeof(int)) size_t;
+
+void clang_analyzer_eval(int);
+
+void *memcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+void top(char *dst) {
+  char buf[10];
+  memcpy(dst, buf, 10); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  (void)buf;
+}
+
+//===--===
+// mempcpy()
+//===--===
+
+void *mempcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+void mempcpy14() {
+  int src[] = {1, 2, 3, 4};
+  int dst[5] = {0};
+  int *p;
+
+  p = mempcpy(dst, src, 4 * sizeof(int)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+   // FIXME: This behaviour is actually surprising and needs to be fixed, 
+   // mempcpy seems to consider the very last byte of the src buffer uninitialized
+   // and returning undef unfortunately. It should have returned unknown or a conjured value instead.
+
+  clang_analyzer_eval(p == &dst[4]); // no-warning (above is fatal)
+}
+
+struct st {
+  int i;
+  int j;
+};
+
+
+void mempcpy15() {
+  struct st s1 = {0};
+  struct st s2;
+  struct st *p1;
+  struct st *p2;
+
+  p1 = (&s2) + 1;
+  p2 = mempcpy(&s2, &s1, sizeof(struct st)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  // FIXME: It seems same as mempcpy14() case.
+  
+  clang_analyzer_eval(p1 == p2); // no-warning (above is fatal)
+}
Index: clang/test/Analysis/bstring.c
===
--- clang/test/Analysis/bstring.c
+++ clang/test/Analysis/bstring.c
@@ -2,13 +2,15 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
-// RUN:   -analyzer-config eagerly-assume=false
+// RUN:   -analyzer-config eagerly-assume=false  
 //
 // RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS \
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 //
@@ -16,6 +18,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 //
@@ -23,6 +26,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 
@@ -70,7 +74,6 @@
 
 #endif /* VARIANT */
 
-
 void memcpy0 () {
   char src[] = {1, 2, 3, 4};
   char dst[4] = {0};
@@ -315,7 +318,7 @@
 
   p1 = (&s2) + 1;
   p2 = mempcpy(&s2, &s1, sizeof(struct st));
-
+  
   clang_analyzer_eval(p1 == p2); // expected-warning{{TRUE}}
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -80,7 +80,7 @@
  check::RegionChanges
  > {
   mutable std::unique_ptr BT_Null, BT_Bounds, BT_Overla

[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

The `core` checkers should be always enabled.




Comment at: clang/test/Analysis/bstring_UninitRead.c:2
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN: -analyzer-checker=alpha.unix.cstring 
+




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets updated this revision to Diff 412464.
phyBrackets added a comment.

enabled the core checker


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
  clang/test/Analysis/bstring.c
  clang/test/Analysis/bstring_UninitRead.c

Index: clang/test/Analysis/bstring_UninitRead.c
===
--- /dev/null
+++ clang/test/Analysis/bstring_UninitRead.c
@@ -0,0 +1,59 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN: -analyzer-checker=core,alpha.unix.cstring
+
+
+// This file is generally for the alpha.unix.cstring.UninitializedRead Checker, the reason for putting it into
+// the separate file because the checker is break the some existing test cases in bstring.c file , so we don't 
+// wanna mess up with some existing test case so it's better to create separate file for it, this file also include 
+// the broken test for the reference in future about the broken tests.
+
+
+typedef typeof(sizeof(int)) size_t;
+
+void clang_analyzer_eval(int);
+
+void *memcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+void top(char *dst) {
+  char buf[10];
+  memcpy(dst, buf, 10); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  (void)buf;
+}
+
+//===--===
+// mempcpy()
+//===--===
+
+void *mempcpy(void *restrict s1, const void *restrict s2, size_t n);
+
+void mempcpy14() {
+  int src[] = {1, 2, 3, 4};
+  int dst[5] = {0};
+  int *p;
+
+  p = mempcpy(dst, src, 4 * sizeof(int)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+   // FIXME: This behaviour is actually surprising and needs to be fixed, 
+   // mempcpy seems to consider the very last byte of the src buffer uninitialized
+   // and returning undef unfortunately. It should have returned unknown or a conjured value instead.
+
+  clang_analyzer_eval(p == &dst[4]); // no-warning (above is fatal)
+}
+
+struct st {
+  int i;
+  int j;
+};
+
+
+void mempcpy15() {
+  struct st s1 = {0};
+  struct st s2;
+  struct st *p1;
+  struct st *p2;
+
+  p1 = (&s2) + 1;
+  p2 = mempcpy(&s2, &s1, sizeof(struct st)); // expected-warning{{Bytes string function accesses uninitialized/garbage values}}
+  // FIXME: It seems same as mempcpy14() case.
+  
+  clang_analyzer_eval(p1 == p2); // no-warning (above is fatal)
+}
Index: clang/test/Analysis/bstring.c
===
--- clang/test/Analysis/bstring.c
+++ clang/test/Analysis/bstring.c
@@ -2,13 +2,15 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
-// RUN:   -analyzer-config eagerly-assume=false
+// RUN:   -analyzer-config eagerly-assume=false  
 //
 // RUN: %clang_analyze_cc1 -verify %s -DUSE_BUILTINS \
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 //
@@ -16,6 +18,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 //
@@ -23,6 +26,7 @@
 // RUN:   -analyzer-checker=core \
 // RUN:   -analyzer-checker=unix.cstring \
 // RUN:   -analyzer-checker=alpha.unix.cstring \
+// RUN:   -analyzer-disable-checker=alpha.unix.cstring.UninitializedRead \
 // RUN:   -analyzer-checker=debug.ExprInspection \
 // RUN:   -analyzer-config eagerly-assume=false
 
@@ -70,7 +74,6 @@
 
 #endif /* VARIANT */
 
-
 void memcpy0 () {
   char src[] = {1, 2, 3, 4};
   char dst[4] = {0};
@@ -315,7 +318,7 @@
 
   p1 = (&s2) + 1;
   p2 = mempcpy(&s2, &s1, sizeof(struct st));
-
+  
   clang_analyzer_eval(p1 == p2); // expected-warning{{TRUE}}
 }
 
Index: clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp
@@ -80,7 +80,7 @@
  check::RegionChanges
  > {
   mutable std::unique_ptr BT_Null, BT_Bounds, BT_Overlap,
-  BT_NotCStrin

[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added inline comments.



Comment at: clang/test/Analysis/bstring_UninitRead.c:2
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN: -analyzer-checker=alpha.unix.cstring 
+

steakhal wrote:
> 
Yeah done! Thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[clang] 3f7c3ff - [OpenMP] Handle sysroot option in offloading linker wrapper

2022-03-02 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-03-02T13:02:41-05:00
New Revision: 3f7c3ff90e33393b7b8a0851f6056ec1d9c164af

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

LOG: [OpenMP] Handle sysroot option in offloading linker wrapper

Summary:
This patch correctly handles the `--sysroot=` option when passed to the
linker wrapper. This allows users to correctly find libraries that may
contain offloading code if using this option.

Added: 


Modified: 
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Removed: 




diff  --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index d183c8b09c997..5807181426459 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -133,6 +133,9 @@ static const char *LinkerExecutable;
 /// Filename of the executable being created.
 static StringRef ExecutableName;
 
+/// System root if passed in to the linker via. '--sysroot='.
+static StringRef Sysroot = "";
+
 /// Binary path for the CUDA installation.
 static std::string CudaBinaryPath;
 
@@ -169,8 +172,8 @@ void printCommands(ArrayRef CmdArgs) {
 return;
 
   llvm::errs() << " \"" << CmdArgs.front() << "\" ";
-  for (auto IC = CmdArgs.begin() + 1, IE = CmdArgs.end(); IC != IE; ++IC)
-llvm::errs() << *IC << (IC + 1 != IE ? " " : "\n");
+  for (auto IC = std::next(CmdArgs.begin()), IE = CmdArgs.end(); IC != IE; 
++IC)
+llvm::errs() << *IC << (std::next(IC) != IE ? " " : "\n");
 }
 
 static StringRef getDeviceFileExtension(StringRef DeviceTriple,
@@ -726,10 +729,10 @@ Expected link(ArrayRef 
InputFiles, Triple TheTriple,
   CmdArgs.push_back(Arg);
 else if (Arg.startswith("-rpath")) {
   CmdArgs.push_back(Arg);
-  CmdArgs.push_back(*(AI + 1));
+  CmdArgs.push_back(*std::next(AI));
 } else if (Arg.startswith("-dynamic-linker")) {
   CmdArgs.push_back(Arg);
-  CmdArgs.push_back(*(AI + 1));
+  CmdArgs.push_back(*std::next(AI));
 }
   }
   CmdArgs.push_back("-Bsymbolic");
@@ -1157,8 +1160,11 @@ Expected 
wrapDeviceImages(ArrayRef Images) {
 
 Optional findFile(StringRef Dir, const Twine &Name) {
   SmallString<128> Path;
-  // TODO: Parse `--sysroot` somewhere and use it here.
-  sys::path::append(Path, Dir, Name);
+  if (Dir.startswith("="))
+sys::path::append(Path, Sysroot, Dir.substr(1), Name);
+  else
+sys::path::append(Path, Dir, Name);
+
   if (sys::fs::exists(Path))
 return static_cast(Path);
   return None;
@@ -1229,7 +1235,13 @@ int main(int argc, const char **argv) {
   if (!CudaPath.empty())
 CudaBinaryPath = CudaPath + "/bin";
 
-  ExecutableName = *(llvm::find(HostLinkerArgs, "-o") + 1);
+  auto RootIt = llvm::find_if(HostLinkerArgs, [](StringRef Arg) {
+return Arg.startswith("--sysroot=");
+  });
+  if (RootIt != HostLinkerArgs.end())
+Sysroot = StringRef(*RootIt).split('=').second;
+
+  ExecutableName = *std::next(llvm::find(HostLinkerArgs, "-o"));
   SmallVector LinkerArgs;
   for (const std::string &Arg : HostLinkerArgs)
 LinkerArgs.push_back(Arg);



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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added a comment.

@steakhal , if everything looks fine, can i land this ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D120489: [analyzer] Done some changes to detect Uninitialized read by the char array manipulation functions

2022-03-02 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Yup, land it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120489

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


[PATCH] D118350: [Clang][Sema][AIX][PowerPC] Emit byval alignment warning only when struct is passed to a function

2022-03-02 Thread Sean Fertile via Phabricator via cfe-commits
sfertile added inline comments.
Herald added a project: All.



Comment at: clang/lib/Sema/SemaChecking.cpp:5246
+
+  if (const auto *ICE = dyn_cast(Arg->IgnoreParens())) {
+if (const auto *DR = dyn_cast(ICE->getSubExpr())) {

Nit: To avoid the deep nesting, can we instead have a series of casts, and if 
the resulting pointer is null we return early?



Comment at: clang/test/Sema/aix-attr-align.c:10
+  int a[8] __attribute__((aligned(8)));  // no-warning
+  int b[8] __attribute__((aligned(16))); // expected-warning {{alignment of 16 
bytes for a struct member is not binary compatible with IBM XL C/C++ for AIX 
16.1.0 or older}}
 };

As far as I am aware, the layout of a 16-byte aligned member is exactly the 
same between the all the compilers on AIX, and the only incompatibility is when 
passing them byval. If that's true then warning on the declaration here is much 
too verbose, as most uses will be fine and warning on the callsite (and later 
on the function definition) calls attention to it only when there is indeed the 
possibility of an incompatability.



Comment at: clang/test/Sema/aix-attr-align.c:31
+
+  baz(p1, p2, s.b, p3, b, p5, s);// expected-note {{'b' used with 
potentially incompatible alignment here}}
+  jaz(p1, p2, a, p3, s.a, p5, t);// no-note

I get the following diagnostic from the compiler now:
```
baz(p1, p2, s.b, p3, b, p5, s);// expected-note {{'b' used with 
potentially incompatible alignment here}}
^
```
I can't seem to get the formatting exact, but the caret is pointing to 's' 
which is the correct argument to warn on, but the note uses the name 'b'.  
Before adjusting the warning using the member name made sense, but I think now 
that we are warning on the byval argument, we should be using `s`, and also 
reword the note to something like 
`passing byval argument 's'  which is 16 byte aligned may be incompatible with 
IBM XL C/C++ for AIX 16.1.0 or older`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118350

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


[PATCH] D93298: [RISCV] add the MC layer support of Zfinx extension

2022-03-02 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D93298#3354313 , @krasimir wrote:

> @achieveartificialintelligence thank you for looking into this, sorry for the 
> late reply!
>
> It looks like the latest version addresses @nikic's IR reproducer with 
> `-mtriple=riscv32`.
>
> There seems to be an error trying this out with `-mtriple=riscv64`:
>
>   % cat test.ll
>   define float @test(float %x) {
> %1 = tail call float asm sideeffect alignstack "mv a0, a0", 
> "={x10},{x10}"(float 0.00e+00)
> ret float 0.00e+00
>   }
>   % llc -mtriple=riscv32 -mattr=+d test.ll
>   % llc -mtriple=riscv64 -mattr=+d test.ll
>   error: couldn't allocate output register for constraint '{x10}'
>
> I'm not sure if this is intended to work `-mtriple=riscv64`, but judging by 
> the newly added test `RUN: llc -mtriple=riscv64 ...` line it seems like it 
> should?

My patch was only partially correct. I'll fix it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

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


[PATCH] D120596: [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/lib/CodeGen/CGStmt.cpp:2517
+else if (OutputTy->isFloatingPointTy())
   Arg = Builder.CreateFPExt(Arg, OutputTy);
   }

Shall we keep the assert (in a new `else` branch) just in case there are other 
cases which cannot be handled?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120596

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


[PATCH] D120596: [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 Thread Tong Zhang via Phabricator via cfe-commits
ztong0001 added inline comments.



Comment at: clang/lib/CodeGen/CGStmt.cpp:2517
+else if (OutputTy->isFloatingPointTy())
   Arg = Builder.CreateFPExt(Arg, OutputTy);
   }

MaskRay wrote:
> Shall we keep the assert (in a new `else` branch) just in case there are 
> other cases which cannot be handled?
IMO adding assert() in else branch still has the same issue with the inline asm 
in description.

This portion of the code is to extend argument to a longer type, if it cannot 
do so the patch will simply skip and let it fall back to old behavior and print 
out 

`impossible constraint in asm: can't store value into a register`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120596

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


[PATCH] D96109: Refactor implementation of -funique-internal-linkage-names.

2022-03-02 Thread Ellis Hoag via Phabricator via cfe-commits
ellis added a comment.
Herald added a subscriber: ormris.
Herald added a project: All.

Hi @tmsriram. I found a clang crash when using the flag 
`-funique-internal-linkage-names` that only happens after this diff. Would you 
mind taking a look?

  $ cat test.c
  inline void foo() {}
  extern void foo();
  $ clang -funique-internal-linkage-names test.c -c

More details are in this bug report 
https://github.com/llvm/llvm-project/issues/54139


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96109

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


[PATCH] D120596: [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 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.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120596

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


[PATCH] D120596: [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 Thread Tong Zhang via Phabricator via cfe-commits
ztong0001 added a comment.

Hi Fangrui @MaskRay,
Thanks for your review. Could you please also help me landing it since I don't 
have write permission to the repo.
Please use Tong Zhang
Thanks and have a good one!

- Tong


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120596

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


[clang] f76d3b8 - [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 Thread Fangrui Song via cfe-commits

Author: Tong Zhang
Date: 2022-03-02T11:18:55-08:00
New Revision: f76d3b800f7341882ea93db47cc8f28d94e74f1c

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

LOG: [clang][CGStmt] fix crash on invalid asm statement

Clang is crashing on the following statement

  char var[9];
  __asm__ ("" : "=r" (var) : "0" (var));

This is similar to existing test: crbug_999160_regtest

The issue happens when EmitAsmStmt is trying to convert input to match
output type length. However, that is not guaranteed to be successful all the
time and if the statement itself is invalid like having an array type in
the example, we should give a regular error message here instead of
using assert().

Reviewed By: MaskRay

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

Added: 


Modified: 
clang/lib/CodeGen/CGStmt.cpp
clang/test/CodeGen/X86/x86_64-PR42672.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 011909a5834b8..01ccc71463069 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -2518,10 +2518,8 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
   Arg = Builder.CreateZExt(Arg, OutputTy);
 else if (isa(OutputTy))
   Arg = Builder.CreateZExt(Arg, IntPtrTy);
-else {
-  assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
+else if (OutputTy->isFloatingPointTy())
   Arg = Builder.CreateFPExt(Arg, OutputTy);
-}
   }
   // Deal with the tied operands' constraint code in adjustInlineAsmType.
   ReplaceConstraint = OutputConstraints[Output];

diff  --git a/clang/test/CodeGen/X86/x86_64-PR42672.c 
b/clang/test/CodeGen/X86/x86_64-PR42672.c
index 2e8ec15b58525..6eea20a1e3f63 100644
--- a/clang/test/CodeGen/X86/x86_64-PR42672.c
+++ b/clang/test/CodeGen/X86/x86_64-PR42672.c
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -DPOSSIBLE_X -emit-llvm %s 
-o - 2>&1 | FileCheck %s --check-prefix=CHECK-X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_X 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES
+// RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES_V2 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES_V2
 
 // Make sure Clang doesn't treat |lockval| as asm input.
 void _raw_spin_lock(void) {
@@ -115,3 +116,11 @@ void crbug_999160_regtest(void) {
 }
 
 // CHECK-IMPOSSIBLE_9BYTES: impossible constraint in asm: can't store value 
into a register
+
+void crbug_999160_regtest_v2(void) {
+#ifdef IMPOSSIBLE_9BYTES_V2
+  char buf[9];
+  asm("" : "=r"(buf) : "0"(buf));
+#endif
+}
+// CHECK-IMPOSSIBLE_9BYTES_V2: impossible constraint in asm: can't store value 
into a register



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


[PATCH] D120596: [clang][CGStmt] fix crash on invalid asm statement

2022-03-02 Thread Fangrui Song 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 rGf76d3b800f73: [clang][CGStmt] fix crash on invalid asm 
statement (authored by ztong0001, committed by MaskRay).

Changed prior to commit:
  https://reviews.llvm.org/D120596?vs=411577&id=412496#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120596

Files:
  clang/lib/CodeGen/CGStmt.cpp
  clang/test/CodeGen/X86/x86_64-PR42672.c


Index: clang/test/CodeGen/X86/x86_64-PR42672.c
===
--- clang/test/CodeGen/X86/x86_64-PR42672.c
+++ clang/test/CodeGen/X86/x86_64-PR42672.c
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -DPOSSIBLE_X -emit-llvm %s 
-o - 2>&1 | FileCheck %s --check-prefix=CHECK-X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_X 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES
+// RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES_V2 
-emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES_V2
 
 // Make sure Clang doesn't treat |lockval| as asm input.
 void _raw_spin_lock(void) {
@@ -115,3 +116,11 @@
 }
 
 // CHECK-IMPOSSIBLE_9BYTES: impossible constraint in asm: can't store value 
into a register
+
+void crbug_999160_regtest_v2(void) {
+#ifdef IMPOSSIBLE_9BYTES_V2
+  char buf[9];
+  asm("" : "=r"(buf) : "0"(buf));
+#endif
+}
+// CHECK-IMPOSSIBLE_9BYTES_V2: impossible constraint in asm: can't store value 
into a register
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2518,10 +2518,8 @@
   Arg = Builder.CreateZExt(Arg, OutputTy);
 else if (isa(OutputTy))
   Arg = Builder.CreateZExt(Arg, IntPtrTy);
-else {
-  assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
+else if (OutputTy->isFloatingPointTy())
   Arg = Builder.CreateFPExt(Arg, OutputTy);
-}
   }
   // Deal with the tied operands' constraint code in adjustInlineAsmType.
   ReplaceConstraint = OutputConstraints[Output];


Index: clang/test/CodeGen/X86/x86_64-PR42672.c
===
--- clang/test/CodeGen/X86/x86_64-PR42672.c
+++ clang/test/CodeGen/X86/x86_64-PR42672.c
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 -triple=x86_64-unknown-linux-gnu -DPOSSIBLE_X -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_X -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_X
 // RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES
+// RUN: not %clang_cc1 -triple=x86_64-unknown-linux-gnu -DIMPOSSIBLE_9BYTES_V2 -emit-llvm %s -o - 2>&1 | FileCheck %s --check-prefix=CHECK-IMPOSSIBLE_9BYTES_V2
 
 // Make sure Clang doesn't treat |lockval| as asm input.
 void _raw_spin_lock(void) {
@@ -115,3 +116,11 @@
 }
 
 // CHECK-IMPOSSIBLE_9BYTES: impossible constraint in asm: can't store value into a register
+
+void crbug_999160_regtest_v2(void) {
+#ifdef IMPOSSIBLE_9BYTES_V2
+  char buf[9];
+  asm("" : "=r"(buf) : "0"(buf));
+#endif
+}
+// CHECK-IMPOSSIBLE_9BYTES_V2: impossible constraint in asm: can't store value into a register
Index: clang/lib/CodeGen/CGStmt.cpp
===
--- clang/lib/CodeGen/CGStmt.cpp
+++ clang/lib/CodeGen/CGStmt.cpp
@@ -2518,10 +2518,8 @@
   Arg = Builder.CreateZExt(Arg, OutputTy);
 else if (isa(OutputTy))
   Arg = Builder.CreateZExt(Arg, IntPtrTy);
-else {
-  assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
+else if (OutputTy->isFloatingPointTy())
   Arg = Builder.CreateFPExt(Arg, OutputTy);
-}
   }
   // Deal with the tied operands' constraint code in adjustInlineAsmType.
   ReplaceConstraint = OutputConstraints[Output];
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D96109: Refactor implementation of -funique-internal-linkage-names.

2022-03-02 Thread Sriraman Tallam via cfe-commits
On Wed, Mar 2, 2022 at 11:08 AM Ellis Hoag via Phabricator <
revi...@reviews.llvm.org> wrote:

> ellis added a comment.
> Herald added a subscriber: ormris.
> Herald added a project: All.
>
> Hi @tmsriram. I found a clang crash when using the flag
> `-funique-internal-linkage-names` that only happens after this diff. Would
> you mind taking a look?
>
>   $ cat test.c
>   inline void foo() {}
>   extern void foo();
>   $ clang -funique-internal-linkage-names test.c -c
>

Sure, will take a look.  The first foo here is internal linkage and must be
mangled, not the second.


>
> More details are in this bug report
> https://github.com/llvm/llvm-project/issues/54139
>
>
> Repository:
>   rG LLVM Github Monorepo
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D96109/new/
>
> https://reviews.llvm.org/D96109
>
>

-- 

SriTallam |

Software Engineer |

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


[PATCH] D93298: [RISCV] add the MC layer support of Zfinx extension

2022-03-02 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D93298#3355088 , @craig.topper 
wrote:

> In D93298#3354313 , @krasimir wrote:
>
>> @achieveartificialintelligence thank you for looking into this, sorry for 
>> the late reply!
>>
>> It looks like the latest version addresses @nikic's IR reproducer with 
>> `-mtriple=riscv32`.
>>
>> There seems to be an error trying this out with `-mtriple=riscv64`:
>>
>>   % cat test.ll
>>   define float @test(float %x) {
>> %1 = tail call float asm sideeffect alignstack "mv a0, a0", 
>> "={x10},{x10}"(float 0.00e+00)
>> ret float 0.00e+00
>>   }
>>   % llc -mtriple=riscv32 -mattr=+d test.ll
>>   % llc -mtriple=riscv64 -mattr=+d test.ll
>>   error: couldn't allocate output register for constraint '{x10}'
>>
>> I'm not sure if this is intended to work `-mtriple=riscv64`, but judging by 
>> the newly added test `RUN: llc -mtriple=riscv64 ...` line it seems like it 
>> should?
>
> My patch was only partially correct. I'll fix it

I just pushed 6cb42cd6669785f3b611106e1b6b38bbe65733a9 
 to 
hopefully fix this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

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


[PATCH] D120398: [format] follow up: Use unsigned char as the base of all enums in FormatStyle

2022-03-02 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D120398#3353053 , @owenpan wrote:

> Can we use `int8_t` instead of `unsigned char` to keep the enum types signed 
> (and update the changes made in D93758 )?

+1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120398

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


[PATCH] D93298: [RISCV] add the MC layer support of Zfinx extension

2022-03-02 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Does a double with `r` for RV32 work with that fix? That's supposed to give the 
low half of the register. You might need to also deal with the register pair 
class?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

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


[PATCH] D93298: [RISCV] add the MC layer support of Zfinx extension

2022-03-02 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Never mind, I see you added a test for that case


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93298

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


[PATCH] D117887: [NVPTX] Expose float tys min, max, abs, neg as builtins

2022-03-02 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D117887#3353653 , @jchlanda wrote:

> I went with the web interface as described here: 
> https://llvm.org/docs/Phabricator.html#requesting-a-review-via-the-web-interface
>  
> with `git diff -U99 ...` didn't want to bite the bullet of `arc`, hoping 
> that github PRs will soon be a thing.

`git show -U9` should work even better as it would include author info and 
commit log message, so one would not need to re-enter it manually when 
importing the patch from phabricator.

In any case that's probably not the root cause of my error, just a minor 
inconvenience. 
I still have no idea what went wrong during my initial commit, but I think I've 
learned the lesson and will start double checking the imported changes for 
completeness.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117887

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


[PATCH] D120255: [Concepts] Check constraints for explicit template instantiations

2022-03-02 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added inline comments.



Comment at: clang/test/SemaTemplate/constraints-instantiation.cpp:3-8
+// void PR46029::A<1>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi1EE1fEv
+// void PR46029::A<2>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi2EE1fEv
+// void PR46029::A<3>::f()
+// CHECK-NOT: define {{.*}} @_ZN7PR460291AILi3EE1fEv

aaron.ballman wrote:
> I think it might be better to test this via an `-ast-dump` test (which lives 
> in the `AST` test directory) rather than emitting LLVM IR to determine 
> whether something was instantiated or not.
> 
> Btw, when you convert the test to use `-ast-dump`, be sure to make use of 
> regexes for things like line, column numbers, pointer values, etc so that the 
> test is easier to edit without breaking.
I tried to look now into doing it in the ast-dump. It seems that we create a 
new `ClassTemplateSpecializationDecl` in SemaTemplate:9663 
(`ActOnExplicitInstantiation`) that is copied from the parent 
`ClassTemplateDecl` along with all its members and `CXXMethodDecl`s. That means 
that the member functions with the unsatisfied constraints still appear in the 
AST.

Do you think I should add the constraints checks into the creation of 
`ClassTemplateSpecializationDecl` instead, so we don't create unnecessary 
`CXXMethodDecl`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120255

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


[PATCH] D120255: [Concepts] Check constraints for explicit template instantiations

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/test/SemaTemplate/constraints-instantiation.cpp:3-8
+// void PR46029::A<1>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi1EE1fEv
+// void PR46029::A<2>::f()
+// CHECK: define {{.*}} @_ZN7PR460291AILi2EE1fEv
+// void PR46029::A<3>::f()
+// CHECK-NOT: define {{.*}} @_ZN7PR460291AILi3EE1fEv

royjacobson wrote:
> aaron.ballman wrote:
> > I think it might be better to test this via an `-ast-dump` test (which 
> > lives in the `AST` test directory) rather than emitting LLVM IR to 
> > determine whether something was instantiated or not.
> > 
> > Btw, when you convert the test to use `-ast-dump`, be sure to make use of 
> > regexes for things like line, column numbers, pointer values, etc so that 
> > the test is easier to edit without breaking.
> I tried to look now into doing it in the ast-dump. It seems that we create a 
> new `ClassTemplateSpecializationDecl` in SemaTemplate:9663 
> (`ActOnExplicitInstantiation`) that is copied from the parent 
> `ClassTemplateDecl` along with all its members and `CXXMethodDecl`s. That 
> means that the member functions with the unsatisfied constraints still appear 
> in the AST.
> 
> Do you think I should add the constraints checks into the creation of 
> `ClassTemplateSpecializationDecl` instead, so we don't create unnecessary 
> `CXXMethodDecl`?
So one of the problems with that is the delayed-concepts thing I'm working on.  
The idea is that we shouldn't be instantiating or checking until the last 
moment, so unless I am misunderstanding what you mean, I would think not. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120255

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 412502.
aaron.ballman marked 3 inline comments as done.
aaron.ballman added a comment.

Address review comments.


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

https://reviews.llvm.org/D120770

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/bitint-suffix.c
  clang/test/Lexer/bitint-constants-compat.c
  clang/test/Lexer/bitint-constants.c
  llvm/include/llvm/ADT/APInt.h
  llvm/lib/Support/APInt.cpp

Index: llvm/lib/Support/APInt.cpp
===
--- llvm/lib/Support/APInt.cpp
+++ llvm/lib/Support/APInt.cpp
@@ -502,12 +502,51 @@
   return retBits;
 }
 
+unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
+  assert(!Str.empty() && "Invalid string length");
+  size_t StrLen = Str.size();
+
+  // Each computation below needs to know if it's negative.
+  unsigned IsNegative = false;
+  if (Str[0] == '-' || Str[0] == '+') {
+IsNegative = Str[0] == '-';
+StrLen--;
+assert(StrLen && "String is only a sign, needs a value.");
+  }
+
+  // For radixes of power-of-two values, the bits required is accurately and
+  // easily computed.
+  if (Radix == 2)
+return StrLen + IsNegative;
+  if (Radix == 8)
+return StrLen * 3 + IsNegative;
+  if (Radix == 16)
+return StrLen * 4 + IsNegative;
+
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large. This avoids the assertion in the constructor. This
+  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
+  // bits in that case.
+  if (Radix == 10)
+return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
+
+  assert(Radix == 36);
+  return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
+}
+
 unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
-  assert(!str.empty() && "Invalid string length");
-  assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
-  radix == 36) &&
- "Radix should be 2, 8, 10, 16, or 36!");
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large.
+  unsigned sufficient = getSufficientBitsNeeded(str, radix);
+
+  // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
+  // return the value directly. For bases 10 and 36, we need to do extra work.
+  if (radix == 2 || radix == 8 || radix == 16)
+return sufficient;
 
+  // This is grossly inefficient but accurate. We could probably do something
+  // with a computation of roughly slen*64/20 and then adjust by the value of
+  // the first few digits. But, I'm not sure how accurate that could be.
   size_t slen = str.size();
 
   // Each computation below needs to know if it's negative.
@@ -519,28 +558,6 @@
 assert(slen && "String is only a sign, needs a value.");
   }
 
-  // For radixes of power-of-two values, the bits required is accurately and
-  // easily computed
-  if (radix == 2)
-return slen + isNegative;
-  if (radix == 8)
-return slen * 3 + isNegative;
-  if (radix == 16)
-return slen * 4 + isNegative;
-
-  // FIXME: base 36
-
-  // This is grossly inefficient but accurate. We could probably do something
-  // with a computation of roughly slen*64/20 and then adjust by the value of
-  // the first few digits. But, I'm not sure how accurate that could be.
-
-  // Compute a sufficient number of bits that is always large enough but might
-  // be too large. This avoids the assertion in the constructor. This
-  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
-  // bits in that case.
-  unsigned sufficient
-= radix == 10? (slen == 1 ? 4 : slen * 64/18)
- : (slen == 1 ? 7 : slen * 16/3);
 
   // Convert to the actual binary value.
   APInt tmp(sufficient, StringRef(p, slen), radix);
Index: llvm/include/llvm/ADT/APInt.h
===
--- llvm/include/llvm/ADT/APInt.h
+++ llvm/include/llvm/ADT/APInt.h
@@ -1506,6 +1506,11 @@
   /// equivalent of the string given by \p str.
   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
 
+  /// Get the bits that are sufficient to represent the string value. This may
+  /// over estimate the amount of bits required, but it does not require
+  /// parsing the value in the string.
+  static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
+
   /// The APInt version of the countLeadingZeros functions in
   ///   MathExtras.h.
   ///
Index: clang/test/Lexer/bitint-constants.c
===
--- /dev/null
+++ clang/test/Lexer/bitint-constants.c
@@ -0,0 +1,144 @@
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify 

[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Lex/LiteralSupport.h:65
   bool isLong : 1;  // This is *not* set for long long.
   bool isLongLong : 1;
   bool isSizeT : 1; // 1z, 1uz (C++2b)

erichkeane wrote:
> I can't help but wonder if there are some really good opportunities to merge 
> a bunch of these mutually exclusive ones into an enum...
> ```
> enum class SizeType {
> Long,
> LongLong,
> SizeT,
> Float,
> Imaginary,
> Float16,
> Flaot128,
> Fract,
> Accum,
> BitInt
> ```
> 
> Or something?
That seems plausible, but perhaps as a follow-up. We're going from 12 bits to 
13 with this patch (and correctly a layout issue as a drive-by), so we're not 
at or near an allocation unit boundary.



Comment at: clang/lib/AST/StmtPrinter.cpp:1157
+  if (const auto *BT = Node->getType()->getAs()) {
+OS << (BT->isUnsigned() ? "uwb" : "wb");
+return;

erichkeane wrote:
> Nit: Instead of BT->isUnsigned(), we already have isSigned above.
Good call!



Comment at: clang/lib/Lex/LiteralSupport.cpp:903
+break; // Invalid for floats.
+  if (HasSize)
+break; // Invalid if we already have a size for the literal.

erichkeane wrote:
> Do we also have to reject isImaginary/isFract/etc separately?
I'm not super familiar with fixed-point literals, but at least with imaginary, 
you can make a _Complex from any integer type, including _BitInt, so I don't 
think there's a reason to reject that case.



Comment at: clang/lib/Sema/SemaExpr.cpp:3987
+  << Literal.isUnsigned;
+  Width = MaxBitIntWidth;
+}

erichkeane wrote:
> Do you have some AST test here to see what happens to the value when the 
> width is exceeded?
Not an AST test -- can't get one of those because this emits an error. But we 
do have a semantic test, see bitint-constants.c lines 135-136.



Comment at: clang/lib/Sema/SemaExpr.cpp:3995
+ResultVal = ResultVal.zextOrTrunc(Width);
+Ty = Context.getBitIntType(Literal.isUnsigned, Width);
+  }

erichkeane wrote:
> I think it is already covered, but do we make sure the literal itself and the 
> suffix match?  That is: -111uwb is invalid?
We do not, but that's consistent with other suffix confusion: 
https://godbolt.org/z/rExPGdex3

(Remember, the `-` isn't part of the literal, that's a unary negation operator 
applied to the positive literal.)



Comment at: clang/test/AST/bitint-suffix.c:20
+  // CHECK: TypedefDecl 0x{{[^ ]*}}  col:28 zero_uwb 'typeof 
(0uwb)':'unsigned _BitInt(1)'
+  typedef __typeof__(0uwb) zero_uwb;
+  // CHECK: TypedefDecl 0x{{[^ ]*}}  col:29 neg_zero_uwb 
'typeof (-0uwb)':'unsigned _BitInt(1)'

erichkeane wrote:
> I think by my reading, wbu is valid as well, right?  Can we have 1 test for 
> that?
We have one -- bitint-constant.c lines 89-92.



Comment at: clang/test/Lexer/bitint-constants.c:133
+  // the width of BITINT_MAXWIDTH.
+  _Static_assert(__BITINT_MAXWIDTH__ <= 128,
+"Need to pick a bigger constant for the test case below.");

erichkeane wrote:
> <3
> 
> I'd also like a 'TODO' here when this happens that we have something to make 
> sure that a 129bit/etc literal 'works' as expected. 
Added a comment.


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

https://reviews.llvm.org/D120770

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


[PATCH] D120774: [clang-format] Handle builtins in constraint expression

2022-03-02 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:23747
+  verifyFormat("template \n"
+   "concept integral = __is_integral(T);");
+

curdeius wrote:
> curdeius wrote:
> > How about other kinds?
> > This doesn't seem to work for at least ARRAY_TYPE_TRAIT (e.g. `concept 
> > OneDimensionalArray = __array_rank(T) == 1;`  and EXPRESSION_TRAIT.
> > 
> > Is there a way to be more generic and treat all identifier-like entities 
> > like identifiers?
> I'd like to see a test for ALIASes as well, e.g. `__is_same_as`.
> How about other kinds?
> This doesn't seem to work for at least ARRAY_TYPE_TRAIT (e.g. `concept 
> OneDimensionalArray = __array_rank(T) == 1;`  and EXPRESSION_TRAIT.

I was conservative, since I don't know what these kind of traits are. But sure 
can add.

> Is there a way to be more generic and treat all identifier-like entities like 
> identifiers?
Not that I know of. There is no such function in `TokenKind.h`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120774

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/Lex/LiteralSupport.h:65
   bool isLong : 1;  // This is *not* set for long long.
   bool isLongLong : 1;
   bool isSizeT : 1; // 1z, 1uz (C++2b)

aaron.ballman wrote:
> erichkeane wrote:
> > I can't help but wonder if there are some really good opportunities to 
> > merge a bunch of these mutually exclusive ones into an enum...
> > ```
> > enum class SizeType {
> > Long,
> > LongLong,
> > SizeT,
> > Float,
> > Imaginary,
> > Float16,
> > Flaot128,
> > Fract,
> > Accum,
> > BitInt
> > ```
> > 
> > Or something?
> That seems plausible, but perhaps as a follow-up. We're going from 12 bits to 
> 13 with this patch (and correctly a layout issue as a drive-by), so we're not 
> at or near an allocation unit boundary.
SGTM.



Comment at: clang/lib/AST/StmtPrinter.cpp:1157
+  if (const auto *BT = Node->getType()->getAs()) {
+OS << (BT->isUnsigned() ? "uwb" : "wb");
+return;

aaron.ballman wrote:
> erichkeane wrote:
> > Nit: Instead of BT->isUnsigned(), we already have isSigned above.
> Good call!
Isn't this reversed now?



Comment at: clang/lib/Sema/SemaExpr.cpp:3995
+ResultVal = ResultVal.zextOrTrunc(Width);
+Ty = Context.getBitIntType(Literal.isUnsigned, Width);
+  }

aaron.ballman wrote:
> erichkeane wrote:
> > I think it is already covered, but do we make sure the literal itself and 
> > the suffix match?  That is: -111uwb is invalid?
> We do not, but that's consistent with other suffix confusion: 
> https://godbolt.org/z/rExPGdex3
> 
> (Remember, the `-` isn't part of the literal, that's a unary negation 
> operator applied to the positive literal.)
Oh! TIL!


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

https://reviews.llvm.org/D120770

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 412507.
aaron.ballman added a comment.

Correct a think-o that fixes a failing test. Also removed a newline that didn't 
need to exist.


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

https://reviews.llvm.org/D120770

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/bitint-suffix.c
  clang/test/Lexer/bitint-constants-compat.c
  clang/test/Lexer/bitint-constants.c
  llvm/include/llvm/ADT/APInt.h
  llvm/lib/Support/APInt.cpp

Index: llvm/lib/Support/APInt.cpp
===
--- llvm/lib/Support/APInt.cpp
+++ llvm/lib/Support/APInt.cpp
@@ -502,12 +502,51 @@
   return retBits;
 }
 
+unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
+  assert(!Str.empty() && "Invalid string length");
+  size_t StrLen = Str.size();
+
+  // Each computation below needs to know if it's negative.
+  unsigned IsNegative = false;
+  if (Str[0] == '-' || Str[0] == '+') {
+IsNegative = Str[0] == '-';
+StrLen--;
+assert(StrLen && "String is only a sign, needs a value.");
+  }
+
+  // For radixes of power-of-two values, the bits required is accurately and
+  // easily computed.
+  if (Radix == 2)
+return StrLen + IsNegative;
+  if (Radix == 8)
+return StrLen * 3 + IsNegative;
+  if (Radix == 16)
+return StrLen * 4 + IsNegative;
+
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large. This avoids the assertion in the constructor. This
+  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
+  // bits in that case.
+  if (Radix == 10)
+return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
+
+  assert(Radix == 36);
+  return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
+}
+
 unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
-  assert(!str.empty() && "Invalid string length");
-  assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
-  radix == 36) &&
- "Radix should be 2, 8, 10, 16, or 36!");
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large.
+  unsigned sufficient = getSufficientBitsNeeded(str, radix);
+
+  // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
+  // return the value directly. For bases 10 and 36, we need to do extra work.
+  if (radix == 2 || radix == 8 || radix == 16)
+return sufficient;
 
+  // This is grossly inefficient but accurate. We could probably do something
+  // with a computation of roughly slen*64/20 and then adjust by the value of
+  // the first few digits. But, I'm not sure how accurate that could be.
   size_t slen = str.size();
 
   // Each computation below needs to know if it's negative.
@@ -519,28 +558,6 @@
 assert(slen && "String is only a sign, needs a value.");
   }
 
-  // For radixes of power-of-two values, the bits required is accurately and
-  // easily computed
-  if (radix == 2)
-return slen + isNegative;
-  if (radix == 8)
-return slen * 3 + isNegative;
-  if (radix == 16)
-return slen * 4 + isNegative;
-
-  // FIXME: base 36
-
-  // This is grossly inefficient but accurate. We could probably do something
-  // with a computation of roughly slen*64/20 and then adjust by the value of
-  // the first few digits. But, I'm not sure how accurate that could be.
-
-  // Compute a sufficient number of bits that is always large enough but might
-  // be too large. This avoids the assertion in the constructor. This
-  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
-  // bits in that case.
-  unsigned sufficient
-= radix == 10? (slen == 1 ? 4 : slen * 64/18)
- : (slen == 1 ? 7 : slen * 16/3);
 
   // Convert to the actual binary value.
   APInt tmp(sufficient, StringRef(p, slen), radix);
Index: llvm/include/llvm/ADT/APInt.h
===
--- llvm/include/llvm/ADT/APInt.h
+++ llvm/include/llvm/ADT/APInt.h
@@ -1506,6 +1506,11 @@
   /// equivalent of the string given by \p str.
   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
 
+  /// Get the bits that are sufficient to represent the string value. This may
+  /// over estimate the amount of bits required, but it does not require
+  /// parsing the value in the string.
+  static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
+
   /// The APInt version of the countLeadingZeros functions in
   ///   MathExtras.h.
   ///
Index: clang/test/Lexer/bitint-constants.c
===
--- /dev/null
+++ clang/test/Lexer/bitint-constants.c
@@ -0,0 +1,144 @@
+// RUN: %clang_cc1 -std=c2x

[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 5 inline comments as done.
aaron.ballman added inline comments.



Comment at: clang/lib/AST/StmtPrinter.cpp:1157
+  if (const auto *BT = Node->getType()->getAs()) {
+OS << (BT->isUnsigned() ? "uwb" : "wb");
+return;

erichkeane wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > Nit: Instead of BT->isUnsigned(), we already have isSigned above.
> > Good call!
> Isn't this reversed now?
It was, and the AST/bitint-suffix.c test caught it, but I missed it locally. 
I've corrected here (and verified we have test coverage for the code). Oops!


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

https://reviews.llvm.org/D120770

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/AST/StmtPrinter.cpp:1156
 
+  if (const auto *BT = Node->getType()->getAs()) {
+OS << (isSigned ? "wb" : "uwb");

You don't need BT here anymore (sorry for missing that!).


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

https://reviews.llvm.org/D120770

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 412509.
aaron.ballman marked 4 inline comments as done.
aaron.ballman added a comment.

getAs -> isa


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

https://reviews.llvm.org/D120770

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/AST/StmtPrinter.cpp
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/bitint-suffix.c
  clang/test/Lexer/bitint-constants-compat.c
  clang/test/Lexer/bitint-constants.c
  llvm/include/llvm/ADT/APInt.h
  llvm/lib/Support/APInt.cpp

Index: llvm/lib/Support/APInt.cpp
===
--- llvm/lib/Support/APInt.cpp
+++ llvm/lib/Support/APInt.cpp
@@ -502,12 +502,51 @@
   return retBits;
 }
 
+unsigned APInt::getSufficientBitsNeeded(StringRef Str, uint8_t Radix) {
+  assert(!Str.empty() && "Invalid string length");
+  size_t StrLen = Str.size();
+
+  // Each computation below needs to know if it's negative.
+  unsigned IsNegative = false;
+  if (Str[0] == '-' || Str[0] == '+') {
+IsNegative = Str[0] == '-';
+StrLen--;
+assert(StrLen && "String is only a sign, needs a value.");
+  }
+
+  // For radixes of power-of-two values, the bits required is accurately and
+  // easily computed.
+  if (Radix == 2)
+return StrLen + IsNegative;
+  if (Radix == 8)
+return StrLen * 3 + IsNegative;
+  if (Radix == 16)
+return StrLen * 4 + IsNegative;
+
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large. This avoids the assertion in the constructor. This
+  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
+  // bits in that case.
+  if (Radix == 10)
+return (StrLen == 1 ? 4 : StrLen * 64 / 18) + IsNegative;
+
+  assert(Radix == 36);
+  return (StrLen == 1 ? 7 : StrLen * 16 / 3) + IsNegative;
+}
+
 unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) {
-  assert(!str.empty() && "Invalid string length");
-  assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 ||
-  radix == 36) &&
- "Radix should be 2, 8, 10, 16, or 36!");
+  // Compute a sufficient number of bits that is always large enough but might
+  // be too large.
+  unsigned sufficient = getSufficientBitsNeeded(str, radix);
+
+  // For bases 2, 8, and 16, the sufficient number of bits is exact and we can
+  // return the value directly. For bases 10 and 36, we need to do extra work.
+  if (radix == 2 || radix == 8 || radix == 16)
+return sufficient;
 
+  // This is grossly inefficient but accurate. We could probably do something
+  // with a computation of roughly slen*64/20 and then adjust by the value of
+  // the first few digits. But, I'm not sure how accurate that could be.
   size_t slen = str.size();
 
   // Each computation below needs to know if it's negative.
@@ -519,28 +558,6 @@
 assert(slen && "String is only a sign, needs a value.");
   }
 
-  // For radixes of power-of-two values, the bits required is accurately and
-  // easily computed
-  if (radix == 2)
-return slen + isNegative;
-  if (radix == 8)
-return slen * 3 + isNegative;
-  if (radix == 16)
-return slen * 4 + isNegative;
-
-  // FIXME: base 36
-
-  // This is grossly inefficient but accurate. We could probably do something
-  // with a computation of roughly slen*64/20 and then adjust by the value of
-  // the first few digits. But, I'm not sure how accurate that could be.
-
-  // Compute a sufficient number of bits that is always large enough but might
-  // be too large. This avoids the assertion in the constructor. This
-  // calculation doesn't work appropriately for the numbers 0-9, so just use 4
-  // bits in that case.
-  unsigned sufficient
-= radix == 10? (slen == 1 ? 4 : slen * 64/18)
- : (slen == 1 ? 7 : slen * 16/3);
 
   // Convert to the actual binary value.
   APInt tmp(sufficient, StringRef(p, slen), radix);
Index: llvm/include/llvm/ADT/APInt.h
===
--- llvm/include/llvm/ADT/APInt.h
+++ llvm/include/llvm/ADT/APInt.h
@@ -1506,6 +1506,11 @@
   /// equivalent of the string given by \p str.
   static unsigned getBitsNeeded(StringRef str, uint8_t radix);
 
+  /// Get the bits that are sufficient to represent the string value. This may
+  /// over estimate the amount of bits required, but it does not require
+  /// parsing the value in the string.
+  static unsigned getSufficientBitsNeeded(StringRef Str, uint8_t Radix);
+
   /// The APInt version of the countLeadingZeros functions in
   ///   MathExtras.h.
   ///
Index: clang/test/Lexer/bitint-constants.c
===
--- /dev/null
+++ clang/test/Lexer/bitint-constants.c
@@ -0,0 +1,144 @@
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify -Wno-unused 

[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/AST/StmtPrinter.cpp:1156
 
+  if (const auto *BT = Node->getType()->getAs()) {
+OS << (isSigned ? "wb" : "uwb");

erichkeane wrote:
> You don't need BT here anymore (sorry for missing that!).
No worries, I should have caught that as well. I've corrected it.


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

https://reviews.llvm.org/D120770

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


[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

Would love someone to check out the APInt changes to confirm it is 'doing the 
right thing', but as far as I can tell it is right (and I'm just not confident 
enough to say so :D).


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

https://reviews.llvm.org/D120770

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


[PATCH] D23934: Add a -ffixed-date-time= flag that sets the initial value of __DATE__, __TIME__, __TIMESTAMP__

2022-03-02 Thread Ed Maste via Phabricator via cfe-commits
emaste added a comment.
Herald added a project: All.

The original author appears to have given up on it. Someone will need to rebase 
and work on pushing it forward


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

https://reviews.llvm.org/D23934

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


[PATCH] D119609: [Clang][Sema] Don't act on ReturnStmt when parsing the lambda declarator.

2022-03-02 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.
Herald added a project: All.

Does this break a case like this? https://godbolt.org/z/Tc9Ko7hWY

it seems the problem is with the Expression statements, and I'm not sure why we 
are doing "ActOnCapScopeReturnStmt" when we aren't really in a capture scope 
anymore, right?  I guess we properly diagnose the use of a capture in this 
scope, but I don't think we should be here in the 1st place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119609

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


[PATCH] D119147: [AIX][clang][driver] Check the command string to the linker for exportlist opts

2022-03-02 Thread Digger Lin via Phabricator via cfe-commits
DiggerLin updated this revision to Diff 412516.
DiggerLin marked an inline comment as done.
Herald added a project: All.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119147

Files:
  clang/include/clang/Driver/Job.h
  clang/lib/Driver/Job.cpp
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.c

Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -596,7 +596,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LD-LIBSTDCXX %s
 // CHECK-LD-LIBSTDCXX: LLVM ERROR: linking libstdc++ unimplemented on AIX
 
-// Check powerpc64-ibm-aix7.1.0.0, 32-bit. -shared.
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared.
 // RUN: %clangxx -x c++ -no-canonical-prefixes %s 2>&1 -### \
 // RUN:-resource-dir=%S/Inputs/resource_dir \
 // RUN:-shared \
@@ -604,9 +604,24 @@
 // RUN:--sysroot %S/Inputs/aix_ppc_tree \
 // RUN:-unwindlib=libunwind \
 // RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared (with exp option strings in other opt).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir \
+// RUN:-shared \
+// RUN:-target powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-ccc-install-dir %T/open_xl_aix_install/opt/IBM/openxlC/%open_xl_vrm/bin \
+// RUN:-unwindlib=libunwind \
+// RUN:-Wl,-Z/expall/expfull/a-bE:/a-bexport:/ \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED %s
+
 // CHECK-LD32-SHARED: {{.*}}clang{{.*}}" "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0"
 // CHECK-LD32-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-LD32-SHARED: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-SHARED: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED: "--export-symbols"
+// CHECK-LD32-SHARED: "-X" "32"
 // CHECK-LD32-SHARED: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD32-SHARED: "-bM:SRE"
 // CHECK-LD32-SHARED: "-bnoentry"
@@ -623,6 +638,56 @@
 // CHECK-LD32-SHARED: "-lm"
 // CHECK-LD32-SHARED: "-lc"
 
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list.
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir \
+// RUN:-shared \
+// RUN:-target powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-ccc-install-dir %T/open_xl_aix_install/opt/IBM/openxlC/%open_xl_vrm/bin \
+// RUN:-Wl,-bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list (no -Wl, variant).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir \
+// RUN:-shared \
+// RUN:-target powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-ccc-install-dir %T/open_xl_aix_install/opt/IBM/openxlC/%open_xl_vrm/bin \
+// RUN:-bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// Check powerpc-ibm-aix7.1.0.0, 32-bit. -shared with export list (-Xlinker variant).
+// RUN: %clangxx -x c++ %s 2>&1 -### \
+// RUN:-resource-dir=%S/Inputs/resource_dir \
+// RUN:-shared \
+// RUN:-target powerpc-ibm-aix7.1.0.0 \
+// RUN:--sysroot %S/Inputs/aix_ppc_tree \
+// RUN:-ccc-install-dir %T/open_xl_aix_install/opt/IBM/openxlC/%open_xl_vrm/bin \
+// RUN:-Xlinker -bE:input.exp \
+// RUN:   | FileCheck --check-prefix=CHECK-LD32-SHARED-EXPORTS %s
+
+// CHECK-LD32-SHARED-EXPORTS: {{.*}}clang{{.*}}" "-cc1" "-triple" "powerpc-ibm-aix7.1.0.0"
+// CHECK-LD32-SHARED-EXPORTS: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-LD32-SHARED-EXPORTS: "-isysroot" "[[SYSROOT:[^"]+]]"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "{{.*}}llvm-nm"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-X"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "32"
+// CHECK-LD32-SHARED-EXPORTS: "{{.*}}ld{{(.exe)?}}"
+// CHECK-LD32-SHARED-EXPORTS: "-bM:SRE"
+// CHECK-LD32-SHARED-EXPORTS: "-bnoentry"
+// CHECK-LD32-SHARED-EXPORTS: "-b32"
+// CHECK-LD32-SHARED-EXPORTS: "-bpT:0x1000" "-bpD:0x2000"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "[[SYSROOT]]/usr/lib{{/|}}crti.o"
+// CHECK-LD32-SHARED-EXPORTS: "-b{{(" ")?}}E:input.exp"
+// CHECK-LD32-SHARED-EXPORTS-NOT: "-bE:{{[^"]+}}"
+// CHECK-LD32-SHARED-EXPORTS: "-lc++"
+// CHECK-LD32-SHARED-EXPORTS: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aix{{/|}}libclang_rt.builtins-powerpc.a"
+// CHECK-LD32-SHARED-EXPORTS: "-lm"
+// CHECK-LD32-SHARED-EXPORTS: "-lc"
+
 // Check powerpc64-ibm-aix7.1.0.0, 64-bit. -shared.
 // RUN: %clangxx -x c++ -no-canonical-prefixes %s 2>&1 -### 

  1   2   >